西电复试之——真题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;
}