51Nod-1163-最高的奖励(经典贪心题:优先队列解法)

题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1163

题解:

将最晚结束时间升序排序,第n个任务最晚时间如果大于已经消耗的时间,则可以算入总和,若不大于可以尝试替换掉已经算入总和中的最小奖励的任务,条件是这件任务的奖励要大于要替换掉的任务的奖励。使用优先队列维护。

代码:

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

typedef long long ll;

using namespace std;

const int MAXN = 5e4 + 10;

struct task
{
    int times;
    int cost;
} t[MAXN];

bool cmp(const task a,const task b)
{
    return a.times < b.times;
}

int main()
{
    int n;
    scanf("%d", &n);

    for (int i = 0; i < n; i++)
    {
        scanf("%d%d", &t[i].times, &t[i].cost);
    }
    sort(t, t + n, cmp);
    //  优先队列维护
    priority_queue<int, vector<int>, greater<int> > pq;
    long long  ans = 0;
    for (int i = 0; i < n; i++)
    {
        int k = t[i].cost;
        if (t[i].times > pq.size())     //  pq.size这里理解代表时间点
        {
            ans += k;
            pq.push(k);
        }
        else                            //  时间点有冲突,把cost最小删除
        {
            ans += k;
            pq.push(k);
            int minn = pq.top();
            ans -= minn;
            pq.pop();                   //  删除
        }
    }
    printf("%lld\n", ans);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36561697/article/details/80968353