Jason_yinkai @ 2022-07-29 16:08:36
#include<bits/stdc++.h>
using namespace std;
int stu[100005],sch[100005];
int m,n;
int ans;
int main(){
cin>>m>>n;
for(int i = 1;i <= m;i++){
cin>>sch[i];
}
for(int i = 1;i <= n;i++){
cin>>stu[i];
}
sort(sch + 1,sch + m + 1);
for(int i = 1;i <= n;i++){
int l = 0,r = m + 1;
int a = 1e9 - 1;
while(l < r){
int mid = (l + r) / 2;
if(sch[mid] == stu[i]){
a = 0;
break;
}
else if(sch[mid] < stu[i]){
l = mid + 1;
a = min(a,abs(sch[mid] - stu[i]));
}
else {
r = mid;
a = min(a,abs(sch[mid] - stu[i]));
}
}
ans += a;
}
cout<<ans;
}
测试点
by JustinXiaoJunyang @ 2022-07-29 16:17:40
@Jason_yinkai
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int a[100005], b[100005];
int main()
{
int m, n;
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);
int sum = 0;
for (int i = 1; i <= n; i++)
{
int l = 1, r = m;
if (b[i] >= a[m])
{
sum += (b[i] - a[m]);
continue;
}
if (b[i] <= a[1])
{
sum += (a[1] - b[i]);
continue;
}
int ans = -1;
while (l <= r)
{
int mid = (l + r) / 2;
if (a[mid] >= b[i])
{
ans = mid;
r = mid - 1;
}
else
{
l = mid + 1;
}
}
sum += min(b[i] - a[ans - 1], a[ans] - b[i]);
}
cout << sum << endl;
return 0;
}
求关注~
by JustinXiaoJunyang @ 2022-07-29 16:18:26
@Jason_yinkai 你读入是 1 开始,二分也要 1 开始
by Jason_yinkai @ 2022-07-29 21:26:33
@JustinXiaoJunyang 谢谢大佬,过了。