0分求助

P1678 烦恼的高考志愿

xiaowei234 @ 2023-07-29 21:10:02

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

by Lycd0719 @ 2023-07-31 15:59:22

你可以用lower_bound


by lijuncheng_1207 @ 2023-08-03 18:49:17

@xiaowei234


#include <bits/stdc++.h>
using namespace std;
const int N=1e8;
long long n,a[N],x,m,cnt;
int main(){
    cin>>n>>m;;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    sort(a+1,a+n+1);
    while(m--){
        cin>>x;
        int l=1,r=n;
        while(l+1<r){
            int mid=(l+r)>>1;
            if(a[mid]>=x)
                r=mid;
            else
                l=mid;
        }
        cnt+=abs(a[l]-x)<=abs(a[r]-x)?abs(a[l]-x):abs(a[r]-x);
    }
    cout<<cnt;
    return 0;//完美落幕
}
``

by lijuncheng_1207 @ 2023-08-03 18:51:21

@xiaowei234

警钟警示,敲烂后人

sort一般不能放在循环里


|