转化一下题意,相当于求能优惠的最大价格。对于每个物品,可能的情况有:
- 不用优惠券,优惠 元;
- 用优惠券 ,优惠 元。
那么一个朴素的想法是,将物品按 升序排序,优惠券按 升序排序,枚举每个物品,每次将新增的能使用的(满足 )优惠券加入一个大根堆中。每次取出一个 最大的优惠券,将其与不用优惠券的收益比较,并决定使用哪个。
但这样做是假的,因为前面的物品可能会占用一个 很大的优惠券,但如果它的 已经很大,实际带来的收益可能不如后面的物品。因此,考虑反悔贪心,再引入一种决策:
- 抢走前面的一个物品 的优惠券 ,收益为 元。
据此,我们每枚举到一个物品,就把它的 也扔进大根堆里。容易发现这样做能覆盖到所有情况。复杂度 。
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e6 + 10;
struct Object{
ll a, b;
bool operator < (const Object &x) const{
return a < x.a;
}
}o[MAXN];
struct Ticket{
ll w, v;
bool operator < (const Ticket &x) const{
return w < x.w;
}
}t[MAXN];
int n, m;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
ll tot = 0;
for (int i = 1; i <= n; i++){
cin >> o[i].a >> o[i].b;
tot += o[i].a;
}
for (int i = 1; i <= m; i++){
cin >> t[i].w >> t[i].v;
}
sort(o + 1, o + n + 1);
sort(t + 1, t + m + 1);
priority_queue <ll> q;
ll sum = 0;
for (int i = 1, j = 1; i <= n; i++){
q.push(o[i].a - o[i].b);
while (j <= m && t[j].w <= o[i].a){
q.push(t[j].v);
j++;
}
ll val = q.top();
q.pop();
sum += val;
}
cout << tot - sum << "\n";
return 0;
}