洛谷 P3045 [USACO12FEB]Cow Coupons G

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <bits/stdc++.h>
using namespace std;
using PII = pair<int, int>;
const int N = 50000;
int n, k, ans;
struct Node {
int p;
int c;
} cow[N];
priority_queue<int, vector<int>, greater<int>> dq; // 折扣小根堆
priority_queue<PII, vector<PII>, greater<PII>> cq, pq; // [折后价,坐标]小根堆,[原价,坐标]小根堆
long long m, cost;
bool st[N];
int main() {
scanf("%d%d%lld", &n, &k, &m);
for (int i = 0; i < n; ++i) scanf("%d%d", &cow[i].p, &cow[i].c);
sort(cow, cow + n, [](Node a, Node b) {
return a.c < b.c; // 按折后价排序
});
for (int i = 0; i < k; ++i) { // 尽可能将 k 个优惠券用掉
cost += cow[i].c;
if (cost > m) {
printf("%d\n", i);
return 0;
}
dq.push(cow[i].p - cow[i].c);
}
if (k == n) {
printf("%d\n", n);
return 0;
}
for (int i = k; i < n; ++i) {
cq.emplace(cow[i].c, i);
pq.emplace(cow[i].p, i);
}
int ans = k;
// 将剩下的钱花掉,要保持每一笔花费尽可能小,以此买更多的牛
for (int i = k; i < n; ++i) {
// 已买过的不再考虑购买
while (st[cq.top().second]) cq.pop();
while (st[pq.top().second]) pq.pop();
auto [c, ci] = cq.top();
auto [p, pi] = pq.top();
// 要么用优惠券买 cow[ci],花费 c,还需要原价购买 dp.top() 对应的牛
int t1 = c + dq.top();
// 要么买价格最小的,花费 p
int t2 = p;
if (t1 < t2) { // 前者花费更少
cost += t1;
dq.pop();
dq.push(cow[ci].p - cow[ci].c);
st[ci] = 1;
} else { // 后者花费更少
cost += t2;
st[pi] = 1;
}
++ans;
if (cost > m) {
printf("%d\n", ans - 1);
return 0;
}
}
printf("%d\n", n);
return 0;
}