完了,为啥就十分啊,我二分不对吗?

P1678 烦恼的高考志愿

ttltony @ 2023-01-08 15:08:20

10分代码:

#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

int m, n, ans;
int a[100001];

int christ(int l, int r, int key) {
    int mid;
    while (l + 1 < r) {
        mid = (l + r) >> 1;
        if (a[mid] <= key) l = mid;
        else r = mid;
    }
    if (key - a[l] <= a[r] - key) return a[l];
    else return a[r];
}

int main() {
    cin >> m >> n;
    for (int i = 1; i <= m; i ++ ) cin >> a[i];
    sort(a + 1, a + n + 1);
    for (int i = 1; i <= n; i ++ ) {
        int b;
        cin >> b;
        int t = christ(1, m, b);
        ans += abs(t - b);
    }
    cout << ans << endl;
    return 0;
}

求大佬指教,谢谢


by HEIMOFA @ 2023-04-05 09:31:28

  1. l+1<=r
  2. 然后ans要开long long
  3. 你排序当中怎么是a+n+1

by HEIMOFA @ 2023-04-05 09:32:06

按我的这个方式改一下,应该就过了


|