哈夫曼编码算法实现完整版讲课讲稿

  • 格式:doc
  • 大小:64.50 KB
  • 文档页数:10

下载文档原格式

  / 10
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

哈夫曼编码算法实现

完整版

实验三树的应用

一.实验题目:

树的应用——哈夫曼编码

二.实验内容:

利用哈夫曼编码进行通信可以大大提高信道的利用率,缩短信息传输的时间,降低传输成本。根据哈夫曼编码的原理,编写一个程序,在用户输入结点权值的基础上求哈夫曼编码。

要求:从键盘输入若干字符及每个字符出现的频率,将字符出现的频率作为结点的权值,建立哈夫曼树,然后对各个字符进行哈夫曼编码,最后打印输出字符及对应的哈夫曼编码。

三、程序源代码:

#include

#include

#include

#include

typedef struct{

char data;

int weight;

int parent,lchild,rchild;

}HTNode,*HuffmanTree;

typedef char * * HuffmanCode;

void Select(HuffmanTree &HT,int n,int m)

{HuffmanTree p=HT;

int tmp;

for(int j=n+1;j<=m;j++)

{int tag1,tag2,s1,s2;

tag1=tag2=32767;

for(int x=1;x<=j-1;x++)

{ if(p[x].parent==0&&p[x].weight

{ tag1=p[x].weight;s1=x;}

}

for(int y=1;y<=j-1;y++)

{ if(p[y].parent==0&&y!=s1&&p[y].weight

{ tag2=p[y].weight;s2=y;}

}

if(s1>s2) //将选出的两个节点中的序号较小的始终赋给s1 { tmp=s1; s1=s2; s2=tmp;}

p[s1].parent=j;

p[s2].parent=j;

p[j].lchild=s1;

p[j].rchild=s2;

p[j].weight=p[s1].weight+p[s2].weight;

}

}

void HuffmanCoding(HuffmanTree &HT,int n,char *w1,int*w2) {

int m=2*n-1;

if(n<=1) return;

HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));

HuffmanTree p=HT;

for(int i=1;i<=n;i++)

{ p[i].data=w1[i-1];

p[i].weight=w2[i];

p[i].parent=p[i].lchild=p[i].rchild=0;

}

for(;i<=m;i++)

{ p[i].weight=p[i].parent=p[i].lchild=p[i].rchild=0; }

Select(HT,n,m);

ofstream outfile; //生成hfmTree文件

outfile.open("hfmTree.txt",ios::out);

for (i=1;i<=m;i++)

{outfile<

}

outfile.close();

cout<<"初始化结果已保存在hfmTree文件中\n";

}

void ToBeTree() //将正文写入文件ToBeTree中

{

ofstream outfile;

outfile.open("ToBeTree.txt",ios::out);

outfile<<"THIS PROGRAM IS MYFAVORITE";

outfile.close();

}

void Encoding(HuffmanTree &HT,int n) //编码

{

HuffmanCode HC;

HC=(HuffmanCode)malloc((n+1)*sizeof(char *));

char *cd;

cd=(char *)malloc(n*sizeof(char));

cd[n-1]='\0';

for(int k=1;k<=n;k++)

{ int start=n-1;

for(int c=k,f=HT[k].parent;f!=0;c=f,f=HT[f].parent) { if(HT[f].lchild==c) cd[--start]='0';

else cd[--start]='1';

}

HC[k]=(char *)malloc((n-start)*sizeof(char));

strcpy(HC[k],&cd[start]);

}

cout<<"输出哈夫曼编码:"<

for(int h=1;h<=n;h++) //输出编码

{ cout<

cout<

cout<<" ";

if (h%8==0) cout<

}

cout<

ToBeTree();

//读取TOBETREE文件里的正文,并进行编码

fstream infile;

infile.open("ToBeTree.txt",ios::in);

char s[80];

while(!infile.eof())

{infile.getline(s,sizeof(s));}

infile.close();

fstream outfile;

outfile.open("CodeFile.txt",ios::out);

int count=0;

for (h=0;s[h]!='\0';h++)

{ for(k=1;k<=n;k++)

if (s[h]==HT[k].data)

{ cout<