哈夫曼编码构造
作者:
Ronin_56
,
2024-10-04 21:59:57
,
所有人可见
,
阅读 2
// 构造一棵哈夫曼树
#include <iostream>
#include <cstring>
#include <algorithm>
#define MAX_INT 1e9
using namespace std;
typedef struct {
char data;
int weight;
int parent, lchild, rchild;
} HTNode, *HuffmanTree;
typedef char ** HuffmanCode;
int n, m;
void CreateHuffmanTree(HuffmanTree &HT, int n)
{
if (n <= 1) return ;
m = 2 * n - 1;
HT = new HTNode[m + 1];
for (int i = 1; i <= m; ++ i) HT[i].parent = HT[i].lchild = HT[i].rchild = -1;
for (int i = 1; i <= n; ++ i) {
cin >> HT[i].weight;
}
for (int i = n + 1; i <= m; ++ i)
{
int min1 = MAX_INT, min2 = MAX_INT;
int lnode = -1, rnode = -1;
for (int j = 1; j <= i - 1; ++ j)
{
if (HT[j].parent == -1 && HT[j].weight < min1)
{
min2 = min1, rnode = lnode;
min1 = HT[j].weight, lnode = j;
}
else if (HT[j].parent == -1 && HT[j].weight < min2)
{
min2 = HT[j].weight, rnode = j;
}
}
HT[lnode].parent = HT[rnode].parent = i;
HT[i].lchild = lnode, HT[i].rchild = rnode;
HT[i].weight = HT[lnode].weight + HT[rnode].weight;
}
}
void CreateHuffmanCode(HuffmanTree &HT, HuffmanCode &HC, int n)
{
HC = new char* [n + 1];
char* cd = new char[n];
cd[n - 1] = '\0';
for (int i = 1; i <= n; ++ i)
{
int start = n - 1;
int c = i, f = HT[c].parent;
while (f != -1)
{
-- start;
if (HT[f].lchild == c) cd[start] = '0';
else cd[start] = '1';
c = f, f = HT[f].parent;
}
HC[i] = new char[n - start];
strcpy(HC[i], &cd[start]);
}
delete cd;
}
int main()
{
cin >> n;
HuffmanTree HT;
HuffmanCode HC;
CreateHuffmanTree(HT, n);
CreateHuffmanCode(HT, HC, n);
for (int i = 1; i <= n; ++ i)
{
printf("%s\n", HC[i]);
}
return 0;
}