题解:P12916 [POI 2021/2022 R1] 剪辑师 / Montażysta
反悔贪心。
怎么想到的呢,首先是最大价值类问题,且有两组变量,其中有一组限制着排序,另一组关系着答案。故反悔贪心可以在答案一组中求得最优解。
放一个码风很好且易懂的代码,我相信可读性比另外几篇题解要高。
首先我们需要对截止时间排序,在每次遍历的时候,分为以下两种处理方式(令
最后将所有堆中元素的截至时间排序再输出,
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int N = 510000;
int n, now;
struct node {
int id;
int t, d;
} a[N];
bool cmp(node x, node y) {
return x.d < y.d;
}
vector<node> ans;
priority_queue<pair<int, int> > q;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &a[i].t, &a[i].d);
a[i].id = i;
}
sort(a + 1, a + n + 1, cmp);
for (int i = 1; i <= n; i++) {
if (now + a[i].t <= a[i].d) {
now += a[i].t;
q.push(make_pair(a[i].t, i));
} else if (!q.empty() && now - q.top().first + a[i].t <= a[i].d && q.top().first > a[i].t) {
now -= q.top().first;
q.pop();
now += a[i].t;
q.push(make_pair(a[i].t, i));
}
}
printf("%d\n", (int)q.size());
while (!q.empty()) {
ans.push_back(a[q.top().second]);
q.pop();
}
sort(ans.begin(), ans.end(), cmp);
now = 1;
for (auto v : ans) {
printf("%d %d\n", v.id, now);
now += v.t;
}
return 0;
}