题解:P18147 [JOI 2027 二次预选] 伴手礼分发计划 / Souvenir Plan
该题解使用 ChatGPT 生成,已经通过测试数据评测验证。
题意简述
给
思路
先给每人凑齐最低需求,剩下的礼物可以任意送给各批次允许送的同学。反过来,从任意可行分法中给每人留出恰好
按编号从小到大给同学分礼物。轮到
如果它已经分给
实现时,把旅行按左端点排序。处理
复杂度分析
每批只入堆一次,至多出堆一次。排序和堆操作共用
参考代码
#include <algorithm>
#include <functional>
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
struct Trip {
int l, r, x;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, q;
cin >> n >> q;
vector<Trip> trips(q);
for (auto &[l, r, x] : trips) cin >> l >> r >> x;
sort(trips.begin(), trips.end(), [](const Trip &a, const Trip &b) {
return a.l < b.l;
});
// 堆的关键字是右端点,数量在 trips 中直接扣减。
using Batch = pair<int, int>;
priority_queue<Batch, vector<Batch>, greater<Batch>> heap;
int pos = 0;
for (int j = 1; j <= n; ++j) {
int need;
cin >> need;
while (pos < q && trips[pos].l <= j) {
heap.emplace(trips[pos].r, pos);
++pos;
}
while (need > 0) {
while (!heap.empty() && heap.top().first < j) heap.pop();
if (heap.empty()) {
cout << "No\n";
return 0;
}
int &left = trips[heap.top().second].x;
int used = min(left, need);
left -= used;
need -= used;
if (left == 0) heap.pop();
}
}
cout << "Yes\n";
}