codeup 21142: 合併果子(哈夫曼樹)

題目鏈接:點擊這裏
在這裏插入圖片描述

#include<cstdio>
#include<queue>
using namespace std;

//代表小頂堆的優先隊列
priority_queue<long long, vector<long long>, greater<long long> > q;

int main() 
{
	int n;
	long long temp, x, y, ans = 0;
	scanf("%d", &n);
	for(int i = 0; i < n;i++)
	{
		scanf("%lld", &temp);
		q.push(temp); //將初始重量壓入優先隊列
	}
	
	while(q.size() > 1)	//只要優先隊列中至少有兩個元素
	{
		x = q.top();
		q.pop();
		y = q.top();
		q.pop();
		q.push(x + y);  //取出堆頂的兩個元素,求和後壓入優先隊列
		ans += x+y;  //累計求和的結果
	}
	printf("%lld\n", ans);  //ans即爲消耗的最小體力
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章