想知道为什么错

P1678 烦恼的高考志愿

redcountry @ 2024-07-07 00:40:23

这是我写的:

#include <cstdio> 
#include <algorithm>
using namespace std;
long long m,n,a[100001],b[100001],sum,ll=1;
int main()
{
    scanf("%d%d",&m,&n);
    for(int i=1;i<=m;i++)
        scanf("%d",&a[i]);
    for(int i=1;i<=n;i++)
        scanf("%d",&b[i]);
    sort(a+1,a+n+1);
    sort(b+1,b+n+1);
    for(int i=1;i<=n;i++)
    {
        if(b[i]<=a[ll])
            sum+=(a[ll]-b[i]);
        else if(b[i]>=a[m])
            sum+=(b[i]-a[m]);
        else
        {
            int l=ll,r=m,mid;
            while(l<=r)
            {
                mid=(l+r)/2;
                if(a[mid]<b[i])
                    l=mid+1;
                else
                    r=mid-1;
            }
            sum+=min(b[i]-a[l-1],a[l]-b[i]);
            ll=l-1;
        }
    }
    printf("%d",sum);
    return 0;
}

请问哪里出问题了?


by lengfengwcx @ 2024-08-08 16:31:58

@seniorhan 这样写 求关

#include<bits/stdc++.h>
using namespace std;
int ans,a[100010],b[100010];
int n,m;
int main(){
    cin>>n>>m;
    if(n==1){
        cout<<"100000000000";
        return 0;
    }
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    for(int i=1;i<=m;i++)
    {
        cin>>b[i];
    }
    sort(a+1,a+n+1);
    for(int i=1; i<=m; i++)
        {
            int l=0,r=n+1;
            while(l<r)
            {
                int mid=(l+r)/2;
                if(a[mid]<=b[i])l=mid+1;
                else r=mid;
            }
            if(b[i]<=a[1])
                ans+=a[1]-b[i];
            else 
                ans+=min(abs(a[l-1]-b[i]),abs(a[l]-b[i]));
        }
    cout<<ans;
    return 0;
} 

|