求助!!!样例过了,但是0分

P1678 烦恼的高考志愿

Li_Junlin @ 2023-09-03 18:47:39

#include<bits/stdc++.h>
using namespace std;
long long a[100000];
long long b[100000];
long long an,bn,l,r,mid,c,c1,sum;
bool cmp(long long &a,long long &b)
{
    return a<b;
}
int main()
{
    freopen("P1678_1.in","r",stdin);
    freopen("P1678_3.out","w",stdout); 
    scanf("%lld%lld",&an,&bn);
    for(int i=0;i<an;i++) scanf("%lld",&a[i]);
    sort(a+0,a+0+an,cmp);
//  for(int i=an;i<100000;i++) a[i]=-1000001;
    for(int i=0;i<bn;i++)
    {
        l=0;
        r=bn-1;
        mid=(l+r)>>1;
        scanf("%lld",&b[i]);
        while(l<r)
        {
            mid=(l+r)>>1;
            if(a[mid]>=b[i]) r=mid;
            else l=mid+1;
        }
        while(a[r]==a[r+1]) r++;
        c1=abs(a[r]-b[i]);
        c=abs(a[r+1]-b[i]);
        if(r>=(an-1)) sum+=c1;
        else
        sum+=min(c1,c);
    }
    printf("%lld",sum);
}

by Perfect_Youth @ 2023-09-03 18:51:15

@Li_Junlin

#include<bits/stdc++.h>
using namespace std;
long long a[100000];
long long b[100000];
long long an,bn,l,r,mid,c,c1,sum;
bool cmp(long long &a,long long &b)
{
    return a<b;
}
int main()
{
    // 下面记得封上
    //freopen("P1678_1.in","r",stdin);
    //freopen("P1678_3.out","w",stdout); 
    scanf("%lld%lld",&an,&bn);
    for(int i=0;i<an;i++) scanf("%lld",&a[i]);
    sort(a+0,a+0+an,cmp);
//  for(int i=an;i<100000;i++) a[i]=-1000001;
    for(int i=0;i<bn;i++)
    {
        l=0;
        r=bn-1;
        mid=(l+r)>>1;
        scanf("%lld",&b[i]);
        while(l<r)
        {
            mid=(l+r)>>1;
            if(a[mid]>=b[i]) r=mid;
            else l=mid+1;
        }
        while(a[r]==a[r+1]) r++;
        c1=abs(a[r]-b[i]);
        c=abs(a[r+1]-b[i]);
        if(r>=(an-1)) sum+=c1;
        else
        sum+=min(c1,c);
    }
    printf("%lld",sum);
}

by Ac_Code_cn_com @ 2023-09-03 19:05:24

@Li_Junlin

#include<bits/stdc++.h>
using namespace std;
int n,m,a[100005],b[1000005];
long long c=0;
int k(int l,int r,int x){
    if(x<a[1]){
        return a[1]-x;      
    }
    if(x>a[r]){
        return x-a[r];      
    }   
    while(l<r){
        int y=(l+r+1)/2;
        if(a[y]==x){
            return 0;
        }else if(a[y]<x){
            l=y;
        }else{
            r=y-1;
        }   
    }
    return min(a[r+1]-x,x-a[l]);
}
int main(){
    cin>>m>>n;
    for(int i=1;i<=m;i++){
        cin>>a[i];
    }
    sort(a+1,a+m+1);
    for(int i=0;i<n;i++){
        cin>>b[i];
        c+=k(1,m,b[i]);     
    }
    cout<<c;
    return 0;
}

AC代码


|