fish_fish @ 2023-07-13 10:01:51
#include<bits/stdc++.h>
using namespace std;
int m,n,school[100005]={},score[100005]={},sum=0;
int test(int x,int l,int r,int ans1,int ans2){
int middle=(l+r)/2;
if(l>r){
int ans11,ans22;
if(school[ans1]-x>0) ans11=school[ans1]-x;
else ans11=x-school[ans1];
if(school[ans2]-x>0) ans22=school[ans2]-x;
else ans22=x-school[ans2];
if(ans11<ans22) return ans11;
else return ans22;
}
else if(school[middle]>x) return test(x,l,middle-1,ans2,middle);
else if(school[middle]<x) return test(x,middle+1,r,ans2,middle);
else return 0;
}
int main(){
cin>>m>>n;
for(int i=0;i<m;i++) cin>>school[i];
for(int i=0;i<n;i++) cin>>score[i];
sort(school,school+m);
for(int i=0;i<n;i++){
sum+=test(score[i],0,n-1,0,0);
}
cout<<sum<<endl;
return 0;
}
by iBaeJuhyun @ 2023-07-13 11:08:18
首先是test函数引用时要用m-1而不是n-1;
然后呢sum会爆int要用long long
二分函数内部好像也有问题,但本蒟蒻不会改,建议使用stl库的lower_bound,(网上查一下就会了很简单的)
贴个代码
#include<bits/stdc++.h>
using namespace std;
inline int read() {int res=0;char ch;do ch=getchar();while(ch<'0' || ch>'9');while(ch>='0' && ch<='9') res=res*10+(ch&15), ch=getchar();return res;}
int m,n,a[100005];
long long sum;
int main(){
m=read(),n=read();
for(int i=0;i<m;i++) cin>>a[i];
sort(a,a+m);
for(int i=0,x,k;i<n;i++) k=read(),x=lower_bound(a,a+m,k)-a,sum+=(x?min(abs(a[x]-k),abs(a[x-1]-k)):abs(a[x]-k));
cout<<sum<<endl;
return 0;
}
by fish_fish @ 2023-07-13 13:47:31
@HanSohee 谢谢,已关