lower_bound 3,8,10WA 求助

P1678 烦恼的高考志愿

玄铮 @ 2022-08-11 13:13:17

蒟蒻疑惑
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int m, n, a[100010], b[100010];
long long cnt;

int main() {
    scanf("%d%d", &m, &n);
    for (int i = 1; i <= m; i++)
        scanf("%d", &a[i]);
    for (int i = 1; i <= n; i++)
        scanf("%d", &b[i]);

    sort(a + 1, a + m + 1);
    for (int i = 1; i <= n; i++) {
        if (b[i] > a[m]) {//这里我觉得不加也可以
            int sad = b[i] - a[m];
            cnt += sad;
        } else {
            int k = lower_bound(a + 1, a + m + 1, b[i]) - a;
            int j = k - 1;
            int sad = min(abs(a[k] - b[i]), abs(a[j] - b[i]));
            cnt += sad;
        }
    }

    printf("%d", cnt);

    return 0;
}

by zhangchengyan @ 2022-08-11 13:33:54

@玄铮 是不是要特判某个学生的成绩比所有分数线都小的情况?


by mayijian @ 2022-08-11 13:42:18

lower_bound如何查找的数比数组中所有数要小返回值是0


by zhangchengyan @ 2022-08-11 13:53:34

if(b[i]<a[1])
{
    cnt+=a[1]-b[i];
    continue;
}

加这段特判


by 玄铮 @ 2022-08-12 18:56:47

哦哦好的谢谢


|