怎么优化?求助大佬!

P1678 烦恼的高考志愿

acmwriter @ 2023-05-16 22:42:59

#include<bits/stdc++.h>
using namespace std;
int a[100005],n,m;
int main(){
    long long sum=0;
    cin>>n>>m;
    for(int i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    int b;
    for(int i=0;i<m;i++){
        cin>>b;
        if(b<=a[0])sum+=a[0]-b;
        else if(b>=a[n-1])sum+=b-a[n-1];
        else {
        for(int j=0;j<n-1;j++){
            if(b>=a[j]&&b<=a[j+1]){
                sum+=min(b-a[j],a[j+1]-b);
                break;
            }
        }
        }
    }
    cout<<sum;
    return 0;
}

by newtocpp @ 2023-05-16 22:46:17

用二分?


by jeamark_233 @ 2023-05-17 08:43:01

if(b<=a[0])sum+=a[0]-b;
        else if(b>=a[n-1])sum+=b-a[n-1];
        else {
        for(int j=0;j<n-1;j++){
            if(b>=a[j]&&b<=a[j+1]){
                sum+=min(b-a[j],a[j+1]-b);
                break;
            }
        }

这一块先用二分查找之后再判定全部都大于还是全部都小于等


|