70分求助

P1678 烦恼的高考志愿

liukuns6 @ 2024-04-08 20:47:02

#include<iostream>
#include<cstring>
#include<algorithm>
#include<math.h>
using namespace std;
const int & N = 1e5+10;
typedef long long ll;
ll arr[N];
ll res , n , m;

int main(){
    cin>>n>>m;
    for(int i =0 ;i<n;i++) cin>>arr[i];
    sort(arr,arr+n);
    while(m--){
        ll x;
        cin>>x;
        ll left = -1 , right = n;
        while(left+1!=right){
            int mid = left+(right-left)/2;
            if(arr[mid] < x) left= mid;
            else right = mid;
        }
        cout<<min(fabs(x-arr[left]) , fabs(x-arr[right]))<<endl;
        res += min(fabs(x-arr[left]) , fabs(x-arr[right]));
    }
    cout<<res<<endl;
    return 0;
}

by liukuns6 @ 2024-04-08 21:06:56

#include<iostream>
#include<cstring>
#include<algorithm>
#include<math.h>
using namespace std;
const int & N = 1e5+10;
typedef long long ll;
ll arr[N];
ll res , n , m;

int main(){
    cin>>n>>m;
    for(int i =1 ;i<=n;i++) cin>>arr[i];
    sort(arr+1,arr+n+1);
    while(m--){
        ll x;
        cin>>x;
        ll left = 0 , right = n+1;
        while(left+1!=right){
            int mid = left+(right-left)/2;
            if(arr[mid] < x) left= mid;
            else right = mid;
        }

        if(left == 0) res+= fabs(x-arr[right]); //左边界
        else if (right == n+1) res+= fabs(x-arr[left]);
        else res += min(fabs(x-arr[left]) , fabs(x-arr[right]));

    }
    cout<<res<<endl;
    return 0;
}

by remake1958 @ 2024-04-09 20:55:38

ll left = -1 , right = n; while(left+1!=right){ int mid = left+(right-left)/2; 这一块处理的不好,在n=1时会死循环,你可以然所有下标从1开始,left也从1开始


by Martin07 @ 2024-04-14 14:35:04

#include<bits/stdc++.h>
using namespace std;
long long a[1000005],s[1000005],ans; 
int n,m;
int Binary(int x,int l,int r){
    while(l+1<r){
        int mid=l+(r-l)/2;
        if(a[mid]<=x)l=mid;
        else r=mid;
    }
    if(l==-1)return abs(a[r]-x);
    if(r==m)return abs(a[l]-x);
    return min(abs(x-a[l]),abs(x-a[r]));
}
int main(){
    cin>>m>>n;
    for(int i=0;i<m;i++)cin>>a[i];
    for(int i=0;i<n;i++)cin>>s[i];
    sort(a,a+m);
    for(int i=0;i<n;i++){
        ans+=Binary(s[i],-1,m);
    }
    cout<<ans;
    return 0;
}

试试这个


|