求助,#1没过

P1678 烦恼的高考志愿

kanjian1 @ 2024-08-26 16:21:21

#include<bits/stdc++.h>
using namespace std;
int a[1001],b[1001];
int main()
{
    int n,m,i;
    cin>>n>>m;
    for(i=1;i<=n;i++)
        cin>>a[i];
    for(i=1;i<=m;i++)
        cin>>b[i];
    sort(a+1,a+n+1);
    int ans=0;
    for(i=1;i<=m;i++)
    {
        int l=0,r=n+1;
        while(l<r)
        {
            int mid=(l+r)/2;
            if(a[mid]<=b[i])
                l=mid+1;
            else
                r=mid;
        }
        if(b[i]<=a[1])
            ans+=a[1]-b[i];
        else
            ans+=min(abs(a[l-1]-b[i]),abs(a[l]-b[i]));
    }
    cout<<ans;
    return 0;
}

by yingxi @ 2024-08-26 16:26:57

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5+5;
int a[N],n,m,x,sum;
int find(int x)
{
    int lt=0,rt=m+1;
    a[0]=-1e9;
    while(lt+1 < rt)
    {
        int mid=(lt+rt)/2;
        if(x==a[mid])
        {
            return 0;
        }
        if(a[mid] > x)
        {
            rt=mid;
        }
        else
        {
            lt=mid;
        }
    }
    return min(abs(a[lt]-x),abs(a[rt]-x));
} 
signed main()
{
    cin>>m>>n;
    for(int i=1;i<=m;i++)
    {
        cin>>a[i];
    }
    sort(a+1,a+m+1);
    while(n--)
    {
        cin>>x;
        sum+=find(x);
    }
    cout<<sum;
    return 0;
} 

by yingxi @ 2024-08-26 16:27:46

可以对照一下 @kanjian1


by kanjian1 @ 2024-08-26 16:48:04

@yingxi 感谢


by khfjg764 @ 2024-09-05 23:24:55

最后一组数据需要开long long


|