洛谷 P2949 [USACO09OPEN]工作调度Work Scheduling 题解

P2949 [USACO09OPEN]工作调度Work Scheduling

题目描述

Farmer John has so very many jobs to do! In order to run the farm efficiently, he must make money on the jobs he does, each one of which takes just one time unit.

His work day starts at time 0 and has 1,000,000,000 time units (!). He currently can choose from any of N (1 <= N <= 100,000) jobs

conveniently numbered 1..N for work to do. It is possible but

extremely unlikely that he has time for all N jobs since he can only work on one job during any time unit and the deadlines tend to fall so that he can not perform all the tasks.

Job i has deadline D_i (1 <= D_i <= 1,000,000,000). If he finishes job i by then, he makes a profit of P_i (1 <= P_i <= 1,000,000,000).

What is the maximum total profit that FJ can earn from a given list of jobs and deadlines? The answer might not fit into a 32-bit integer.

输入格式

  • Line 1: A single integer: N

  • Lines 2..N+1: Line i+1 contains two space-separated integers: D_i and P_i

输出格式

  • Line 1: A single number on a line by itself that is the maximum possible profit FJ can earn.

题意翻译

约翰有太多的工作要做。为了让农场高效运转,他必须靠他的工作赚钱,每项工作花一个单位时间。 他的工作日从0时刻开始,有10^9个单位时间。在任一时刻,他都可以选择编号1~N的N(1 <= N <= 10^6)项工作中的任意一项工作来完成。 因为他在每个单位时间里只能做一个工作,而每项工作又有一个截止日期,所以他很难有时间完成所有N个工作,虽然还是有可能。 对于第i个工作,有一个截止时间D_i(1 <= D_i <= 10^9),如果他可以完成这个工作,那么他可以获利P_i( 1<=P_i<=10^9 ). 在给定的工作利润和截止时间下,约翰能够获得的利润最大为多少.

输入输出样例

输入 #1

3
2 10
1 5
1 7

输出 #1

17

说明/提示

Complete job 3 (1,7) at time 1 and complete job 1 (2,10) at time 2 to maximize the earnings (7 + 10 -> 17).

【思路】

优先队列 + 贪心
这道题告诉我以后不要相信洛谷标签 ……
标签是单调队列,我硬生生用单调队列写了半个多小时
终于放弃了单调队列选择了我的条件反射
优先队列
然后改了几下就A掉了……
可能是我太蒻了,不会怎么写单调队列吧

【为什么要用贪心】

还好贪心这个标签是正确的
这道题的贪心很显然
就是在每一个时间点都选择在这个时间点能够做的获得利润最大的策略
这样就可以由局部最优得到全局最优了

【最终思路】

那怎么好好的利用贪心呢?
可以按照时间顺序排一下序
然后如果优先队列中的元素数量
小于这个点的时间
那就直接放入优先队列

因为这个点的时间之前的每一个时间单位
都是可以完成一个工作的
所以如果元素数量小于这个时间
那就是时间还绰绰有余
不需要考虑优不优的
放进去就行
反正多放一定比少放更优

反之,
则想一下
这一个利润如果比前面某一个时间单位做的工作得到的利润更大
那如果在那个时间单位做这个工作就会变得更优
有点反悔的意思
这个时候队首就是一个最好的被替换的对象
这很显然就不赘述了
然后处理完成之后将优先队列里面全部的值加起来就是了

【注意】

优先队列是小根堆的哦

【完整代码】

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#define int long long
using namespace std;
const int Max = 1000006;
struct node
{
	int t;
	int v;
}a[Max];

bool cmp(const node x,const node y)
{
	return x.t < y.t;
}
priority_queue<int,vector<int>,greater<int> >q;
signed main()
{
//	freopen("work.in","r",stdin);
	int n;	
	cin >> n;
	for(register int i = 1;i <= n;++ i)
		cin >> a[i].t >> a[i].v;
	sort(a + 1,a + 1 + n,cmp);
	int ans = 0;
	for(register int i = 1;i <= n;++ i)
	{
		if(a[i].t > q.size())
		{
			q.push(a[i].v);
			ans += a[i].v;
		}
		else
		{
			if(a[i].v > q.top())
			{
				ans -= q.top();
				q.pop();
				q.push(a[i].v);
				ans += a[i].v;
			}
		}
	}
	cout << ans << endl;
	return 0;
}
原文地址:https://www.cnblogs.com/acioi/p/11686683.html