基准时间限制:1 秒 空间限制:131072 KB 分值: 20
难度:3级算法题
有N个任务,每个任务有一个最晚结束时间以及一个对应的奖励。在结束时间之前完成该任务,就可以获得对应的奖励。完成每一个任务所需的时间都是1个单位时间。有时候完成所有任务是不可能的,因为时间上可能会有冲突,这需要你来取舍。求能够获得的最高奖励。
Input
第1行:一个数N,表示任务的数量(2 <= N <= 50000) 第2 - N + 1行,每行2个数,中间用空格分隔,表示任务的最晚结束时间E[i]以及对应的奖励W[i]。(1 <= E[i] <= 10^9,1 <= W[i] <= 10^9)
Output
输出能够获得的最高奖励。
Input示例
7 4 20 2 60 4 70 3 40 1 30 4 50 6 10
Output示例
230
想了好长时间,思想会了,但是实现代码我还是太弱;
时间按照从小到大的顺序排列;
每一个时间点都会安排一个任务,(首先这个任务还没有结束)
当然我们会遇到安排不了的任务,那肯定是需要判断这个任务是否
可以安排到前面,时间上当前这个任务肯定是可以的;
然后就是奖励上需要比那些已经安排的任务大才可以安排
一直动态的更新
#include<cstdio>
#include<functional>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long LL;
struct node
{
LL time;
LL cost;
}best[51000];
bool cmp(node a,node b)
{
return a.time<b.time;//按照时间从小到大排列
}
int main()
{
LL n,i;
scanf("%lld",&n);
for(i=1;i<=n;++i)
scanf("%lld%lld",&best[i].time,&best[i].cost);
sort(best+1,best+n+1,cmp);
priority_queue<int,vector<int>,greater<int> >que;
//优先级从小到大
LL tm,sum=0;
for(i=1,tm=1;i<=n;++i)
{
if(best[i].time>=tm)
{
sum+=best[i].cost;
que.push(best[i].cost);
++tm;
}
else
{
int temp=que.top();
if(temp<best[i].cost)
{
sum-=temp;
que.pop();
que.push(best[i].cost);
sum+=best[i].cost;
}
}
}
printf("%lld\n",sum);
return 0;
}