70 分 求助~

P1678 烦恼的高考志愿

DarPluto_9 @ 2022-06-08 16:51:15

#include <iostream>
using namespace std;
#include <algorithm>
typedef long long ll;
const int N = 1e5 + 10;
int sch[N], stu[N];

int main()
{
    int m, n;
    ll sum = 0;
    cin >> m >> n;
    for (int i = 0; i < m; i++)
        scanf("%d",&sch[i]);

    sort(sch, sch + m);   //排序

    for (int i = 0; i < n; i++)
    {
        scanf("%d", &stu[i]);

        int ex = lower_bound(sch, sch + m, stu[i]) - sch;  //找到>=val的最左位置
        if (ex == n)  //比所有的都大
            ex = n - 1;
        else if (ex == 0)   //防止后续ex-1
            ex = 0;
        else    //有可能小的更符合
            ex = abs(stu[i] - sch[ex]) > abs(stu[i] - sch[ex - 1]) ? ex - 1 : ex;

        sum += abs(stu[i] - sch[ex]);
    }
    cout << sum;
    return 0;
}

by metaphysis @ 2022-06-08 19:31:14

@DarPluto_9

if (ex == n)  //比所有的都大
            ex = n - 1;

by DarPluto_9 @ 2022-06-08 20:20:12

@metaphysis 感谢感谢~~


|