求助大佬的改正,只有70分

P1678 烦恼的高考志愿

liweiergg @ 2024-08-05 15:09:06

#include<iostream> 
#include<map>
#include<algorithm>
#include<math.h>
#define int long long
const int N = 1e5 + 10;
using namespace std;
int m, n, sum = 0;
int a[N], b[N];
int find(int x) {
    int l = 1, r = m;
    while (l < r) {
        int mid = l + (r - l) / 2;
        if (a[mid] - x == 0)return 0;
        if (a[mid] - x > 0) {
            r = mid;
        }
        if (a[mid] - x < 0) {
            l = mid + 1;
        }
    }
    return min(abs(a[l] - x), abs(a[l - 1] - x));
}
signed main() {
    cin >> m >> n;
    for (int i = 1; i <= m; i++)cin >> a[i];
    sort(a + 1, a + 1 + m);
    if (m != 1) {
        for (int i = 1; i <= n; i++) {
            cin >> b[i];
            sum += find(b[i]);
        }
        cout << sum;
    }
    else {
        for (int i = 1; i <= n; i++) {
            cin >> b[i];
            sum += abs(b[i] - a[1]);
        }
        cout << sum;
    }
    return 0;
}

by dongzhen @ 2024-08-05 15:46:30

你的二分模板错了喵~,这样写属于两种都沾了点边,可以去网上看看正确的二分写法,这里就不详细讲了。


by whx_1026 @ 2024-08-06 11:47:40

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

可以这样


by lengfengwcx @ 2024-08-08 16:30:40

@whx_1026 你可以省去很多大括号


by whx_1026 @ 2024-08-14 13:46:44

@lengfengwcx 看着好看


|