哈夫曼编码贪心算法c++
时间: 2023-11-24 11:50:45 浏览: 122
以下是C++实现哈夫曼编码的贪心算法的示例代码:
```c++
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
// 定义哈夫曼树节点
struct HuffmanNode {
char ch; // 字符
int freq; // 频率
HuffmanNode* left; // 左子节点
HuffmanNode* right; // 右子节点
HuffmanNode(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
// 定义比较函数,用于优先队列
struct cmp {
bool operator()(HuffmanNode* a, HuffmanNode* b) {
return a->freq > b->freq;
}
};
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(unordered_map<char, int>& freqMap) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, cmp> pq;
for (auto& p : freqMap) {
pq.push(new HuffmanNode(p.first, p.second));
}
while (pq.size() > 1) {
HuffmanNode* left = pq.top();
pq.pop();
HuffmanNode* right = pq.top();
pq.pop();
HuffmanNode* parent = new HuffmanNode('$', left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 递归遍历哈夫曼树,生成编码表
void generateHuffmanCode(HuffmanNode* root, string code, unordered_map<char, string>& codeMap) {
if (!root) {
return;
}
if (root->ch != '$') {
codeMap[root->ch] = code;
}
generateHuffmanCode(root->left, code + "0", codeMap);
generateHuffmanCode(root->right, code + "1", codeMap);
}
// 哈夫曼编码
string huffmanEncode(string s) {
unordered_map<char, int> freqMap;
for (char c : s) {
freqMap[c]++;
}
HuffmanNode* root = buildHuffmanTree(freqMap);
unordered_map<char, string> codeMap;
generateHuffmanCode(root, "", codeMap);
string res = "";
for (char c : s) {
res += codeMap[c];
}
return res;
}
// 哈夫曼解码
string huffmanDecode(string s, HuffmanNode* root) {
string res = "";
HuffmanNode* cur = root;
for (char c : s) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (cur->ch != '$') {
res += cur->ch;
cur = root;
}
}
return res;
}
// 测试代码
int main() {
string s = "abacabad";
string encoded = huffmanEncode(s);
cout << "Encoded string: " << encoded << endl;
HuffmanNode* root = buildHuffmanTree({{'a', 2}, {'b', 2}, {'c', 1}, {'d', 1}});
string decoded = huffmanDecode(encoded, root);
cout << "Decoded string: " << decoded << endl;
return 0;
}
```
阅读全文