题解:P14842 [ICPC 2022 Yokohama R] Hasty Santa Claus

· · 题解

一道很简单贪心

#include<bits/stdc++.h>
using namespace std;
// 结构体仅保留单字母成员
struct s{
    int a, b, i; // a:开始日期, b:结束日期, i:原始索引
};
int main() {
    int n, k;
    cin >> n >> k;
    vector<s> h(n); // h:存储所有房屋信息
    for (int j = 0; j < n; ++j) {
        cin >> h[j].a >> h[j].b;
        h[j].i = j; // i:记录原始输入索引
    }
    // 按结束日期b升序排序
    sort(h.begin(), h.end(), [](const s& x, const s& y) {
        return x.b < y.b;
    });
    vector<int> c(32, 0); // c:日期计数数组(c[d]表示d日已分配数量)
    vector<int> a(n);     // a:存储最终分配结果(按原始索引)
    for (const auto& x : h) {
        // 遍历日期区间找可用日期
        for (int d = x.a; d <= x.b; ++d) {
            if (c[d] < k) {
                c[d]++;
                a[x.i] = d;
                break;
            }
        }
    }
    // 输出结果
    for (int d : a) {
        cout << d << endl;
    }
    return 0;
}