题目5: 哈夫曼编/译码器 [问题描述]
利用哈夫曼编码进行通信可以大大提高信道利用率,缩短信息传输时间,降低传输成本。但是,这要求在发送端通过一个编码系统对待传数据预先编码,在接收端将传来的数据进行译码(复原)。对于双工信道(即可以双向传输信息的信道),每端都需要一个完整的编/译码系统。试为这样的信息收发站写一个哈夫曼码的编/译码系统。
[基本要求] 一个完整的系统应具有以下功能:
1、I:初始化(Initialization)。从终端读入字符集大小n,以及n个字符和n个权值,建立哈夫曼树,并将它存于文件hfmTree中。
2、 E:编码(Encoding)。利用以建好的哈夫曼树(如不在内存,则从文件hfmTree中读入),
对文件ToBeTran中的正文进行编码,然后将结果存入文件CodeFile中。
3、D:译码(Decoding)。利用已建好的哈夫曼树将文件CodeFile中的代码进行译码,结果存入文件TextFile中。 1、
P:打印代码文件(Print)。将文件CodeFile以紧凑格式显示在终端上,每行50个代码。
同时将此字符形式的编码文件写入文件CodePrin中。 2、 T:打印哈夫曼树(Tree
Printing)。将已在内存中的哈夫曼树以直观的方式(树或凹入
表形式)显示在终端上,同时将此字符形式的哈夫曼树写入文件TreePrint中。
代码:
//要编码的正文存储在tobetran.txt文件中,得到的结果存入codefile文件中
//译码的结果存在于textfile.txt文件中
//二进制编码存在于codeprin中
//哈夫曼树存在于treeprin中
//-abcdefghijklmnopqrstuvwxyz
//186 64 13 22 32 103 21 15 47 57 1 5 32 20 57 63 15 1 48 51 80 23 8 18 1 16 1
//this problem is my favourite
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef struct
{
int weight; //节点权值
int lchild,rchild,parent; //左右孩子和双亲的下标
} HTNode,*HuffmanTree;
void menu()
{
cout<<"================================================="<<endl;
cout<<"| ******哈夫曼树编码与译码****** |"<<endl;
cout<<"| 1.创建哈夫曼树 |"<<endl;
cout<<"| 2.生成二进制码 |"<<endl;
cout<<"| 3.哈夫曼编码 |"<<endl;
cout<<"| 4.哈夫曼译码 |"<<endl;
cout<<"| 5.显示代码文件 |"<<endl;
cout<<"| 6.打印哈夫曼树 |"<<endl;
cout<<"| 7.退出 |"<<endl;
cout<<"================================================="<<endl;
}
void Select(HuffmanTree HT,int n,int &s1,int &s2)
{
int i=1;
while(HT[i].parent!=0&&i<=n)
i++;
if(i==n+1)
return ;
s1=i;
i++;
while(HT[i].parent!=0&&i<=n)
i++;
if(i==n+1)
return ;
s2=i;
i++;
if(HT[s1].weight>HT[s2].weight)
swap(s