230syh @ 2022-11-12 11:50:13
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,sum=0,l,r,mid,tmp;
cin>>n>>m;
int school[n],student[m];
for(int i=0;i<n;i++)
cin>>school[i];
for(int i=0;i<m;i++)
cin>>student[i];
sort(school,school+n);
for(int i=0;i<m;i++){
l=0,r=n;
while(l<=r){
mid=(l+r)/2;
if(school[mid]>student[i])
r=mid-1;
else if(school[mid]<student[i])
l=mid+1;
else
break;
}
tmp=abs(school[mid]-student[i]<abs(school[mid+1]-student[i]))?school[mid]-student[i]:abs(school[mid+1]-student[i]);
tmp=tmp<abs(school[mid-1]-student[i])?tmp:abs(school[mid-1]-student[i]);
sum+=tmp;
}
cout<<sum;
}
可能有点乱,
你们可以买点西瓜,准备吃席
by LyuCx @ 2022-11-13 19:59:19
#include<bits/stdc++.h>
using namespace std;
int main(){
long long n,m,sum=0,l,r,mid,tmp;
cin>>n>>m;
long long school[n],student[m];
for(int i=0;i<n;i++)
cin>>school[i];
for(int i=0;i<m;i++)
cin>>student[i];
sort(school,school+n);
for(int i=0;i<m;i++){
l=0,r=n-1;
while(l<=r){
mid=(l+r)/2;
if(school[mid]>student[i])
r=mid-1;
else if(school[mid]<student[i])
l=mid+1;
else
break;
}
tmp=abs(school[mid]-student[i]);
if(mid>0) tmp=min(tmp,abs(school[mid-1]-student[i]));
if(mid<n-1) tmp=min(tmp,abs(school[mid+1]-student[i]));
sum+=tmp;
}
cout<<sum;
}
把变量定义成long long
mid要判一下防止出现数组下标问题
然后就AC了
by 230syh @ 2022-12-03 12:13:21
@LiuCx2009 谢谢