lijince6666 @ 2022-12-03 21:17:19
#include<bits/stdc++.h>
using namespace std;
int a[100050],n,m,q,ans;
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
sort(a+1,a+n+1);
for(int i=1;i<=m;i++){
cin>>q;
int dizhi=lower_bound(a+1,a+n+1,q)-a;
ans+=min(a[dizhi]-q,q-a[dizhi-1]);
}
cout<<ans<<endl;
}
思路有没有什么问题
by kkkk2022 @ 2022-12-03 21:25:57
#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;
}
by zhczcg314 @ 2023-02-22 18:02:23
@lijince6666 同问,思路一样