STL -- 优先队列

版权声明:蒟蒻写博客不宜,请随文附上原文链接 https://blog.csdn.net/qq_34493840/article/details/85254646

STL真是个好东西

题目描述
在一个果园里,多多已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆。多多决定把所有的果子合成一堆。
每一次合并,多多可以把两堆果子合并到一起,消耗的体力等于两堆果子的重量之和。可以看出,所有的果子经过 n-1n−1 次合并之后, 就只剩下一堆了。多多在合并果子时总共消耗的体力等于每次合并所耗体力之和。
因为还要花大力气把这些果子搬回家,所以多多在合并果子时要尽可能地节省体力。假定每个果子重量都为 11 ,并且已知果子的种类 数和每种果子的数目,你的任务是设计出合并的次序方案,使多多耗费的体力最少,并输出这个最小的体力耗费值。

样例
输入 输出
3 1 2 9 15

#include <bits/stdc++.h>

using namespace std;

inline int read() {
	int s = 0, w = 1;
	char ch = getchar();
	while(!isdigit(ch)) { if(ch == '-') w = -1; ch = getchar(); }
	while(isdigit(ch)) { s = (s << 1) + (s << 3) + ch - '0'; ch = getchar();}
	return s * w;
}

#define MAXX 11000

int n;
int a[MAXX];
int res = 0;
priority_queue<int,vector<int>,greater<int> >q;

int main() {
	n = read(); 
	for(int i = 1; i <= n; ++i) {
		a[i] = read();
		q.push(a[i]);
	}
	while(q.size() >= 2) {
		int a = q.top();
		q.pop();
		int b = q.top();
		q.pop();
		res += (a + b);
		q.push(a + b);
	}
	printf("%d\n", res);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34493840/article/details/85254646
今日推荐