lzsy0313 @ 2024-07-06 11:53:08
#include <iostream>
#include <cmath>
#include <algorithm>
#define MAXN 100010
using namespace std;
long long m,n,s[100010],t[100010],ans=0;
int find(int x){
long long l=1,r=m,mid;
while(l<r){
mid=(l+r) >>1;
if(x<=s[mid]){
r=mid;
}else{
l=mid+1;
}
}
return min(abs(s[mid]-x),abs(s[mid+1]-x));
}
int main(){
cin >>m >>n;
for(int i=1;i<=m;i++) cin >>s[i];
for(int i=1;i<=n;i++) cin >>t[i];
sort(s+1,s+n+1);
for(int i=1;i<=n;i++){
ans+=find(t[i]);
}
cout <<ans <<endl;
return 0;
}
by zldx @ 2024-07-18 15:10:04
#include<bits/stdc++.h>
using namespace std;
typedef long long T;
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
T n,m,sum=0;
cin>>n>>m;
vector<T>v1(n);
vector<T>v2(m);
for(T i=0;i<n;i++){
cin>>v1[i];
}
sort(v1.begin(), v1.end());
for(T i=0;i<m;i++){
cin>>v2[i];
}
sort(v2.begin(), v2.end());
for(T i=0;i<m;i++){
if(v2[i]<v1[0]){
sum+=v1[0]-v2[i];
continue;
}if(v2[i]>v1[n-1]){
sum+=v2[i]-v1[n-1];
continue;
}
T r,l,mid;
l=0;
r=n-1;
while(l<r){
mid=(l+r+1)/2;
if((v1[mid]<v2[i]&&v1[mid+1]>v2[i])||(v1[mid]>v2[i]&&v1[mid-1]<v2[i])){
if(v1[mid]<v2[i]&&v1[mid+1]>v2[i]){
sum+=min(v2[i]-v1[mid],v1[mid+1]-v2[i]);
break;
}else{
sum+=min(v2[i]-v1[mid-1],v1[mid]-v2[i]);
break;
}
}else{
if(v1[mid]<v2[i]){
l=mid+1;
}if(v1[mid]>v2[i]){
r=mid-1;
}if(v1[mid]==v2[i]){
break;
}
}
}
}
cout<<sum;
return 0;
}