Christian_ @ 2024-04-07 13:30:34
#include <bits/stdc++.h>
using namespace std;
const int N=100100;
int c[N];
int n,m,s,d;
long long res=0;
void judge(int x){
int l=1,r=m;
if(c[l]>=s){
d=c[l]-s;
return;
}
if(c[r]<=s){
d=s-c[r];
return;
}
while(l+1<r){
int mid=(l+r)>>1;
if(c[mid]>=s) r=mid;
else l=mid;
}
d=min(s-c[r-1],c[r]-s);
return;
}
int main(){
scanf("%d%d",&m,&n);
for(int i=1;i<=m;i++) scanf("%d",&c[i]);
sort(c+1,c+m+1);
for(int i=1;i<=n;i++){
scanf("%d",&s);
judge(s);
res+=d;
}
printf("%d",res);
return 0;
}
by ycy1124 @ 2024-04-07 13:34:42
@Christian_
#include <bits/stdc++.h>
using namespace std;
const int N=100100;
int c[N];
int n,m,s,d;
long long res=0;
void judge(int x){
int l=1,r=m;
if(c[l]>=s){
d=c[l]-s;
return;
}
if(c[r]<=s){
d=s-c[r];
return;
}
while(l+1<r){
int mid=(l+r)>>1;
if(c[mid]>=s) r=mid;
else l=mid;
}
d=min(s-c[r-1],c[r]-s);
return;
}
int main(){
scanf("%d%d",&m,&n);
for(int i=1;i<=m;i++) scanf("%d",&c[i]);
sort(c+1,c+m+1);
for(int i=1;i<=n;i++){
scanf("%d",&s);
judge(s);
res+=d;
}
printf("%lld",res);//
return 0;
}
by ycy1124 @ 2024-04-07 13:35:50
@Christian_
输出long long类型时要用%lld
by Christian_ @ 2024-04-07 13:49:14
@ycy1124 哎呀忘记了,谢谢你