StarCraft FZU - 2219 贪心+优先队列

ZB loves playing StarCraft and he likes Zerg most!

One day, when ZB was playing SC2, he came up with an idea:

He wants to change the queen’s ability, the queen’s new ability is to choose a worker at any time, and turn it into an egg, after K units of time, two workers will born from that egg. The ability is not consumed, which means you can use it any time without cooling down.

Now ZB wants to build N buildings, he has M workers initially, the i-th building costs t[i] units of time, and a worker will die after he builds a building. Now ZB wants to know the minimum time to build all N buildings.

Input

The first line contains an integer T, meaning the number of the cases. 1 <= T <= 50.

For each test case, the first line consists of three integers N, M and K. (1 <= N, M <= 100000, 1 <= K <= 100000).

The second line contains N integers t[1] … t[N](1 <= t[i] <= 100000).

Output

For each test case, output the answer of the question.

Sample Input

2
3 1 1
1 3 5
5 2 2
1 1 1 1 10
Sample Output

6
10
Hint

For the first example, turn the first worker into an egg at time 0, at time 1 there’s two worker. And use one of them to build the third building, turn the other one into an egg, at time 2, you have 2 workers and a worker building the third building. Use two workers build the first and the second building, they are built at time 3, 5, 6 respectively. ​​​​​​​

题意:开始有m个工人,一共要建n个建筑,每个建筑需要ti时间,一个员工建一个建筑,建完就死掉,对于某个员工可以将他变成蛋,在k个单位时间后会变成两个员工,求建完n个建筑的最少时间

思路:由题目可知,要建完这n个建筑,还需要n-m个工人,所以还需要n-m次分裂,每一次分裂分出两个工人,因为分裂和建造建筑是并行的,如果还需要工人,那么我们可以令分出的2个工人一个继续分裂,另一个去建筑,建筑时,我们贪心选取建造的建筑,优先选建筑时间长的建筑。这样,我们就可以以建筑花费时间为叶节点,分裂时间为边权画出来一个哈夫曼树,利用优先队列解决即可。

以样例为例:
在这里插入图片描述

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=100009;
struct node{
	int cost;
	friend bool operator < (node a,node b)
	{
		return a.cost>b.cost;
	}
}a[maxn];
priority_queue<node> q;
int main()
{
	int t,n,m,k;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d%d",&n,&m,&k);
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i].cost);
			q.push(a[i]);
		}
		int tmp=n-m;
		while(tmp>0)
		{
			q.pop();
			node now=q.top();
			q.pop();
			now.cost+=k;
			q.push(now);
			tmp--;
		}
		while(q.size()>1)
			q.pop();
		printf("%d\n",q.top());
		while(q.size())
			q.pop();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/why932346109/article/details/88831571