题解:P14904 [NHSPC 2024] 计程车叫车问题

· · 题解

步骤

读入 m,读入数组 t 和 p,对 t 和 p 分别排序(升序),遍历 i=1…m,累加 t_i-p_i 即可。

#include <iostream>
#include <algorithm>
using namespace std;

const int MAXM = 1e6 + 5;
int t[MAXM], p[MAXM];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int m;
    cin >> m;
    for (int i = 0; i < m; i++) cin >> t[i];
    for (int i = 0; i < m; i++) cin >> p[i];

    sort(t, t + m);
    sort(p, p + m);

    long long ans = 0;
    for (int i = 0; i < m; i++) {
        ans += abs(t[i] - p[i]);
    }

    cout << ans << "\n";
    return 0;
}