题解 | #搬水果#

搬水果

https://www.nowcoder.com/practice/e4c775b0f3ee42a4bb72c26d2e1eef8a

实质为哈夫曼树
#include <iostream>
#include<queue>
using namespace std;

struct hafuman {
	int value;
};

bool operator < (hafuman lhs, hafuman rhs) {
	return lhs.value > rhs.value;   //变成小根堆
}
int main() {
	int n,dot;
	while (cin >> n) {
		int a, b, res = 0 ; //res表示带权路径长度
		priority_queue<hafuman>  HafumanTree;
		for (int i = 0; i < n; i++) {
			cin >> dot;
			hafuman c;
			c.value = dot;
			HafumanTree.push(c);  //传入小根堆
		}
		while (!HafumanTree.empty()) {
			a = HafumanTree.top().value;
			HafumanTree.pop();
			if (HafumanTree.empty()) break;
			b = HafumanTree.top().value;
			HafumanTree.pop();
			hafuman c;
			c.value = a + b;
			HafumanTree.push(c);
			res = res + a + b;


		}
		cout << res << endl;

	}

}

全部评论

相关推荐

Gaynes:查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务