《算法竞赛进阶指南》超市

超市里有 NN 件商品,每件商品都有利润 pipi 和过期时间 didi,每天只能卖一件商品,过期商品不能再卖。

求合理安排每天卖的商品的情况下,可以得到的最大收益是多少。

输入格式

输入包含多组测试用例。

每组测试用例,以输入整数 NN 开始,接下来输入 NN 对 pipi 和 didi,分别代表第 ii 件商品的利润和过期时间。

在输入中,数据之间可以自由穿插任意个空格或空行,输入至文件结尾时终止输入,保证数据正确。

输出格式

对于每组产品,输出一个该组的最大收益值。

每个结果占一行。

数据范围

0≤N≤100000≤N≤10000,
1≤pi,di≤100001≤pi,di≤10000
最多有 1414 组测试样例

输入样例:

4  50 2  10 1   20 2   30 1

7  20 1   2 1   10 3  100 2   8 2
   5 20  50 10

输出样例:

80
185

解题思路:
将所有产品按时间从小到大排序
每次将一个数插入小根堆,若小根堆的产品个数小于等于插入产品的时间则不做处理
若小根堆的产品个数大于插入产品的时间则将小根堆中的最小元素删除
最后小根堆里面的元素之和即为最终的答案 

#include <queue>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

#define x first
#define y second

using namespace std;

const int N = 10010;

typedef pair<int, int> PII;

int n;

int main()
{
    while (scanf("%d", &n) != EOF)
    {
        vector<PII> products(n);
        for (int i = 0; i < n; i ++ ) 
            scanf("%d %d", &products[i].y, &products[i].x);
        
        sort(products.begin(), products.end());
        
        priority_queue<int, vector<int>, greater<int>> heap;
        for (auto temp : products)
        {
            heap.push(temp.y);
            if (heap.size() > temp.x) heap.pop();//若小根堆的产品个数大于插入产品的时间则将小根堆中的最小元素删除
        }
        
        int res = 0;
        while (heap.size())
        {
            res += heap.top();
            heap.pop();
        }
        
        printf("%d\n", res);
    }
    
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啥也不会hh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值