#include <iostream>
#include <string>
#define n 4
#define m 2*n-1
using namespace std;
const int MAX = 100;
typedef struct
{
int weight;
int parent, lchild, rchild;
} HuffmanTree;
typedef HuffmanTree hfmtree[m + 1];
typedef struct
{
char ch;
char code[n + 1];
} CodeNode;
typedef CodeNode hfmcode[n + 1];
void CreateHuffmanTree(HuffmanTree tree[])
{
int m1, m2;
int l, r;
for(int i = 1; i <= m; i++)
{
tree[i].weight = 0;
tree[i].lchild = 0;
tree[i].rchild = 0;
tree[i].parent = 0;
}
cout << "请输入" << n << "个结点的权值:" << endl;
for(i = 1; i <= n; i++)
{
cin >> tree[i].weight;
}
for(i = n + 1; i <= m; i++)
{
m1 = m2 = 32767;
l = r = 0;
for(int k = 1; k <= i - 1; k++)
if(tree[k].parent == 0)
if(tree[k].weight < m1)
{
m2 = m1;
r = l;
m1 = tree[k].weight;
l = k;
}
else if(tree[k].weight < m2)
{
m2 = tree[k].weight;
r = k;
}
tree[l].parent = i;
tree[r].parent = i;
tree[i].lchild = l;
tree[i].rchild = r;
tree[i].weight = tree[l].weight + tree[r].weight;
}
}
void ShowHuffmanTree(HuffmanTree tree[])
{
cout << "哈夫曼数的最终状态:" << endl;
cout << "权值,双亲,左孩子,右孩子:" << endl;
for(int i = 1; i <= m; i++)
cout << tree[i].weight << "," << tree[i].parent << "," << tree[i].lchild << ","
<< tree[i].rchild << endl;
cout << endl;
}
void HuffmanCoding(HuffmanTree tree[], CodeNode H[])
{
int start, c, p;
char cd[n + 1], chh;
cd[n] = '\0';
cout << "请输入各结点的字符:(" << "共" << n << "个)" << endl;
for(int i = 1; i <= n; i++)
{
cin >> chh;
H[i].ch = chh;
start = n;
c = i;
while(p = tree[c].parent)
{
if(tree[p].lchild == c)
cd[--start] = '0';
else
cd[--start] = '1';
c = p;
}
strcpy(H[i].code, &cd[start]);
}
cout << endl;
for(i = 1; i <= n; i++)
cout << "第" << i << "个字符" << H[i].ch << "的编码为:" << H[i].code << endl;
}
void main()
{
hfmtree t;
hfmcode h;
CreateHuffmanTree(t);
HuffmanCoding(t, h);
ShowHuffmanTree(t);
}