50,求改

P1678 烦恼的高考志愿

LYL__1107 @ 2024-08-28 15:08:42

#include<bits/stdc++.h>
using namespace std;
int n,m,mm[100010],nn[100010];
int l,r,mid,s,minn;
int main(){
    cin>>m>>n;
    for(int i=1;i<=m;i++) cin>>mm[i];
    for(int i=1;i<=n;i++) cin>>nn[i];
    sort(mm+1,mm+m+1);
    for(int i=1;i<=n;i++){
        l=1;
        r=m;
        minn=1000100;
        while(l<r){

            mid=(l+r)/2;
            if(mm[mid]<nn[i]){
                minn=min(minn,abs(nn[i]-mm[mid]));
                l=mid+1;

            }
            else{
                r=mid;
                minn=min(minn,abs(nn[i]-mm[mid]));
            }

        }
        s+=minn;
    }
    cout<<s;
}

by yhcorey @ 2024-08-28 15:23:43

@LYL__1107

#include<bits/stdc++.h>
using namespace std;
int main(){
    long long m,n;
    cin>>m>>n;
    long long a[m+1]={0},b[n+1]={0};
    long long s=0;
    for(int i=1;i<=m;i++){
        cin>>a[i];
        s+=a[i];
    }
    for(int i=1;i<=n;i++){
        cin>>b[i];
    }
    sort(a+1,a+1+m);
    sort(b+1,b+1+n);
    long long ans=0;
    for(int i=1;i<=n;i++){
        long long head=1;
        long long tail=m;
        long long mid=m/2;
        bool flag=true;
        long long c=m;
        while(head<=tail){
            if(a[mid]>b[i]){
                if(mid<c) c=mid;
                flag=false;
                tail=mid-1;
            }
            else head=mid+1;
            mid=(head+tail)/2;
        }
        long long d=c-1;
        if(d!=0) ans+=min(abs(a[c]-b[i]),abs(a[d]-b[i]));
        else ans+=abs(a[c]-b[i]);
    }
    cout<<ans;
    return 0;
}

by LYL__1107 @ 2024-08-28 15:33:44

谢谢啦 yhcorey


|