哈夫曼编码的精简C++代码

#include
#include
#include
#include

using namespace std;

// 哈夫曼树节点
struct Node {
    char data;
    int frequency;
    Node* left;
    Node* right;

    Node(char data, int frequency) : data(data), frequency(frequency), left(nullptr), right(nullptr) {}
};

// 优先队列中的比较函数
struct CompareNodes {
    bool operator()(Node* const& lhs, Node* const& rhs) {
        return lhs->frequency > rhs->frequency;
    }
};

// 生成哈夫曼树
Node* buildHuffmanTree(unordered_map& frequencies) {
    priority_queue, CompareNodes> minHeap;

    // 初始化优先队列
    for (auto& entry : frequencies) {
        minHeap.push(new Node(entry.first, entry.second));
    }

    // 构建哈夫曼树
    while (minHeap.size() > 1) {
        Node* left = minHeap.top();
        minHeap.pop();

        Node* right = minHeap.top();
        minHeap.pop();

        Node* internalNode = new Node('$', left->frequency + right->frequency);
        internalNode->left = left;
        internalNode->right = right;

        minHeap.push(internalNode);
    }

    return minHeap.top();
}

// 生成哈夫曼编码表
void generateHuffmanCodes(Node* root, string code, unordered_map& huffmanCodes) {
    if (!root)
        return;

    if (root->data != '$') {
        huffmanCodes[root->data] = code;
    }

    generateHuffmanCodes(root->left, code + "0", huffmanCodes);
    generateHuffmanCodes(root->right, code + "1", huffmanCodes);
}

int main() {
    // 输入字符及其频率
    unordered_map frequencies = {
        {'a', 5},
        {'b', 9},
        {'c', 12},
        {'d', 13},
        {'e', 16},
        {'f', 45}
    };

    // 构建哈夫曼树
    Node* root = buildHuffmanTree(frequencies);

    // 生成哈夫曼编码表
    unordered_map huffmanCodes;
    generateHuffmanCodes(root, "", huffmanCodes);

    // 输出结果
    cout << "Huffman Codes:\n";
    for (const auto& entry : huffmanCodes) {
        cout << entry.first << ": " << entry.second << '\n';
    }

    return 0;
}
 

你可能感兴趣的:(算法)