jikky @ 2024-07-05 16:10:50
#include<bits/stdc++.h>
using namespace std;
long long st[1000003];
long long sch[1000003];
long long line[1000003];
int main(){
unsigned long long m,n;
scanf("%lld%lld",&m,&n);
for(int i=1;i<=m;i++){
scanf("%lld",&sch[i]);
}
sort(sch+1,sch+m+1);
for(int i=1;i<=n;i++){
scanf("%lld",&st[i]);
}
sort(st+1,st+n+1);
for(int i=1;i<m;i++){
line[i]=(sch[i]+sch[i+1])/2;
//cout<<line[i]<<" ";
}
/*
for(int i=1;i<=n;i++){
//line[i]=(sch[i]+sch[i+1])/2;
cout<<st[i]<<" ";
}
*/
unsigned long long cnt=1;
unsigned long long ans=0;
for(int i=1;i<=n;i++){
if(st[i]<=line[cnt]){
ans+=abs(sch[cnt]-st[i]);
}
else{
while(st[i]>line[cnt+1]&&cnt<m){
cnt++;
}
if(st[i]<=line[cnt]){
ans+=abs(sch[cnt]-st[i]);
}
else{
ans+=abs(sch[cnt+1]-st[i]);
}
}
}
cout<<ans;
return 0;
}
by zldx @ 2024-07-18 15:12:45
#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;
}
@jikky
by jikky @ 2024-07-18 19:05:26
@zldx Thx