Henry_234 @ 2023-07-29 13:15:42
#include<bits/stdc++.h>
using namespace std;
long long b[100005],m,aa,a[10000005],n;
int ef(int num){
int L=0,R=n-1;
int mid=(L+R)/2;
while(L<=R){
mid=(L+R)/2;
if(b[mid]==num){
return num;
}
else if(b[mid]>num){
R=mid-1;
}
else if(b[mid]<num){
L=mid+1;
}
}
if(num-b[L-1]<b[L]-num){
return b[L-1];
}
else return b[L];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int num=0;
cin>>m>>n;
for(int i=0;i<m;i++){
cin>>b[i];
}
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(b,b+m);
for(int i=0;i<n;i++){
aa=a[i];
if(b[0]>=aa){
num+=b[0]-aa;
}
else if(b[n-1]<=aa){
num+=aa-b[n-1];
}
else{
if(ef(aa)<=aa) num+=aa-ef(aa);
else num+=ef(aa)-aa;
}
}
cout<<num;
return 0;
}
by winner_0207_AFO @ 2023-07-29 13:28:30
c++
#include<bits/stdc++.h>
using namespace std;
int n,m,a[100005];
long long ans;
long long find(int num){
int l = 1,r = n;
while(r - l > 1){
int mid = (l + r) >> 1;
if(a[mid] > num) r = mid;
else if(a[mid] < num) l = mid;
else return 0;
}
int t1 = abs(a[l] - num),t2 = abs(a[r] - num);
return t1 < t2 ? t1 : t2;
}
int main(){
cin>>n>>m;
for(int i = 1;i <= n;i++) cin>>a[i];
stable_sort(a + 1,a + 1 + n);
for(int i = 1;i <= m;i++){
int num;
cin>>num;
ans += find(num);
}
cout<<ans;
return 0;
}
by 违规用户名777764 @ 2023-07-29 13:34:49
#include <iostream>
#include <algorithm>
#define int long long
using namespace std;
int a[100010];
bool cmp(int x, int y)
{
return x < y;
}
signed main()
{
int m, n;
cin >> m >> n;
for (int i = 1; i <= m; ++i) cin >> a[i];
sort(a + 1, a + m + 1, cmp);
int ans = 0;
while (n--)
{
int x;
cin >> x;
int p = lower_bound(a + 1, a + m + 1, x) - a;
if (p == m + 1)
{
ans += x - a[m];
}
else
{
if (p == 1) ans += a[1] - x;
else ans += min(abs(a[p] - x), abs(x - a[p - 1]));
}
}
cout << ans << endl;
return 0;
}
by lijuncheng_1207 @ 2023-08-03 18:52:02
@Henry_234
#include <bits/stdc++.h>
using namespace std;
const int N=1e8;
long long n,a[N],x,m,cnt;
int main(){
cin>>n>>m;;
for(int i=1;i<=n;i++){
cin>>a[i];
}
sort(a+1,a+n+1);
while(m--){
cin>>x;
int l=1,r=n;
while(l+1<r){
int mid=(l+r)>>1;
if(a[mid]>=x)
r=mid;
else
l=mid;
}
cnt+=abs(a[l]-x)<=abs(a[r]-x)?abs(a[l]-x):abs(a[r]-x);
}
cout<<cnt;
return 0;
}