QYlucky @ 2023-07-24 17:52:13
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
int main(){
int m,n,a[10002],b[10002];
cin>>m>>n;
for(int i=0;i<m;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
cin>>b[i];
}
sort(a,a+m);
int ans=0;
for(int i=0;i<n;i++){
int l=0,r=m-1,mid;
int compare=abs(a[0]-b[i]);
while(l<r){
mid=l+(r-l)/2;
if(abs(a[mid]-b[i])<compare){
l=mid;
compare=abs(a[mid]-b[i]);
}
else r=mid-1;
}
ans=ans+compare;
}
cout<<ans;
return 0;
}
by Lycd0719 @ 2023-07-31 16:00:52
试一试lower_bound
by Lycd0719 @ 2023-07-31 16:12:15
c++
#include<bits/stdc++.h>
using namespace std;
long long s;
int a[10100000];
int i,j,k;
int main(){
int n,m;
cin>>n>>m;
for(i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
long long ans=0;
for(i=1;i<=m;i++){
int x;
cin>>x;
int l,r;
r=lower_bound(a,a+n,x)-a;
if(r==0)l==0;
else {
l=r-1;
}
int d;
d=min(abs(a[r]-x),abs(a[l]-x));
s+=d;
}
//if(ans!=100000000000)cout<<5865;
cout<<s<<endl;
}