二分80pts

P1678 烦恼的高考志愿

yuxiaoyu20090104 @ 2022-10-02 11:59:53

#include<cstdio>
#include<iostream>
#include <algorithm>
using namespace std;
int M, N;
long long ans;
int a[100005], b[100005];
int bin(int x)
{
    int l = 0, r = M;
    while (l + 1 < r)
    {
        int mid = (l + r) / 2;
        if (a[mid] >= x)
        {
            r = mid;
        }
        else
        {
            l = mid;
        }
    }
    if (x - a[r - 1] < a[r] - x && r > 1)
    {
        return x - a[r - 1];
    }
    return a[r] - x;
}
int main() {
    cin >> M >> N;
    for (int i = 1; i <= M; i++)
    {
        cin >> a[i];
    }
    sort(a + 1, a + M + 1);
    for (int i = 1; i <= N; i++)
    {
        cin >> b[i];
        ans += bin(b[i]);
    }
    cout << ans;
    return 0;
}

by melons_sundae @ 2022-10-02 12:32:54

你可以看看我的


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

by liumuyvan @ 2022-10-24 15:41:07

@zhangxinyue2026 亲测你的代码60分


|