通信的电文由字符集中的字母构成,每个字母在电文中会有一个出现的频率。为这些字母设计相应的哈夫曼编码!
方法:每次在哈夫曼树构造过程中,两个最小数的选择总是最小的在左,而次小的在右。
输入输出样例:1组
#1
样例输入:
abcdefg#\\#代表结束符
0.31
0.16
0.10
0.08
0.11
0.20
0.04\\代表每个字母的出现频率
样例输出:
a:11
b:101
c:010
d:1001
e:011
f:00
g:1000
//注意
//1:该程序每次运行的时间必须小于10秒,否则会超时,程序超时将不会测试剩余的测试集
//2:该程序每次运行使用的内存不能超过1M,否则会返回错误
//3:该程序每次运行输出的结果最多显示1000个字符(多余的不显示),每行末尾的所有空格用□表示
#include <iostream>
#define Maxsize 1024
using namespace std;
typedef struct
{
float weight;
int parent;
int lchild;
int rchild;
}HNodeType;
typedef struct
{
int bit[Maxsize];
int start;
}HCodeType;
HCodeType HuffCode[Maxsize];
void Create_HuffMTree(HNodeType HFMTree[],int n);
void HaffmanCode(HNodeType HFMTree[],HCodeType HuffCode[],int n);
int main()
{
char arr[Maxsize];
int i=0;
char x;
cin>>x;
while(x!='#')
{
arr[i++]=x;
cin>>x;
}
int n;
n=i;//n为叶子节点的个数
HNodeType HFMTree[Maxsize];
Create_HuffMTree(HFMTree,n);
//cout<<HFMTree[5].lchild;
//cout<<HFMTree[5].rchild;
HaffmanCode(HFMTree,HuffCode,n);
for(i=0;i<n;i++)
{
cout<<arr[i]<<":";
for(int j=HuffCode[i].start;j<n;j++)
cout<<HuffCode[i].bit[j];
cout<<endl;
}
return 0;
}
void Create_HuffMTree(HNodeType HFMTree[],int n)//建立哈夫曼树
{
float x1,x2;
int m1,m2;
int i,j;
for(i=0;i<2*n-1;i++)//初始化
{
HFMTree[i].weight=0;
HFMTree[i].parent=-1;
HFMTree[i].lchild=-1;
HFMTree[i].rchild=-1;
}
for(i=0;i<n;i++)
{
cin>>HFMTree[i].weight;//输入叶子节点的权值
}
for(i=0;i<n-1;i++)//左小右大
{
x1=x2=Maxsize;
m1=m2=0;
for(j=0;j<n+i;j++)
{
if(HFMTree[j].parent==-1&&HFMTree[j].weight<x1)
{
x2=x1;m2=m1;
x1=HFMTree[j].weight;
m1=j;
}
else if(HFMTree[j].parent==-1&&HFMTree[j].weight<x2)
{
x2=HFMTree[j].weight;
m2=j;
}
}
HFMTree[m1].parent=n+i;//创建双亲结点
HFMTree[m2].parent=n+i;
HFMTree[n+i].weight=HFMTree[m1].weight+HFMTree[m2].weight;
HFMTree[n+i].lchild=m1;
HFMTree[n+i].rchild=m2;
}
}
void HaffmanCode(HNodeType HFMTree[],HCodeType HuffCode[],int n)//哈夫曼编码
{
HCodeType cd;
int i,j,c,p;
for(i=0;i<n;i++)
{
cd.start=n-1;
c=i;
p=HFMTree[c].parent;
while(p!=-1)
{
if(HFMTree[p].lchild==c)
cd.bit[cd.start]=0;
else
cd.bit[cd.start]=1;
cd.start--;
c=p;
p=HFMTree[c].parent;
}
for(j=cd.start+1;j<n;j++)
HuffCode[i].bit[j]=cd.bit[j];
HuffCode[i].start=cd.start+1;
}
}