Huffman树
利用贪心的思想,每次从当前所有堆中,挑出最小的两堆合并即可。
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int main()
{
int n;
cin >> n;
// 利用小根堆动态维护最小值
priority_queue<int, vector<int>, greater<int>> heap;
while (n -- ) {
int x;
cin >> x;
heap.push(x);
}
int res = 0;
while (heap.size() > 1) {
int a = heap.top(); heap.pop();
int b = heap.top(); heap.pop();
res += a + b;
heap.push(a + b);
}
cout << res << endl;
return 0;
}
标签:int,res,pop,52,算法,heap,include,Huffman
From: https://www.cnblogs.com/I-am-Sino/p/17044589.html