题解 | #哈夫曼树#
哈夫曼树
https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155
#include <functional> #include <iostream> #include <queue> #include <vector> using namespace std; int main() { int n, a; while (cin >> n) { priority_queue<int, vector<int>, greater<int>> pq; for (int i = 0; i < n; i++) { cin >> a; pq.push(a); } int res = 0; for (int i = 0; i < n - 1; i++) { int a = pq.top(); pq.pop(); int b = pq.top(); pq.pop(); pq.push(a + b); res += a + b; } cout << res << endl; } }