- 4
- 0
- 约 8页
- 2017-07-03 发布于湖北
- 举报
哈夫曼编码算汇编
实验三 树的应用
一.实验题目:
树的应用——哈夫曼编码
二.实验内容:
利用哈夫曼编码进行通信可以大大提高信道的利用率,缩短信息传输的时间,降低传输成本。根据哈夫曼编码的原理,编写一个程序,在用户输入结点权值的基础上求哈夫曼编码。
要求:从键盘输入若干字符及每个字符出现的频率,将字符出现的频率作为结点的权值,建立哈夫曼树,然后对各个字符进行哈夫曼编码,最后打印输出字符及对应的哈夫曼编码。
三、程序源代码:
#include iostream
#include fstream
#include string.h
#include stdlib.h
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==0p[x].weighttag1)
{ tag1=p[x].weight;s1=x;}
}
for(int y=1;y=j-1;y++)
{ if(p[y].parent==0y!=s1p[y].weighttag2)
{ tag2=p[y].weight;s2=y;}
}
if(s1s2) //将选出的两个节点中的序号较小的始终赋给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++)
{outfileHT[i].weight\tHT[i].parent\tHT[i].lchild
\tHT[i].rchild\tendl;
}
outfile.close();
cout初始化结果已保存在hfmTree文件中\n;
}
void ToBeTree() //将正文写入文件ToBeTree中
{
ofstream outfile;
outfile.open(ToBeTree.txt,ios::out);
outfileTHIS 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==
您可能关注的文档
最近下载
- 班本课程引领完美教室缔造.doc VIP
- 2025年高级经济师《人力资源管理》预测试卷一.pdf VIP
- 大班数学《有趣的测量》PPT课件.pptx VIP
- Q-SHEC-J100012-2022 栈桥设计指南(中交二航局).pdf VIP
- 辽宁省名校联盟2025届高三下学期3月联合考试(一模)物理试卷含答案.docx VIP
- 体例格式10:工学一体化课程《小型网络安装与调试》任务2学习任务信息页.docx VIP
- 律师事务所与分所管理办法.docx VIP
- 《环境工程技术经济》课程教学大纲.docx VIP
- 北京市朝阳区2025-2026学年九年级上学期期末语文试题(原卷版).pdf VIP
- 中班数学:有趣的梯形.pptx VIP
原创力文档

文档评论(0)