70pts求调

P1678 烦恼的高考志愿

hhhxxxxx @ 2023-11-16 20:42:49

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 1e5 + 10;

int n, m;
LL czx[N];
LL gu[N];
LL ans;

int main()
{
    cin >> m >> n;

    for (int i = 1; i <= m; i++)
        cin >> czx[i];

    sort(czx + 1, czx + 1 + m);

    for (int i = 1; i <= n; i++)
        cin >> gu[i];

    for (int i = 1; i <= n; i++)
    {
        LL minn = 0x3f3f3f3f;
        int r = lower_bound(czx + 1, czx + m + 1, gu[i]) - czx;//查找第一个大于等于当前分数的值
        minn = min(minn, abs(czx[r] - gu[i]));
        minn = min(minn, abs(czx[r - 1] - gu[i]));//再找第一个小于当前分数的值 两者取最小
        ans += minn;
    }

    cout << ans << endl;

    return 0;
}

by Happy_Orca @ 2023-11-16 20:46:50

@hhhxxxxx 如果lower_bound找到的是第一位的话,你的代码会去和0比较,这样有可能取得是与0的差


by hhhxxxxx @ 2023-11-16 20:49:31

@Happy_Orca 好的 我改一下 谢谢qwq


by hhhxxxxx @ 2023-11-16 20:54:00

@Happy_Orca 请问如果数组中所有的数比查找的数都小 那么lower_bound返回的是哪个位置 是m + 1吗


by Happy_Orca @ 2023-11-16 20:57:04

@hhhxxxxx 是的


by hhhxxxxx @ 2023-11-16 20:57:26

@Happy_Orca 谢谢


|