哈夫曼树的创建

  1. 所有出现过的字符都作为叶子结点,放到优先队列
  2. 从优先队列中取两个出现频率最小的结点,将两个结点合并-->既创建一个新节点,这个节点的左右子树为刚才取出来的那两个频率最小的结点,这个结点的频率为这两个结点的频率之和。将这个新创建的结点重新放到优先队列中。
  3. 迭代步骤2,步骤2每次会让优先队列中少一个元素,所以总能让优先队列中只剩余一个元素。

这个剩余的元素就是整棵哈夫曼树的根节点。

从根节点遍历整棵树,遍历左树则让编码+"0",遍历右树则让编码+"1"。

将每一个叶子结点中的原始的字符都得到一个编码,计算长度既可,这个长度就是最短的。

#include <bits/stdc++.h>
#include <queue>
using namespace std;

struct Node {
    int c;
    double frequence;
    Node* left;
    Node* right;
};

struct Compare {
    bool operator()(Node* a, Node* b) {
        return a->frequence > b->frequence;
    }
};
long long ans = 0;
void dfs(Node* root, string s, vector<int>& a) {
    if (root->c != -1) {
        ans += a[root->c] * s.size();
    } else {
        if (root->left) dfs(root->left, s + '0', a);
        if (root->right) dfs(root->right, s + '1', a);
    }
}

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    long long sum = 0;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        sum += a[i];
    }
    priority_queue<Node*, vector<Node*>, Compare> pq;
    for (int i = 0; i < n; i++) {
        Node* t = new Node{i, a[i] * 1.0 / sum, nullptr, nullptr};
        pq.push(t);
    }
    while (pq.size() > 1) {
        auto x = pq.top();
        pq.pop();
        auto y = pq.top();
        pq.pop();
        Node * t = new Node{-1, x->frequence + y->frequence, x, y};
        pq.push(t);
    }
    auto t = pq.top();
    if (t->left) dfs(t->left, "1", a);
    if (t->right) dfs(t->right, "1", a);
    cout << ans << '\n';
}
// 64 位输出请用 printf("%lld")