向晚 @ 2021-08-25 16:34:04
回来复习二分发现这道题没写 结果过不去
蒟蒻求帮助
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int m,n,a[100005],b[100005],ans;
int main(){
cin>>m>>n;
for(int i=1;i<=m;i++) cin>>a[i];
sort(a+1,a+m+1);
for(int i=1;i<=n;i++) cin>>b[i];
for(int i=1;i<=n;i++){
int l=0,r=m;
while(l<r){
int mid=(l+r)/2;
if(a[mid]<=b[i]) l=mid+1;
else r=mid;
}
ans+=min(abs(a[l]-b[i]),abs(a[l-1]-b[i]));
}
cout<<ans;
return 0;
}
by cqbztz2 @ 2021-08-25 16:45:17
@向晚
ans+=min(abs(a[l]-b[i]),abs(a[l-1]-b[i]));
这句话之前需要加上
if(b[i]<=a[1]){ans+=a[1]-b[i];}
by 向晚 @ 2021-08-25 16:46:52
为什么啊
by cqbztz2 @ 2021-08-25 16:49:12
@向晚
b[i]有可能和初始值为0的a[0]最接近
by 向晚 @ 2021-08-25 16:49:32
谢谢
by Li_Xin_xian @ 2022-02-03 20:38:26
直接把a[0]=999999;