题解 | #哈夫曼树#
哈夫曼树
https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155
#include <iostream> #include<queue> #include<string> #include<cstdio> #include<cstring> using namespace std; int main() { int n; while (scanf("%d", &n) != EOF) { priority_queue<int, vector<int>, greater<int>> myPriorityQueue; while (n--) { int x; cin >> x; //注意这个地方不能有endl myPriorityQueue.push(x); } int answer = 0; while (myPriorityQueue.size() > 1) { int a = myPriorityQueue.top(); myPriorityQueue.pop(); int b = myPriorityQueue.top(); myPriorityQueue.pop(); answer += a + b; myPriorityQueue.push(a + b); } cout << answer << endl; } return 0; }