哈夫曼树哈夫曼编码

哈夫曼树哈夫曼编码
 

输入一组整型权值,构建哈夫曼树,实现哈夫曼编码,并输出带权路径长度。

#include<iostream>
#include<cstring>
using namespace std;
typedef char**HuffmanCode;

typedef struct
{
int weight;
int lchild,rchild,parent;
}HTNode,*HuffmanTree;
void min(HuffmanTree HT,int pos,int &s1,int &s2)
{
s1=pos;s2=pos;
for(int i=pos-1;i>=1;i--)
{
if(HT[i].parent==0&&HT[i].weight<=HT[s1].weight)
s1=i;
}
for(int i=pos-1;i>=1;i--)
{
if(HT[i].parent==0&&HT[i].weight<=HT[s2].weight&&i!=s1)
s2=i;
}
}
void CreatHT(HuffmanTree &HT,int n)
{
if(n<=1)
return;
int m=2*n-1;
HT=new HTNode[m+1];
for(int i=1;i<=m;++i)
{
HT[i].weight=0;HT[i].parent=0;HT[i].lchild=0;HT[i].rchild=0;
}
for(int i=1;i<=n;i++)
cin>>HT[i].weight;
for(int i=n+1;i<=m;i++)
{
int s1,s2;
min(HT,i-1,s1,s2);
HT[s1].parent=i;
HT[s2].parent=i;
HT[i].lchild=s1;
HT[i].rchild=s2;
HT[i].weight=HT[s1].weight+HT[s2].weight;
}
}
void CreatHC(HuffmanTree HT,HuffmanCode &HC,int n)
{
HC=new char*[n+1];
char *cd=new char[n];
cd[n-1]='\0';
for(int i=1;i<=n;i++)
{
int start =n-1;
int c=i,f=HT[i].parent;
while(f!=0)
{
if(c==HT[f].lchild)cd[--start]='0';
else cd[--start]='1';
c=f;
f=HT[c].parent;
}
HC[i]=new char[n-start];
strcpy(HC[i],&cd[start]);
}
delete cd;
}
int main()
{
HuffmanTree HT;
HuffmanCode HC;
int n,WPL=0,j;
cin>>n;
if(n>1)
{
CreatHT(HT,n);
CreatHC(HT,HC,n);
for(int i=1;i<=n;i++)
{
cout<<HT[i].weight<<"编码为";
for(j=0;HC[i][j]!='\0';j++)
{
cout<<HC[i][j];
//WPL+=j*HT[i].weight;
//cout<<endl;
//WPL=WPL+HT[i].weight*j;
}
//cout<<"WPL:"<<WPL;
WPL=WPL+HT[i].weight*j;
cout<<endl;

}
cout<<"WPL:"<<WPL;
}
else{
cout<<"error";
}
return 0;
}

posted @ 2023-11-30 15:26  涨涨涨张  阅读(21)  评论(0编辑  收藏  举报