学习记录~
#include<iostream>
#include<ctime>
#include<cmath>
using namespace std;
typedef char ElemType;
struct HfNode
{
int weight;
int lchild, rchild, parent;
ElemType data;
ElemType* hc;
};
class HuffManTree
{
private:
HfNode* root;
int num;
void Select(int n, int& i1, int& i2);
public:
HuffManTree(int* w,ElemType c[], int n);
void PrintfHfmanTree();
void GreatHuffManCode();
void DeCoding(char *c);
void PrintfHfCode();
};
int main()
{
int w[] = { 35,25,15,15,10};
char p[] = "110110100100100001010111";
ElemType c[] = { 'A','B','C','D','E'};
HuffManTree h(w,c, 5);
cout << "哈夫曼编码树为\n";
h.PrintfHfmanTree();
cout << endl;
h.GreatHuffManCode();
cout << "字符编码表为\n";
h.PrintfHfCode();
cout << "对以下编码串进行解码为\n";
cout << p << endl;
h.DeCoding(p);
return 0;
}
void HuffManTree::Select(int n, int& i1, int& i2)
{
int i;
for (i = 0; i < n; i++)
{
if (root[i].parent == -1)
{
i1 = i;
break;
}
}
for (i = 0; i < n; i++)
{
if (root[i].parent == -1 && root[i].weight < root[i1].weight)
{
i1 = i;
}
}
for (i = 0; i < n; i++)
{
if (root[i].parent == -1 && i != i1)
{
i2 = i;
break;
}
}
for (i = 0; i < n; i++)
{
if (root[i].parent == -1 && root[i].weight < root[i2].weight && i1 != i)
i2 = i;
}
}
HuffManTree::HuffManTree(int* w,ElemType c[], int n)
{
int i,i1,i2;
root = new HfNode[2 * n - 1];
num = n;
for (i = 0; i < 2 * n-1; i++)
root[i].lchild = root[i].parent = root[i].rchild = -1;
for (i = 0; i < num; i++)
{
root[i].weight = w[i];
root[i].data = c[i];
}
for (i = num; i < 2 * num - 1; i++)
{
Select(i, i1, i2);
root[i].weight = root[i1].weight + root[i2].weight;
root[i].lchild = i1; root[i].rchild = i2;
root[i1].parent = i; root[i2].parent = i;
}
}
void HuffManTree::PrintfHfmanTree()
{
for (int i = 0; i < 2 * num - 1; i++)
{
cout << i << " ";
if(i>=0&&i<num)
cout << root[i].data << " ";
if (i >=num)
cout << " ";
cout << root[i].weight << " " << root[i].parent << " ";
cout << root[i].lchild << " " << root[i].rchild << endl;
}
}
void HuffManTree::GreatHuffManCode()
{
int i;
for(i=0;i<num;i++)
root[i].hc = new ElemType[num];
ElemType* cd = new ElemType[num];
cd[num-1] = 0;
int start,f,c;
for (i = 0; i < num; i++)
{
start = num - 1;
c = i;//当前结点下标
f = root[i].parent;//双亲下标
while (f != -1)
{
--start;
if (root[f].lchild == c)cd[start] = '0';
else cd[start] = '1';
c = f; f = root[f].parent;
}
strcpy(root[i].hc,&cd[start]);
}
delete cd;
}
void HuffManTree::DeCoding(char *c)
{
int i = 0,j=0;
while (c[i])
{
j = 2*num-1-1;//每次从根结点开始j表示下表
while (root[j].lchild != -1 || root[j].rchild != -1)
{
if (c[i] == '0')
{
j = root[j].lchild; i++;
}
else
{
j = root[j].rchild; i++;
}
}
cout << root[j].data;
}
}
void HuffManTree::PrintfHfCode()
{
for (int i = 0; i < num; i++)
{
cout << i << " ";
cout << root[i].data << " " << root[i].weight << " ";
cout << root[i].hc << endl;
}
}