返回首页 C++ 模板

哈夫曼树模板

最优编码树——带权路径长度最短的二叉树

哈夫曼 编码 优先队列 GESP6
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    priority_queue<int, vector<int>, greater<int>> pq;
    for (int i = 0; i < n; i++) {
        int w; cin >> w;
        pq.push(w);
    }

    // 每次取最小的两个合并
    int totalCost = 0;
    while (pq.size() > 1) {
        int a = pq.top(); pq.pop();
        int b = pq.top(); pq.pop();
        totalCost += a + b;
        pq.push(a + b);
    }

    cout << totalCost << endl;  // 最小带权路径长度
    return 0;
}

📖 要点说明

⚠️ 常见错误