diff --git a/CMakeLists.txt b/CMakeLists.txt index fe98f1d..541e19b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,4 +11,6 @@ add_executable(data_structure_homework main.cpp problem3.cpp problem3.h problem4.cpp - problem4.h) + problem4.h + problem5.cpp + problem5.h) diff --git a/main.cpp b/main.cpp index 502deaa..b13dd23 100644 --- a/main.cpp +++ b/main.cpp @@ -5,6 +5,7 @@ #include "problem2.h" #include "problem3.h" #include "problem4.h" +#include "problem5.h" int main() { problem_1(); @@ -14,4 +15,6 @@ int main() { problem_3(); std::cout << "------------------------" << std::endl; problem_4(); + std::cout << "------------------------" << std::endl; + problem_5(); } diff --git a/problem5.cpp b/problem5.cpp new file mode 100644 index 0000000..cf90b76 --- /dev/null +++ b/problem5.cpp @@ -0,0 +1,86 @@ +// +// Created by grtsinry43 on 5/8/25. +// + +#include "problem5.h" + +#include +#include +#include +#include + +// 定义哈夫曼树节点 +struct HuffmanNode { + char character; + int frequency; + HuffmanNode *left; + HuffmanNode *right; + + HuffmanNode(char ch, int freq) : character(ch), frequency(freq), left(nullptr), right(nullptr) {} +}; + +// 比较器,用于优先队列 +struct Compare { + bool operator()(HuffmanNode *a, HuffmanNode *b) { + return a->frequency > b->frequency; + } +}; + +// 构建哈夫曼树 +HuffmanNode* buildHuffmanTree(const std::unordered_map &frequencyTable) { + std::priority_queue, Compare> pq; + + // 将每个字符和频率插入优先队列 + for (const auto &entry : frequencyTable) { + pq.push(new HuffmanNode(entry.first, entry.second)); + } + + // 构建哈夫曼树 + while (pq.size() > 1) { + HuffmanNode *left = pq.top(); pq.pop(); + HuffmanNode *right = pq.top(); pq.pop(); + + HuffmanNode *merged = new HuffmanNode('\0', left->frequency + right->frequency); + merged->left = left; + merged->right = right; + + pq.push(merged); + } + + return pq.top(); +} + +// 生成哈夫曼编码 +void generateHuffmanCodes(HuffmanNode *root, const std::string &code, std::unordered_map &huffmanCodes) { + if (!root) return; + + if (!root->left && !root->right) { + huffmanCodes[root->character] = code; + } + + generateHuffmanCodes(root->left, code + "0", huffmanCodes); + generateHuffmanCodes(root->right, code + "1", huffmanCodes); +} + +// 主函数 +int problem_5() { + // 示例字符频率表 + std::unordered_map frequencyTable = { + {'a', 5}, {'b', 9}, {'c', 12}, {'d', 13}, {'e', 16}, {'f', 45} + }; + + // 构建哈夫曼树 + HuffmanNode *root = buildHuffmanTree(frequencyTable); + + // 生成哈夫曼编码 + std::unordered_map huffmanCodes; + generateHuffmanCodes(root, "", huffmanCodes); + + // 输出每个字符的哈夫曼编码 + std::cout << "Huffman Codes:\n"; + for (const auto &entry : huffmanCodes) { + std::cout << entry.first << ": " << entry.second << "\n"; + } + + return 0; +} diff --git a/problem5.h b/problem5.h new file mode 100644 index 0000000..af658b8 --- /dev/null +++ b/problem5.h @@ -0,0 +1,10 @@ +// +// Created by grtsinry43 on 5/8/25. +// + +#ifndef PROBLEM5_H +#define PROBLEM5_H + +int problem_5(); + +#endif //PROBLEM5_H