52hertz_yh @ 2024-05-08 13:07:42
#include<bits/stdc++.h>
using namespace std;
long long n,k;
long long a[10000007],b[10000007],ans,mid,c,d,e,q,o;
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+n+1);
for(int i=1;i<=k;i++)
cin>>b[i];
while(k)
{
int l=0,r=n;
while(l+1<r)
{
mid=(l+r)/2;
if(a[mid]>b[k])r=mid;
else l=mid;
}
e=abs(b[k]-a[mid-1]);
c=abs(b[k]-a[mid]);
d=abs(b[k]-a[mid+1]);
o=min(e,c);
q=min(o,d);
ans+=q;
k--;
}
cout<<ans<<endl;
return 0;
}
by luoruichen2012 @ 2024-05-26 09:51:09
献上蒟蒻拙码一份
#include<bits/stdc++.h>
using namespace std;
long long n,m,a[100005],b[100005],sum;
int find(int x){
long long l=1,r=n,ans=2e9;
while(l<=r){
long long mid=(l+r)/2;
if(a[mid]>x){
ans=min(ans,a[mid]-x);
r=mid-1;
}
else if(a[mid]<x){
ans=min(ans,x-a[mid]);
l=mid+1;
}
else return 0;
}
return ans;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)cin>>a[i];
sort(a+1,a+1+n);
for(int i=1;i<=m;i++){
cin>>b[i];
sum+=find(b[i]);
}
cout<<sum;
return 0;
}
by luoruichen2012 @ 2024-05-26 09:56:28
@52hertz_yh