steve255 @ 2023-02-27 18:53:40
#include<bits/stdc++.h>
using namespace std;
int a[1000002];
int b[1000002];
int main(){
int n,m;
cin>>m>>n;
for(int i=1;i<=m;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
cin>>b[i];
}
int cnt=0;
sort(a+1,a+1+n);
for(int i=1;i<=n;i++){
int key=b[i];
int tmp=lower_bound(a+1,a+1+n,key)-a;
int f=tmp-1;
if(tmp-a[i]>a[i]-f)cnt+=a[i]-f;
else cnt+=tmp-a[i];
}
cout<<cnt;
return 0;
}
by pxlamda @ 2023-03-03 21:22:44
for(int i=1;i<=n;i++){
int key=b[i];
int tmp=lower_bound(a+1,a+1+n,key)-a;
int f=tmp-1;
if(tmp-a[i]>a[i]-f)cnt+=a[i]-f;
else cnt+=tmp-a[i];
}
改成
for (long long i = 1; i <= m; i++) {
long long key = b[i];
long long tmp = lower_bound(a + 1, a + 1 + n, key) - a;
long long f = tmp - 1;
if (f == 0) {
cnt = cnt + abs(a[tmp] - b[i]);
}
else {
cnt = cnt + min(abs(a[tmp] - b[i]), abs(a[f] - b[i]));
}
}
cnt必须是long long才能过最后一个测试点。 我试过了可以AC.