_mei_tou_nao_ @ 2024-11-08 15:51:25
#include <bits/stdc++.h>
using namespace std;
const int N = 1e8 + 5;
long long n, m, a[N], b[N], mid, ans;
int main() {
cin >> m >> n;
for (int i = 1; i <= m; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
cin >> b[i];
}
sort(a + 1, a + m + 1);
for (int j = 1; j <= n; j++) {
long long l = 0, r = n + 1;
while (l < r) {
mid = (l + r) / 2;
if (a[mid] <= b[j]) {
l = mid + 1;
} else {
r = mid;
}
}
ans += min(abs(a[l] - b[j]), abs(a[l - 1] - b[j]));
}
cout << ans;
return 0;
}
by dqh_0616 @ 2024-11-08 16:20:24
输入数据太大,循环会TLE,建议用二分。
by dqh_0616 @ 2024-11-08 16:37:42
#include<bits/stdc++.h>
using namespace std;
int n,m,a[100000],b[100000];
long long ans;
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
for(int i=0;i<m;i++)
scanf("%d",&b[i]);
sort(a,a+n);
for(int i=0;i<m;i++){
int fs=lower_bound(a,a+n,b[i])-a;
if(fs==n)
ans+=b[i]-a[n-1];
else if(fs==0)
ans+=a[0]-b[i];
else
ans+=min(abs(a[fs]-b[i]),abs(b[i]-a[fs-1]));
}
printf("%ld",ans);
return 0;
}
by _mei_tou_nao_ @ 2024-11-08 23:15:38
@dqh0616 其实我用循环打了个二分,下次应该说清楚不是TLE的