1. 题目描述
2. 思路分析
将每个学校的分数线用sort()升序排序,再二分查找每个学校的分数线,通过二分找到每个同学估分附近的分数线。
最后特判一下:
如果每个同学的估分都比最低分数线低。直接让最低的分数线减同学估分,然后取绝对值即可,
如果每个同学的估分都比最高分数线高。直接让最高的分数线减同学估分,然后取绝对值即可。
3. 代码实现
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5 + 10;
int a[N], b[N], n, m;
ll sum;
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 i = 1; i <= n; i++)
{
int l = 0, r = m + 1;
while (l + 1 < r)
{
int mid = (l + r) >> 1;
if (a[mid] <= b[i]) l = mid;
else r = mid;
}
if (b[i] <= a[1]) //特判同学估分比分数线数都低的情况
sum += abs(a[1] - b[i]);
else if (b[i] >= a[m]) //特判同学估分比分数线都高的情况
sum += abs(a[m] - b[i]);
else
sum += min(abs(a[l] - b[i]), abs(a[r] - b[i]));
}
cout << sum << endl;
return 0;
}