跳到正文

题解

题解 UVA1316 【Supermarket】

陷语约 3 分钟
原文
文章信息与版本

文章信息

发布
2019年5月12日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟
题目
UVA1316

版本

  1. v2当前
  2. v1

Supermarket

题目大意:

超市有n种商品,每个商品都有一个利润和保质期,超市每天只可以卖一种商品,求超市在保质期内卖出商品可获得的最大利益。

思路:

读完题目我们的脑海里一般都会浮现出一个想法,就是在最大的保质期时间内找出利润最大的商品卖掉,这个贪心思路是正确的,但是如何实现呢?通过思考我们会发现我们的每一个选择都会被商品的保质期影响,即我们必须在商品的保质期内卖出商品,所以我们可以将保质期与可选择的次数相结合,得到以下贪心思路:

将每种商品的保质期按从小到大顺序排序,得到一个有序的时间。

使用小根堆维护已经选择商品的价值,然后继续选择商品,这时会有这两种情况:

1.当前商品的保质期大于已经选择商品的次数,直接将此商品加入选择之中;

2.当前商品的保质期等于已经选择商品的次数,将这个商品的价值与小根堆的堆顶作比较,如果大于即替换,否则不变。

证明:

设:x1 < x2 > x3,保质期分别为1 1 2;

当选择为空时,直接选择x1,当选择一种保质期为1天时,将x2和x1作比较,发现x2 > x1,将x1替换。

很明显可以发现当前局部最优并不会影响全局最优。

附上代码:

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>

using namespace std;
const int N = 10100;

struct goods{
    int val, day;
    bool operator < (const goods a) const {
        return day < a.day;
    }
} a[N];

struct cmp{
    int val;
    bool operator < (const cmp a) const {
        return val > a.val;
    }
};

int n, ans;

int main() {
//	freopen("in.txt", "r", stdin);
    while(cin >> n) {
        ans = 0;
        memset(a, 0, sizeof(a));
        priority_queue <cmp> que;

        for(int i = 1; i <= n; ++i) scanf("%d %d", &a[i].val, &a[i].day);
        sort(a + 1, a + 1 + n);//按时间从小到大排序

        for(int i = 1; i <= n; ++i) {
            if(a[i].day > que.size()) que.push((cmp) {a[i].val});
            else if(a[i].day == que.size() && a[i].val > que.top().val) {
                que.pop();
                que.push((cmp) {a[i].val});
            }
        }

        while(!que.empty()) {
            ans += que.top().val;
            que.pop();
        }
        printf("%d\n", ans);
    }
    return 0;
}

需要注意的是,这题在while()里面用~scanf会出问题,使用cin则不会,这就是我WA了n的原因……

原文
存档评论2 条抓取于