c++实现霍夫曼编码:实现任意Q符号的N重序列信源的最优R进制编码
时间: 2024-02-13 20:05:30 浏览: 96
c++实现的哈夫曼编码
以下是C++实现任意Q符号的N重序列信源的最优R进制编码的代码示例:
```c++
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <cmath>
using namespace std;
// 定义哈夫曼树的节点
struct Node {
string str;
int freq;
Node* left;
Node* right;
Node(string s, int f) : str(s), freq(f), left(NULL), right(NULL) {}
~Node() {
delete left;
delete right;
}
};
// 定义哈夫曼树节点的比较器
struct NodeComparator {
bool operator()(Node* a, Node* b) { return a->freq > b->freq; }
};
// 哈夫曼编码函数
unordered_map<string, string> huffmanEncoding(vector<string>& seq, int n, int r) {
// 统计序列出现的频率
unordered_map<string, int> freqMap;
for (int i = 0; i < seq.size(); i += n) {
string str = seq.substr(i, n);
freqMap[str]++;
}
// 将序列频率信息转换为节点信息
priority_queue<Node*, vector<Node*>, NodeComparator> minHeap;
for (auto pair : freqMap) {
minHeap.push(new Node(pair.first, pair.second));
}
// 构建哈夫曼树
while (minHeap.size() > 1) {
Node* left = minHeap.top();
minHeap.pop();
Node* right = minHeap.top();
minHeap.pop();
Node* parent = new Node(left->str + right->str, left->freq + right->freq);
parent->left = left;
parent->right = right;
minHeap.push(parent);
}
// 构建哈夫曼编码表
unordered_map<string, string> encodingMap;
function<void(Node*, string)> dfs = [&](Node* node, string code) {
if (!node) {
return;
}
if (node->str.length() == n) {
encodingMap[node->str] = code;
}
dfs(node->left, code + "0");
dfs(node->right, code + "1");
};
dfs(minHeap.top(), "");
// 将编码表转换为R进制编码表
unordered_map<string, string> rEncodingMap;
for (auto pair : encodingMap) {
string str = pair.second;
int num = 0;
for (int i = 0; i < str.length(); i++) {
num += (str[i] - '0') * pow(2, i);
}
string rEncoding = "";
while (num > 0) {
rEncoding = to_string(num % r) + rEncoding;
num /= r;
}
rEncodingMap[pair.first] = rEncoding;
}
return rEncodingMap;
}
int main() {
string seq = "ABCDEABCDEABCDEABCDE";
int n = 3;
int r = 5;
vector<string> subSeqs;
for (int i = 0; i < seq.length(); i += n) {
subSeqs.push_back(seq.substr(i, n));
}
unordered_map<string, string> encodingMap = huffmanEncoding(subSeqs, n, r);
for (auto pair : encodingMap) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
```
上述代码中,首先使用 `unordered_map` 统计序列中各个子序列的出现频率,然后将频率信息转换为节点信息,并使用最小堆构建哈夫曼树。接着使用深度优先搜索构建哈夫曼编码表,并返回编码表。最后,将编码表转换为R进制编码表,并输出各个子序列对应的编码。
阅读全文