样例3和样例9WA,求助

P1678 烦恼的高考志愿

土木1909陈冠吾 @ 2021-02-28 10:56:50

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

|