用了二分,50分,不知错哪了,求大神看看

P1678 烦恼的高考志愿

Feng123754 @ 2024-01-24 18:00:07

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 100010;
int a[N],m;

int findl(int x)  //找到第一个大于等于的数
{
    int l=0,r=m+1;
    while(l<r)
    {
        int mid=(l+r)/2;
        if(x<=a[mid]) r=mid;
        else l=mid+1;
    }

    return l;
}

int findr(int x)
{
    int l=0,r=m+1;
    while(l<r)
    {
        int mid=(l+r+1)/2;
        if(x>=a[mid]) l=mid;
        else r=mid-1;
    }

     return l;
}

int main()
{
    int n,res=0;
    cin>>m>>n;
    for(int i=0;i<m;i++) cin>>a[i];
    sort(a,a+m);
    while(n--)
    {
        int x;
        cin>>x;
        res+=min(abs(x-a[findr(x)]),abs(x-a[findl(x)]));
    }
    cout<<res;
    return 0;
}

by TLE_ZBR @ 2024-01-24 18:09:48

不开long long见祖宗


by Feng123754 @ 2024-01-24 20:10:07

@TLE_ZBR 开了long long 也是50分


by Lg17207068176 @ 2024-02-03 18:37:15

你现在过了嘛,我60QAQ

#include<cmath>
#include<algorithm>
#include<iostream>
#define N 1000010
using namespace std;
long long m,n,ans=0;//m代表学校数,n代表学生数
long long Sc[N],St[N];
long long binary_search1(long long x){//找到第一个大于等于x的数 
    long long l=-1,r=m;
    while(l+1<r){
        long long mid=(l+r)>>1;
        if(Sc[mid]<x) l=mid;
        else r=mid; 
    }
    if(Sc[r]==x) return 0;
    else return  Sc[r]-x;
}
long long binary_search2(long long x){//找到最后一个小于等于x的值 
    long long l=-1,r=m;
    while(l+1<r){
        long long mid=(l+r)>>1;
        if(Sc[mid]<=x) l=mid;
        else r=mid; 
    }
    if(Sc[l]==x) return 0;
    else return  x-Sc[l];
}
int main(){
    cin>>m>>n;
    for(long long i=0;i<m;i++)
        cin>>Sc[i];
    sort(Sc,Sc+m);
    for(long long i=0;i<n;i++){
        cin>>St[i];
        ans+=min(binary_search1(St[i]),binary_search2(St[i]));
    }
    cout<<ans;
    return 0;
}

|