二分法 40分求助

P1678 烦恼的高考志愿

Wan2co @ 2022-08-01 11:52:52

rt,实在想不通是哪里的问题了。。。希望大佬们能帮帮孩子

#include<bits/stdc++.h> 
using namespace std;
int m,n,ans=0;
vector<int>a(100001); 
vector<int>b(100001);
int main(){ 
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    sort(a.begin(),a.begin()+n);
    for(int i=1;i<=m;i++){
        scanf("%d",&b[i]);
        int l=1,r=n,tmp=9999;
        while(l<=r){
            int mid=(r-l)/2+l;
            if(a[1]>=b[i]){
                tmp=a[1]-b[i];
                break;
            }
            else if(a[mid]==b[i]){
                tmp=0;
                break;
            }
            else if(a[mid]<b[i]){
                l=mid+1;
                tmp=min(tmp,abs(a[mid]-b[i])); 
            }
            else {
                r=mid-1;
                tmp=min(tmp,abs(a[mid]-b[i]));
            }   
        }
        ans+=tmp;
    }
    printf("%d",ans);
    return 0;
}

by hanzhang666 @ 2022-08-01 13:36:53

你用 lower_bound 不香吗


|