这样为什么错?悬关

P1678 烦恼的高考志愿

lucy2012 @ 2024-03-20 20:41:07

#include<bits/stdc++.h>
using namespace std;
int a[100010],b[100010],m,n;
int main(){
    cin>>m>>n;
    long long l,r,ans=0,mid;
    for(int i=1;i<=m;i++)
        cin>>a[i];
    for(int i=1;i<=n;i++)
        cin>>b[i];
    sort(a+1,a+1+m);
    for(int i=1;i<=n;i++){
        long long l=0,r=n+1;
        while(l<r){
            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;
}

为神马这样却对了

#include<bits/stdc++.h>
using namespace std;
int a[100010],b[100010];
int main()
{
    int n,m;
    cin>>n>>m;
    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);
    long long ans=0;
    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;
}

by c52_hdzyl @ 2024-03-20 20:47:16

@lucy2012

#include<bits/stdc++.h>
using namespace std;
int a[100010],b[100010],m,n;
int main(){
    cin>>m>>n;
    long long l,r,ans=0,mid;
    for(int i=1;i<=m;i++)
        cin>>a[i];
    for(int i=1;i<=n;i++)
        cin>>b[i];
    sort(a+1,a+1+m);
    for(int i=1;i<=n;i++){
        long long l=0,r=m+1;//r=n+1是错的 
        while(l<r){
            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;
}

by c52_hdzyl @ 2024-03-20 20:48:18

@lucy2012 你二分时,r的值错了


by lucy2012 @ 2024-03-20 20:50:42

@c52_hdzyl 谢谢!


|