30分,只对了1,2,10,请大佬们看看☺

P1678 烦恼的高考志愿

一洛本谷通 @ 2022-01-23 14:21:49

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

by RicardoLu @ 2022-01-24 13:40:39

if(a[mid]<b) r=mid;
else l=mid+1;

你搞反了!还少了一个特判。
if(a[mid]==b) cout<<"0\n";
if(a[mid]<b) l=mid;
else r=mid;

by RicardoLu @ 2022-01-24 13:41:35

写函数不香吗???


|