西電覆試之——真題2011D 哈夫曼樹

西電覆試之——真題2011D 哈夫曼樹

1 優先隊列

//基礎知識
priority_queue<int> q;
//push()時間複雜度O(logN)
q.push(3);
//優先隊列沒有front()函數和back()函數(隊列中隊首隊尾),只能用top()訪問隊首元素O(1)
q.top();
//pop()時間複雜度O(logN)
q.pop();
//q.empty() O(1)
q.empty();
//q.size() O(1)
q.size();

1.1 priority_queue內元素優先級的設置

//下面兩種優先隊列的定義是等價的
priority_queue<int> q;
//less<int>表示數字大的優先級大,greater<int>表示數字小的優先級越大
priority_queue<int,vector<int>,less<int>>q;

2 真題

輸入樣例:
8
7 19 2 6 32 3 21 10
輸出樣例:
261
使用優先隊列模擬哈夫曼樹的帶權路徑長度

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

priority_queue < int, vector<int>, greater<int>> q;

int main() {
	int n;
	int temp, x, y, ans = 0;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> 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;
	}
	cout << ans;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章