FZU2219 StarCraft(思维 哈夫曼树构造变形)

版权声明:Please work hard for your dreams. https://blog.csdn.net/calculate23/article/details/89390947

题目大意:给T组数据,之后一行n,m,k分别表示n个建筑,初始m个兵,一个兵生产一个兵要k时间。接下来n个数分别表示建造对应建筑要消耗的时间,求最少要多少时间?一个兵生产后还可以工作,工作后要将其移除。

思路:贪心,类似于哈夫曼建树的过程,具体思路见模拟哈夫曼建树(好题)

Code
错误思路

#include <iostream>
#include <queue>
#include <algorithm>
#include <stdio.h>

using namespace std;
const int maxn = (int)1e5+5;
typedef long long LL;

int num[maxn];
int n,m,k;
LL mT, now;

bool cmp (int a, int b) {
	return a > b;
}

int main() {
	int T;
	scanf("%d", &T);
	while (T--) {
		scanf("%d%d%d", &n, &m, &k);
		for (int i = 0; i < n; i++) {
			scanf("%d", &num[i]);
		}
		sort(num, num + n, cmp);
		mT = now = 0; //目前最大时间
		for (int i = 0; i < n;) {
			
			//只有1只并且不止有1栋建筑
			if (m == 1 && i < n - 1) {
				now += k;
				m *= 2;
				continue;
			}
			
			//只有1只并且只有1栋建筑
			if (m == 1 && i == n - 1) {
				mT = max(mT, now + num[i]);
				i++;
				continue;
			}
			
			//目前已经够人  全拉过去施工
			if (m + i >= n) {
				mT = max(mT, now + num[i]);
				break;
			}
			
			//如果本次建筑会让全局时间得到更新说明要也早建越好
			if (num[i] + now >= mT) {
				mT = max(mT, now + num[i]);
				m--;
				i++;
				continue;
			}
			
			//
			now += k;
			m *= 2;
		}
		printf("%lld\n", mT);
	}
	return 0;
}

正解

#include <iostream>
#include <stdio.h>
#include <queue>
#include <vector>

using namespace std;

int n,m,k;
priority_queue<int, vector<int>, greater<int> > num;

int main() {
	int T, tmp;
	scanf("%d", &T);
	while (T--) {
		while (!num.empty()) {
			num.pop();
		}
		scanf("%d%d%d", &n, &m, &k);
		for (int i = 0; i < n; i++) {
			scanf("%d", &tmp);
			num.push(tmp);
		}
		while (n > m) {
			n--;
			num.pop();
			tmp = num.top() + k; //最小的那个用来生产新胚胎
			num.pop();
			num.push(tmp);
		}
		while (num.size() > 1) {
			num.pop();
		}
		printf("%d\n",num.top());
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/calculate23/article/details/89390947