40分!求助大佬!

P1678 烦恼的高考志愿

fsy2024 @ 2024-08-12 20:39:15

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

by suizihan1226 @ 2024-08-12 20:41:29

哪题啊?


by lin20081016 @ 2024-08-12 20:55:21

第十二行,z和y的赋值应是z=1,y=n,因为你的a数组下标是1~n,而这个二分的范围是[z,y],两者要保持一致


by WEICY123 @ 2024-08-12 20:58:53

if(b[i]<=a[1]){
    t+=a[1]-b[i];
    }
    else{
    t+=min(abs(a[z-1]-b[i]),abs(a[z]-b[i]));
    }

@fsy2024 这题要特判,且你先没事干吗?y=n-1,干嘛直接y=n. 把t+=k改成上面这个特判就行了


by fsy2024 @ 2024-08-12 21:02:17

@suizihan1226 P1678


by fsy2024 @ 2024-08-12 21:03:01

@lin20081016 @WEICY123 谢谢大佬


by suizihan1226 @ 2024-08-12 21:03:20

@fsy2024 我到了


by fsy2024 @ 2024-08-12 21:16:28

@lin20081016 @WEICY123

两位大佬,本蒟蒻已关


|