20分求助!!!改了很多次还是错了!!谢谢大佬们!!!

P1678 烦恼的高考志愿

618xiaoliu @ 2023-12-22 16:56:31

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6+10;
int a[N],b[N];
signed main()
{
    int m,n;
    int sum = 0;
    cin>>m>>n;
    for(int i = 1;i<=m;i++){
        cin>>a[i];
    }
    if(m==1){
        for(int i = 1;i<=n;i++){
            cin>>b[i];
            sum+=abs(a[1]-b[i]);
        }
        cout<<sum<<endl;

        return 0;
    }
    sort(a+1,a+1+m);
    for(int i = 1;i<=n;i++){
        cin>>b[i];
        int l = 0,r = n+1;
        while(r-l>1){
            int mid = (l+r)>>1;
            if(a[mid]>b[i]){
                r = mid;
            }else{
                l = mid;
            }
        }
        if(b[i]<=a[1]){
            sum+=(a[1]-b[i]);
        }
        else{
            if(abs(a[r-1]-b[i])>abs(a[r]-b[i])){
                sum += abs(a[r]-b[i]);
            }else{
                sum += abs(a[r-1]-b[i]);
            }
        }
    }
    cout<<sum<<endl;

    return 0;
}

|