【算法】算法之字符统计哈夫曼编码(C++源码)
一、任务描述
有一个英文句子str=“The following code computes the intersection of two arrays.”,请统计各个字符出现的次数,以其为频率构造对应的哈夫曼编码,将该英文句子进行编码以得到enstr。编写程序实现上述功能。
二、步骤描述
1、定义哈夫曼数组的结构体HTreeNode用ht[ ]表示,里面包含:字符data,权值weight,父亲结点p,左孩子lc,右孩子lr。
2、定义点的结构体nodetype,包含:字符data,权值weight,编号no,重载小于号字符,使权值小的先出队。
3、creat函数,初始化各个结点与优先队列里面的元素,设置所有结点的指针域,将n个结点进qu,构造哈夫曼树n-1个非叶子结点,出队权值最小的结点e1,出队权值次小的结点e2,构造哈夫曼树的非叶子结点j,修改e1.no的双亲为结点j,修改e2.no的双亲为结点j,构造队列结点e。
4、构造hafu函数,即编码,先构造叶子结点i的哈夫曼编码,while循环到根结点,如果当前结点cur为双亲f的左孩子,code加0,如果为右孩子,code加1,最后将哈夫曼编码得到保存在htcode数组里面。
5、在main函数里面初始化str数组为要求的句子,统计句子中的字符出现次数,保存在ht[ ]数组里面,调用creathafu函数。
6、输出结果。
三、运行结果截图
四、源代码(C++)
#include <iostream>
#include <bits/stdc++.h>
#define MAX 99
using namespace std;
int n=0;
struct HTreeNode
{
char data;
int weight;
int p;
int lc;
int rc;
}ht[MAX];
map<char,string> htcode; struct nodetype
{
int no;
char data;
int weight;
bool operator<(const nodetype&s)const
{
return weight<s.weight;
}
};
void creat()
{
nodetype e,e1,e2;
priority_queue<nodetype> qu;
for(int k=0;k<2*n-1;k++)
{
ht[k].lc=ht[k].rc=ht[k].p=-1;
}
for(int i=0;i<n;i++)
{
e.no=i;
e.data=ht[i].data;
e.weight=ht[i].weight;
qu.push(e);
}
for(int j=n;j<n*2-1;j++)
{
e1=qu.top();
qu.pop();
e2=qu.top();
qu.pop();
ht[j].weight=e1.weight+e2.weight;
ht[j].lc=e1.no;
ht[j].rc=e2.no;
ht[e1.no].p=j;
ht[e2.no].p=j;
e.no=j;
e.weight=e1.weight+e2.weight;
qu.push(e);
}
}
void hafu()
{
string code;
code.reserve(MAX);
for(int i=0;i<n;i++)
{
code=" ";
int cur=i;
int f=ht[cur].p;
while(f!=-1)
{
if(ht[f].lc==cur)
{
code='0'+code;
}
else
{
code='1'+code;
}
cur=f; f=ht[cur].p;
}
htcode[ht[i].data]=code;
}
}
int main()
{
char str[]={"The following code computes the intersection of two arrays"};
int k=strlen(str);
for(int i=0; i<k; i++)
{
if(str[i]==' ')
continue;
int flag=1;
for(int j=0; j<n; j++)
{
if(ht[j].data==str[i])
{
flag=0;
ht[j].weight++;
}
}
if(flag)
{
ht[n].data=str[i];
ht[n].weight++;
n++;
}
}
for(int i=0;i<n;i++)
{
cout<<"["<<ht[i].data<<"]"<<" the weight of is :"<<ht[i].weight<<endl;
}
creat();
hafu();
for(int i=0;i<n;i++)
{
cout<<"["<<ht[i].data<<"]"<<" the Huffman code of is :"<<htcode[ht[i].data]<<endl;
}
return 0;
}