要求
根据给定的n个权值生成赫夫曼二叉树,输出赫夫曼编码及进行译码。
代码
#include<bits/stdc++.h>
int rootnum;
using namespace std;
typedef struct Node{
int weight;
int parent;
int rchild,lchild;
}HuffmanTree,*Tree;
void Initial(Tree root)
{
for(int i=0;i<300;i++){
root[i].lchild=-1;
root[i].rchild=-1;
root[i].parent=-1;
root[i].weight=0;
}
}
void output(Tree root)
{
for(int i=0;i<300;i++){
cout<<i<<' ';
if(i<126) cout<<(char)i<<' ';
cout<<root[i].lchild<<' ';
cout<<root[i].rchild<<' ';
cout<<root[i].parent<<' ';
cout<<root[i].weight<<' ';
cout<<endl;
}
}
void CalculateWeight(Tree root,char *s){
int lens=strlen(s);
for(int i=0;i<lens;i++){
root[(int)s[i]].weight++;
}
}
void find(Tree root,int &a,int &b){
for(int i=0;i<300;i++){
if(root[i].weight!=0&&root[i].parent==-1)
{
a=i;
break;
}
}
for(int i=a+1;i<300;i++){
if(root[i].weight!=0&&root[i].parent==-1)
{
b=i;
break;
}
}
for(int i=0;i<300;i++){
if(i==b) i++;
if(root[i].weight!=0 && root[i].parent==-1 && root[i].weight<root[a].weight)
a=i;
}
for(int i=0;i<300;i++){
if(i==a) i++;
if(root[i].weight!=0 && root[i].parent==-1 && root[i].weight<root[b].weight)
b=i;
}
}
void Creathuffman(Tree root){
int cnt=0;
for(int i=0;i<260;i++){
if(root[i].weight>0) cnt++;
}
cnt--;
int m,n,last=150;
for(int i=0;i<cnt;i++){
find(root,n,m);
root[last].weight=root[m].weight+root[n].weight;
root[m].parent=last;
root[n].parent=last;
root[last].lchild=m;
root[last].rchild=n;
last++;
rootnum=last-1;
}
}
void Creatres(Tree root,string res[]){
for(int i=0;i<130;i++){
if(root[i].weight!=0){
int q=i;
while(root[q].parent!=-1){
if(root[root[q].parent].rchild==q) res[i]+='0';
else res[i]+='1';
q=root[q].parent;
}
}
}
}
void fx(string res[]){
for(int i=0;i<130;i++)
{
int len=res[i].length();
for(int j=0;j<len/2;j++){
char a=res[i][j];
res[i][j]=res[i][len-1-j];
res[i][len-1-j]=a;
}
}
}
void Afterencoding(char s[],string res[]){//输出转码后
cout<<"编码后为"<<endl;
int lens=strlen(s);
for(int i=0;i<lens;i++)
cout<<res[s[i]];
cout<<endl;
}
void Decode(Tree root){
cout<<endl<<"解码模块"<<endl<<"请输入编码"<<endl;
char a[1000];
gets(a);
int lena=strlen(a);
int p=rootnum;
for(int i=0;i<lena;i++){
if(a[i]=='1') p=root[p].lchild;
else p=root[p].rchild;
if(root[p].lchild==-1 &&root[p].rchild==-1){
cout<<(char)p;
p=rootnum;
}
}
}
int main()
{
Tree root;
HuffmanTree a[300]; //128个可见字符
root=a;
Initial(root);
char s[1000];
gets(s);
CalculateWeight(root,s);//计算权重
Creathuffman(root);//建立树
string res[130];
Creatres(root,res);
fx(res);
cout<<endl<<"编码完成"<<endl<<"请输入你要编码的字符串"<<endl;
gets(s);
Afterencoding(s,res);//输出
Decode(root); //解码
return 0;
}