求,TLE

P1678 烦恼的高考志愿

xjx199 @ 2024-03-03 16:14:13

#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[100001],b[10001];
long long ans;
int erfen(int k)
{
    int l=1,r=n;
    int m;
    int mmin=INT_MAX;
    while(l<=r)
    {
        m=(l+r)/2;
        mmin=min(mmin,abs(a[m]-k));
        if(a[m]<k) l=m+1;
        else if(a[m]>k) r=m-1;
        else mmin;
    }
    return mmin;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    sort(a+1,a+n+1);
    for(int i=1;i<=m;i++)
    {
        cin>>b[i];
        ans+=erfen(b[i]);
    }
    cout<<ans;
}

by __zhang__ @ 2024-03-10 09:07:50

可以这样

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
int a[100005],b[100005];
int n,m;
int main(){
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++) scanf("%d",&a[i]);
    for(int i=0;i<m;i++) scanf("%d",&b[i]);
    sort(a,a+n);
    long long tot=0;
    for(int i=0;i<m;i++){
        int zuo=0,you=n-1,ans=0x7fffffff,now=0;
        while(zuo<=you){
            int c=(zuo+you)/2;
            if(a[c]<b[i]){
                ans=min(ans,abs(b[i]-a[c]));
                zuo=c+1;
            }
            else{
                you=c-1;
                ans=min(ans,abs(b[i]-a[c]));
            }
        }
        tot+=ans;
    }
    printf("%lld",tot); 

}

|