题解 | #哈夫曼树#
哈夫曼树
https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155
#include <iostream> #include <queue> using namespace std; struct Element { int value; }; bool operator<(Element l, Element r) { return l.value > r.value; } int main() { int n; while (scanf("%d", &n) != EOF) { int sum = 0; priority_queue<Element> pqueue; for (int i = 0; i < n; i++) { int t; scanf("%d", &t); Element e; e.value = t; pqueue.push(e); }//完成小根堆的构建 while (1 < pqueue.size()) { int t1, t2; t1 = pqueue.top().value; pqueue.pop(); t2 = pqueue.top().value; pqueue.pop(); sum = sum + t1 + t2; Element e; e.value = t1 + t2; pqueue.push(e); } cout << sum << endl; } return 0; }