#include<iostream>
#include<string>
#include<malloc.h>
using namespace std;
typedef struct{
char charname;
double weight;
int parent, lchild, rchild;
}HTNode, *HuffmanTree;
typedef char **HuffmanCode;
int n;
char *a;
double *b;
void TestNum()
{
n = 27;
a = new char[27];
b = new double[n];
char *Code[27] = {"space", "e", "t", "a", "o", "i", "n", "s", "h",
"r", "d", "l", "c", "u", "m", "w", "f", "g",
"y", "p", "b", "v", "k", "j", "x", "q", "z"};
for (int i = 0; i < n; i++)
{
a[i] = *Code[i];
}
double WeightNum[27] = {18.3, 10.2, 7.7, 6.8, 5.9, 5.8, 5.5, 5.1, 4.9,
4.8, 3.5, 3.4, 2.6, 2.4, 2.1, 1.9, 1.8, 1.7, 1.6,
1.6, 1.3, 0.9, 0.6, 0.2, 0.2, 0.1, 0.1};
for(int i = 0; i < n; i++)
{
b[i] = WeightNum[i];
}
}
void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,char *a,double *b,int n)
{
if(n<=1)
{
return;
}
int m = 2 * n - 1;
HT = (HuffmanTree)malloc((m+1)*sizeof(HTNode));
int i;
for(i = 1; i <= n; ++i)
{
HT[i].charname = a[i-1];
HT[i].weight = b[i-1];
HT[i].parent = HT[i].lchild = HT[i].rchild = 0;
}
for(; i <= m; ++i)
{
HT[i].charname = '0';
HT[i].weight = 0;
HT[i].parent = HT[i].lchild=HT[i].rchild = 0;
}
for(i = n + 1; i <= m; ++i)
{
int s1 = 0;
int s2 = 0;
for(s1 = 1; HT[s1].parent != 0;)
{
s1++;
}
for (int j = s1; j <= i - 1; j++)
{
if(HT[j].parent != 0)
{
continue;
}
s1 = HT[j].weight<HT[s1].weight?j:s1;
}
HT[s1].parent = i;
HT[i].lchild = s1;
for(s2 = 1; HT[s2].parent != 0;)
{
s2++;
}
for (int j = s2; j <= i - 1; j++)
{
if(HT[j].parent != 0)
{
continue;
}
s2 = HT[j].weight<HT[s2].weight?j:s2;
}
HT[s2].parent = i;
HT[i].rchild = s2;
HT[i].weight = HT[s1].weight+HT[s2].weight;
}
HC = (HuffmanCode)malloc((n+1)*sizeof(char*));
char *cd = (char*)malloc(n*sizeof(char));
cd[n-1] = '\0';
for (i = 1; i <= n; ++i)
{
int start = n-1, c, f;
for (c=i, f=HT[i].parent; f != 0; c = f, f = HT[f].parent)
{
if(HT[f].lchild==c)
{
cd[--start]='0';
}
else if(HT[f].rchild==c)
{
cd[--start]='1';
}
}
HC[i] = (char*)malloc((n-start) * sizeof(char));
f=n-start;
for(int d = 0; d < f; d++, start++)
{
HC[i][d]=cd[start];
}
}
}
void coutHC(HuffmanTree &HT,HuffmanCode &HC,int n, char* a)
{
for (int i = 1; i <= n; i++)
{
// cout<<"ok";
cout<<a[i]<<"的编码为:";
for(int d = 0; HC[i][d] != '\0'; d++)
{
cout<<HC[i][d];
}
cout<<endl;
}
}
void main()
{
HuffmanTree HT;
HuffmanCode HC;
TestNum();
HuffmanCoding(HT, HC, a, b, n);
coutHC(HT, HC, n, a);
}
第六周作业1——利用哈夫曼编码英文字母表】
最新推荐文章于 2023-10-11 16:33:15 发布