#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef struct{
int weight;
int parent,lchild,rchild;
}HTnode,*HuffmanTree;
typedef char **HuffmanCode;
int min(HuffmanTree t,int i){
int j,f=0;
int k=100;
for(j=1;j<=i;j++)
if(t[j].weight<k&&t[j].parent==0)
k=t[j].weight,f=j;
t[f].parent=1;
return f;
}
void Select(HuffmanTree t,int i,int &s1,int &s2){
int j;
s1=min(t,i);
s2=min(t,i);
if(s1>s2){
j=s1;
s1=s2;
s2=j;
}
}
void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n){
int m,i,s1,s2,start,c,f;
HuffmanTree p;
char *cd;
if(n<=1) return;
m=2*n-1;
HT=(HuffmanTree)malloc((m+1)*sizeof(HTnode));
for(p=HT+1,i=1;i<=n;++i,++p,++w){
(*p).weight=*w;
(*p).parent=0;
(*p).lchild=0;
(*p).rchild=0;
};
for(;i<=m;++i,++p){
(*p).weight=0;
(*p).parent=0;
(*p).lchild=0;
(*p).rchild=0;
}
for(i=n+1;i<=m;++i){ //建赫夫曼树
Select(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;
}
//HC=(HuffmanCode)malloc((n+1)*sizeof(char *));
HC=(HuffmanCode)malloc(n*sizeof(char *));
cd=(char *)malloc(n*sizeof(char));
cd[n-1]='\0';
for(i=1;i<=n;++i){
start=n-1;
for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)
if(HT[f].lchild==c) cd[--start]='0';
else cd[--start]='1';
HC[i]=(char *)malloc((n-start)*sizeof(char));
strcpy(HC[i],&cd[start]);
}
free(cd);
}
int main(){
HuffmanTree Ht;
HuffmanCode Hc;
int *w,n,i;
cout<<"输入个数:";
cin>>n;
w=(int *)malloc(n*sizeof(int));
cout<<"输入各权值:"<<endl;
for(i=0;i<=n-1;i++)
scanf("%d",w+i);
HuffmanCoding(Ht,Hc,w,n);
for(i=1;i<=n;i++)
puts(Hc[i]);
return 0;
}
哈夫曼树
最新推荐文章于 2022-07-25 10:49:36 发布