苏子恒阳 @ 2020-10-02 20:40:25
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
#define _int long
_int n,m,a[1000001],b;
_int rfen(_int x)
{
_int l=1,r=n;
while(l<r)
{
_int mid=(r+l)/2;
if(a[mid]>=x)r=mid;
else l=mid+1;
}
return l;
}
int main(){
_int ans=0;
scanf("%d%d",&n,&m);
for(_int i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+n+1);
for(_int i=1;i<=m;i++)
{
scanf("%d",&b);
_int c=rfen(b);
if(c==1)ans+=a[c]-b;
else if(a[c]==b)ans+=0;
else if(a[c]-b<b-a[c-1])ans+=a[c]-b;
else ans+=fabs(a[c-1]-b);
}
cout<<ans;
}
by shenmadongdong @ 2020-10-02 20:42:59
long long 不用%lld读?
by 苏子恒阳 @ 2020-10-02 20:47:34
@shenmadongdong 天哪大佬!!!!!!!!我真的太感谢您了,这么快给我回复,还一语道破天机;
by sunyizhe @ 2021-07-23 12:02:48
@苏子恒阳
#include <bits/stdc++.h>
using namespace std;
int a[100002],m,n,q,sum;
int main()
{
int x,wa,wb;
cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+n+1);
for(int i=1;i<=m;i++)
{
wa=wb=INT_MAX;
cin>>x;
int r=lower_bound(a+1,a+n+1,x)-a;
int l=upper_bound(a+1,a+n+1,x)-a-1;
if(l>=1)wa=abs(x-a[l]);
if(r<=n)wb=abs(a[r]-x);
sum+=min(wa,wb);
}
cout<<sum<<endl;
return 0;
}