有N个任务,每个任务有一个最晚结束时间以及一个对应的奖励。在结束时间之前完成该任务,就可以获得对应的奖励。完成每一个任务所需的时间都是1个单位时间。有时候完成所有任务是不可能的,因为时间上可能会有冲突,这需要你来取舍。求能够获得的最高奖励。
分析:
首先可以将所有完成时间截止日期大于n的任务的截止日期置为n,这是因为遍历完所有的任务只需要n步,所以只需要的时间为n,当截止日期大于n的时候,不考虑其他的限制条件的话,那这样的任务是肯定可以去完成的。当然了,好像不这样也没什么关系。
贪心+优先队列。将所有截至日期大于当前时间的任务都放入队列中,当截止日期等于当前时间的时候就有了矛盾,这时候就要抉择到底选择哪个任务,当然是选择价值大的任务了。
具体看代码。
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std ;
#define mem(a) memset(a,0,sizeof(a))
#define inf 100000005
int const maxn = 50005;
struct node
{
long long e,w;//结束时间和奖励
bool operator < (const node& u)const
{
if(w!=u.w)return w>u.w ; //最小值优先
return e<u.e;
}
}A[maxn];
bool cmp(node a,node b)
{
if(a.e!=b.e)return a.e<b.e;
return a.w>b.w;
}
int main()
{
int n;
priority_queue<node> q ;//优先队列,奖励小的优先,应该是要删除的
while(scanf("%d",&n)!=EOF)
{
for(int i = 0; i < n ; ++i)
{
scanf("%I64d%I64d",&A[i].e,&A[i].w);
if(A[i].e>n)A[i].e = n ;
}
sort(A,A+n,cmp);
while(!q.empty())q.pop();
int time = 0 ; //当前时间
long long ans = 0 ;
for(int i = 0 ; i < n ; ++i)
{
if(A[i].e>time)
{
q.push(A[i]);
time++; //完成一个任务之后当前的时间
}
else if(A[i].e==time) //大于就可以直接不管了
{ //等于的情况就出现了矛盾,在规定的时间多一个任务,这时候就把价值最小的删除
if(q.top().w<A[i].w)
{
q.pop();
q.push(A[i]); //比较当前元素和队列里面最小元素的价值
}
}
}
while(!q.empty())
{
ans+=q.top().w;
q.pop();
}
printf("%I64d\n",ans);
}
return 0 ;
}