写出哈夫曼树和哈夫曼编码的实现只用stdio和iostream
时间: 2023-06-28 13:11:12 浏览: 98
哈夫曼树和哈夫曼编码的实现
下面是哈夫曼树和哈夫曼编码的实现示例,仅使用了stdio和iostream库:
```c++
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int MAXN = 10005;
int n;
int w[MAXN];
int parent[MAXN], lc[MAXN], rc[MAXN];
char code[MAXN][MAXN];
struct Node {
int id, w;
bool operator<(const Node& o) const {
return w > o.w;
}
};
void huffman() {
priority_queue<Node> q;
for (int i = 1; i <= n; ++i) {
q.push({i, w[i]});
}
int id = n + 1;
while (q.size() > 1) {
Node x = q.top();
q.pop();
Node y = q.top();
q.pop();
parent[x.id] = parent[y.id] = id;
lc[id] = x.id;
rc[id] = y.id;
w[id] = x.w + y.w;
q.push({id, w[id]});
++id;
}
}
void dfs(int u, char* cur) {
if (lc[u] == 0 && rc[u] == 0) {
strcpy(code[u], cur);
return;
}
int len = strlen(cur);
cur[len] = '0';
dfs(lc[u], cur);
cur[len] = '1';
dfs(rc[u], cur);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &w[i]);
}
huffman();
dfs(n * 2 - 1, code[n * 2 - 1]);
for (int i = 1; i <= n; ++i) {
printf("char %c : %s\n", 'A' + i - 1, code[i]);
}
return 0;
}
```
上述代码实现了哈夫曼树和哈夫曼编码的构建,其中用到了优先队列和深度优先遍历。在输入时,需要先输入字符集的大小n,然后依次输入每个字符的权值。输出时,对于每个字符,输出它的字符编码。
阅读全文