题目链接:烦恼的高考志愿 - 洛谷
贪心+二分答案
要求每个同学匹配距离自己分数最近的学校, 先对学校进行排序, 然后二分学校的编号, 时刻更新mmin(最小差值)就好了
注意边界问题!注意边界问题!注意边界问题!
ac代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstring>
#include <string>
#include <stack>
#include <deque>
#include <map>
#include <set>
using namespace std;
#define ll long long
#define endl "\n"
#define rep(i, a, b) for (ll i = (a); i <= (b); i++)
#define repr(i, a, b) for (ll i = (a); i < (b); i++)
#define rrep(i, a, b) for (ll i = (b); i >= (a); i--)
#define rrepr(i, a, b) for (ll i = (b); i > (a); i--)
#define min(a,b) (a)<(b)?(a):(b)
#define max(a,b) (a)>(b)?(a):(b)
ll cnt,n,m,t,ans,ant;
const int N=1e5+10;
ll sc[N];
ll st[N];
string str;
inline ll read()
{
char c = getchar();int x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}//是符号
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}//是数字
return x*s;
}
void solve()
{
n=read();
m=read();
rep(i,1,n) sc[i]=read();
rep(i,1,m) st[i]=read();
sort(sc+1,sc+n+1);
rep(i,1,m)
{
ll l=1,r=n+1;
ll mmin=0x3f3f3f3f;
while(l<=r)
{
ll mid=l+r>>1;
if(sc[mid]==st[i])
{
mmin=0;
break;
}
else if(sc[mid]<st[i])
{
l=mid+1;
mmin=min(mmin,abs(sc[mid]-st[i]));
}
else r=mid-1,mmin=min(mmin,abs(sc[mid]-st[i]));
}
// cout<<st[i]<<" "<<sc[cnt]<<endl;
ans+=mmin;
}
cout<<ans;
return;
}
int main()
{
solve();
return 0;
}