dalao!本蒟蒻40分求解

P1678 烦恼的高考志愿

President_Zhao @ 2023-09-09 19:35:24

#include<bits/stdc++.h>
#define int long long
using namespace std;
int f[1000001],gf[1000001],kun=1;
signed main()
{
    int m,n,total=0;
    cin>>m>>n;
    for(int k=1;k<=m;k++)
    {
        cin>>f[k];
    }
    sort(f+1,f+1+m);
    for(int k=1;k<=n;k++)
    {
        cin>>gf[k];
        int l=1,r=m;
        while(l<=r)
        {
            int mid=(l+r)/2;
            if(f[mid]<=gf[k])
            {
                l=mid+1;
                 kun=mid;
            }
            else
            {
                r=mid-1;
            }
        }
        total+=min(abs(f[min(kun+1,m)]-gf[k]),abs(f[kun]-gf[k]));
    }
    cout<<total;
}

by junjie_zhao @ 2023-09-09 19:51:09

#include<bits/stdc++.h>
#define abs(a) ((a)<0?-(a):a)
using namespace std;
int a[1000005],b[100005],n;
bool cmp(int a,int b)
{
    return a<b;
}
int AC(int x)
{
    int l=1,r=n+1,mid;
    while(l<=r)
    {
        mid=(l+r)/2;
        if(a[mid]==x)return x;
        if(a[mid]>x&&a[mid-1]<=x)
        {
            if(a[mid]-x>x-a[mid-1])return a[mid-1];
            return a[mid];
        }
        if(x>a[mid])l=mid+1;
        if(x<a[mid])r=mid-1;
    }
}
int main()
{
    int m;
    long long sum=0;
    cin>>n>>m;
    for(int i=1;i<=n;i++)cin>>a[i];
    a[n+1]=1000000000;
    a[0]=-1000000000;
    sort(a+1,a+n+1,cmp);
    for(int i=1;i<=m;i++)
    {
        cin>>b[i];
        sum+=abs(AC(b[i])-b[i]);
    }
    cout<<sum<<endl;
    return 0;
}

|