jy20091121 @ 2024-02-16 08:20:49
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,m;
int ans;
int a[1010040];
signed 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++){
int x;
cin>>x;
int l=1,r=n;
int k=1e9;
while(l<=r){
int mid=l+r>>1;
if(a[mid]>=x){
r=mid-1;
k=min(k,mid);
}
else{
l=mid+1;
}
}
if(k>1)
ans+=min(a[k]-x,x-a[k-1]);
else{
ans+=a[k]-x;
}
}
cout<<ans<<endl;
return 0;
}
by DReAM__LoveR @ 2024-02-16 08:57:05
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,m;
int ans;
int a[1010040];
signed main(){
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i];
sort(a+1,a+n+1);
int x;
for(int i=1;i<=m;i++){
cin>>x;
int l=1,r=n;
int k=1e9;
while(l<=r){
int mid=l+r>>1;
if(a[mid]>=x){
r=mid-1;
}
else{
l=mid+1;
}
k = min(abs(a[mid]-x),k);
}
ans += k;
}
cout<<ans<<endl;
return 0;
}
改了第 25 行和 27 行,其实在二分过程中直接找最小值就行,二分后再找会有一些边界问题,这样就过了
by jy20091121 @ 2024-02-16 11:13:29
@DReAM__LoveR 感谢 此贴结