求助,玄关

P1678 烦恼的高考志愿

x2401002 @ 2024-11-16 15:44:35

#include<bits/stdc++.h>
using namespace std;
const int maxn = 10e4+100;
long long n,m,a[maxn],b[maxn],ans;
int main(){
    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+1+n);
    for(int i = 1;i<=m;i++){
        long long l = 1,r = n,x=0;
        while(l<=r){
            long long mid = (l+r)/2;
            if(a[mid]==b[i]){
                x = mid;
                break;
            }else if(a[mid]<b[i]){
                //x = mid;
                l = mid+1;
                if(abs(b[i]-a[x])>abs(b[i]-a[mid])){
                    x = mid;
                }
            }else{
                //x = mid;
                r = mid - 1;
                if(abs(b[i]-a[x])>abs(b[i]-a[mid])){
                    x = mid;
                }
            }
        }
        ans+=abs(b[i]-a[x]);        
    }
    cout<<ans;
    return 0;
}

https://www.luogu.com.cn/problem/P1678

70pts+WA

by 1nes @ 2024-11-16 16:02:04

需要特判b[i] < a[1]的情况
for后面加上这个可以AC

    if(b[i] < a[1]){
            ans += a[1] - b[i];
            continue;
        }

|