本文共 1602 字,大约阅读时间需要 5 分钟。
超市购物问题的贪心解决方案
在这个问题中,我们需要在有限的时间内选择一天中价值最大的商品。每个商品都有一个最晚卖出时间,只能在此时间之前选择。我们的目标是最大化总价值。
思路分析
我们采用贪心算法来解决这个问题。贪心算法的核心思想是,在每一步做出局部最优选择,从而达到全局最优。具体来说:
排序商品:将所有商品按最晚卖出时间从晚到早排序。如果两个商品的卖出时间相同,则按价值从高到低排序。 使用优先队列:将商品按照上述排序依次处理。对于每个商品,我们尝试在其最晚卖出时间之前尽可能多地选择尚未处理的商品,并且在每个时间点选取当前队列中价值最高的商品。 通过这种方式,我们可以确保在每个时间点都选择最优的商品,从而达到整体最大价值的目标。
详细步骤
输入处理:读取商品数量和各商品的价值与最晚卖出时间。 排序:将商品按最晚卖出时间从晚到早排序,价值从高到低排序。 贪心选择: - 初始化最大价值为第一个商品的价值。
- 对于每个后续商品,尝试在其最晚卖出时间之前尽可能多地从优先队列中取出未处理的商品。
- 在每一步中,总是选择队列中价值最高的商品,直到无法再选择为止。
代码实现
#include #include #include #include using namespace std;struct node { int x, t;};int main() { int n; while (scanf("%d", &n) != EOF) { priority_queue
> q; struct node a[n + 1]; memset(a, 0, sizeof(a)); for (int i = 1; i <= n; ++i) { scanf("%d %d", &a[i].x, &a[i].t); } sort(a + 1, a + n + 1, [](const node& x, const node& y) { if (x.t != y.t) return x.t > y.t; return x.x > y.x; }); if (n == 0) { printf("0\n"); continue; } long long ans = a[1].x; for (int i = 2; i <= n; ++i) { q.push(a[i].x); if (a[i].t != a[i-1].t) { int delta = a[i-1].t - a[i].t; for (int j = 0; j < delta; ++j) { if (q.empty()) break; ans += q.top(); q.pop(); } } } for (int i = a[n].t - 1; i >= 1; --i) { if (q.empty()) break; ans += q.top(); q.pop(); } printf("%lld\n", ans); } return 0;}