P1678 烦恼的高考志愿 - 洛谷 | 计算机科学教育新生态 https://www.luogu.com.cn/problem/P1678
#include<bits/stdc++.h>
#define N (int)1e6+5
using namespace std;
int a[N];
int score,dis;
void search(int l,int r) {
if (a[l] >= score) {
dis = abs(a[l] - score);
return;
}
if (a[r] <= score) {
dis = abs(a[r] - score);
return;
}
if (r - l == 1) {
dis = min(abs(a[r] - score), abs(a[l] - score));
return;
}
if (l >= r) {//为什么要有这个if呢
dis = abs(a[r] - score);
return;
}
int mid = (l + r)/ 2;
if (a[mid] > score) search(l, mid);
else search(mid, r);
}
int main() {
int m, n, i, ans;
ans = 0;
cin >> m >> n;
for (i = 0; i < m; i++) {
cin >> a[i];
}
sort(a, a + m);
for (i = 0; i < n; i++) {
cin >> score;
search(0, m - 1);
ans += dis;
}
cout << ans << endl;
return 0;
}
谢谢大家