0分求调

P1678 烦恼的高考志愿

Yae__Miko @ 2024-12-22 14:32:39

#include<bits/stdc++.h>
#define endl "\n"
#define IO ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
typedef long long ll;
using namespace std;
const int maxn=1e6+10;
int a[maxn],n;

int check(int x){
    int l=1,r=n,ans=-1;

    while(l<=r){

        int mid=(l+r)/2;
        if(a[mid]==x) return mid;
        else if(a[mid]<x){

            ans=mid;
            l=mid+1;
        }

        else r=mid-1;
    }

    if(x<a[1]){
        return a[1]-x;
    }

    return min((x-a[ans]),(a[ans+1]-x));

}
int m;
int main(){
    IO;
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>a[i];
    sort(a+1,a+1+n);
    ll fd;
    ll cnt=0;
    for(int i=1;i<=m;i++){
        cin>>fd;
        //cout<<check(fd)<<' ';
        cnt+=check(fd);
    }
    cout<<cnt;
    return 0;
}

|