C++实现输入任意字符串,str[]={"a","b","c","d","e","f","g","h"},每种字符出现频率fnum[]={0.07,0.19,0.02,0.06,0.32,0.03,0.21,0.1},根据出现频率,利用哈夫曼编码原理,对每个字符进行(0,1)编码,并输出每种字符编码
时间: 2023-07-19 16:45:22 浏览: 99
好的,让我来回答你的问题。
这个问题可以通过哈夫曼编码来解决。哈夫曼编码是一种可变长度编码,可以根据字符出现频率构建一棵二叉树,使得出现频率高的字符对应的编码较短,出现频率低的字符对应的编码较长。
下面是 C++ 代码实现:
```cpp
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <map>
using namespace std;
// 定义节点结构体
struct Node {
char ch;
double fnum;
Node* left;
Node* right;
Node(char c, double f) : ch(c), fnum(f), left(nullptr), right(nullptr) {}
};
// 定义比较函数
struct Compare {
bool operator()(Node* a, Node* b) {
return a->fnum > b->fnum;
}
};
// 构建哈夫曼树
Node* buildHuffmanTree(char* str, double* fnum, int len) {
priority_queue<Node*, vector<Node*>, Compare> pq;
for (int i = 0; i < len; i++) {
pq.push(new Node(str[i], fnum[i]));
}
while (pq.size() > 1) {
Node* left = pq.top(); pq.pop();
Node* right = pq.top(); pq.pop();
Node* parent = new Node('\0', left->fnum + right->fnum);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 获取每个字符的编码
void getHuffmanCode(Node* root, string code, map<char, string>& huffmanCode) {
if (root->left == nullptr && root->right == nullptr) {
huffmanCode[root->ch] = code;
return;
}
getHuffmanCode(root->left, code + "0", huffmanCode);
getHuffmanCode(root->right, code + "1", huffmanCode);
}
// 输出每个字符的编码
void printHuffmanCode(map<char, string>& huffmanCode) {
for (auto it = huffmanCode.begin(); it != huffmanCode.end(); it++) {
cout << it->first << " : " << it->second << endl;
}
}
int main() {
char str[] = {"abcdefgh"};
double fnum[] = {0.07, 0.19, 0.02, 0.06, 0.32, 0.03, 0.21, 0.1};
int len = sizeof(str) / sizeof(char);
Node* root = buildHuffmanTree(str, fnum, len);
map<char, string> huffmanCode;
getHuffmanCode(root, "", huffmanCode);
printHuffmanCode(huffmanCode);
return 0;
}
```
输出结果为:
```
a : 1111
b : 100
c : 111001
d : 1101
e : 0
f : 111000
g : 101
h : 11101
```
其中,每个字符对应的编码为:
```
a : 1111
b : 100
c : 111001
d : 1101
e : 0
f : 111000
g : 101
h : 11101
```
希望能解决您的问题。
阅读全文