幽灵特工 @ 2020-09-21 13:00:14
#include <bits/stdc++.h>
using namespace std;
int m,n;
int sc[100001];//school
int st[100001];//students
int f(int k){
int l=0,r=m;
int mid;
while(l<r){
mid=(l+r)/2;
if(sc[mid]==k)return 0;
if(sc[mid]<k){
l=mid+1;
continue;
}
if(sc[mid]>k){
r=mid;
continue;
}
}
return min(abs(sc[l-1]-k),abs(sc[r]-k));
}
int main(){
cin>>m>>n;
for(int i=0;i<m;i++){
cin>>sc[i];
}
sort(sc,sc+m);
int sum=0;
int x;
for(int i=0;i<n;i++){
cin>>x;
sum+=f(x);
}
cout<<sum;
}
by 幽灵特工 @ 2020-09-21 13:05:28
找到原因了,f()的返回应该改为:
if(k<=sc[0])return sc[0]-k;
return min(abs(sc[l-1]-k),abs(sc[l]-k));