https://codeforces.com/problemset/problem/439/D
思路:不是很能想到贪心阿。但是看这个范围。感觉像二分枚举。
首先定一个假设最终到达的值为temp。那么可以得出Ans=Σtmp-a【i】(a【i】<tmp)+Σb【i】-tmp(b【i】>tmp);
答案在temp+1/+2/-1/-2都会变大。是个单峰函数。
于是上三分
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL a[maxn],b[maxn];
LL check(LL x,LL n,LL m){
LL sum=0;
for(LL i=1;i<=n;i++){
if(a[i]<x) sum+=x-a[i];
}
for(LL i=1;i<=m;i++){
if(b[i]>x) sum+=b[i]-x;
}
return sum;
}
int main(void)
{
LL n,m;n=read();m=read();
LL l=1e18;
for(LL i=1;i<=n;i++){
a[i]=read();
l=min(l,a[i]);
}
LL r=-1;
for(LL i=1;i<=m;i++){
b[i]=read();
r=max(r,b[i]);
}
LL ans=0;
///三分
while(l<=r){
LL len=(r-l)/3;
LL lm=l+len;LL rm=r-len;
LL flm=check(lm,n,m);LL frm=check(rm,n,m);
if(flm>=frm){
ans=flm;
l=lm+1;
}
else{
ans=frm;
r=rm-1;
}
}
printf("%lld\n",ans);
return 0;
}