# include <stdio.h>
# include <iostream>
# include <string.h>
using namespace std;


typedef struct			//define structure HuffmanTree
{   int weight;
    int parent,lchild,rchild;
}HTNode,*HuffmanTree;

typedef char **  HuffmanCode;

void Select(HuffmanTree HT,int i,int &s1,int &s2) ;//选出HT树到i为止,权值最小且parent为0的2个节点
void HuffmanTreeing(HuffmanTree &HT,int *w,int n);//构建哈夫曼树函数 

void output(HuffmanTree HT,int m);//输出哈夫曼树

int main()            		
{ 
	HuffmanTree HT;
	HuffmanCode HC;
	int n,i;
	int *w;
	scanf("%d",&n);
	w=(int *)malloc(n*sizeof(int));
  	for(i=0;i<n;i++)
	{
		scanf("%d",&w[i]);		
	}
	HuffmanTreeing( HT , w  ,n  );	
	cout<<"哈夫曼树:"<<endl;
	output(HT,2*n-1);	
	return 0;
}

void Select(HuffmanTree HT,int i,int &s1,int &s2)  
{ 	//选出HT树到i为止,权值最小且parent为0的2个节点
	//s1 is the least of HT[].weight
	//s2 is the second least of HT[].weight
	/********** Begin **********/ 
	int j,m=0x3f3f3f3f,n=0x3f3f3f3f;
	for(j=1;j<=i;j++){
		if(HT[j].weight<m && HT[j].parent==0){
			m=HT[j].weight;
			s1=j;
		}
	}
	int temp=HT[s1].weight;
	HT[s1].weight=0x3f3f3f3f;
	for(j=1;j<=i;j++){
		if(HT[j].weight<n && HT[j].parent==0){
			n=HT[j].weight;
			s2=j;
		}
	}
    HT[s1].weight=temp;
	/********** End **********/
} 


void HuffmanTreeing(HuffmanTree &HT,int *w,int n) //构建哈夫曼树函数
{ // w存放n个字符的权值(均>0),构造赫夫曼树HT
	/********** Begin **********/
	int i,m,s1,s2;
	HuffmanTree p;
	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=n+1;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;
	}
	/********** End **********/
}   


void output(HuffmanTree HT,int m)
{ //输出哈夫曼树
	for(int i=1;i<=m;++i)
	{   
		cout<<"HT["<<i<<"] ="<<HT[i].weight<<"\t"<<HT[i]. parent<<"\t";
		cout<<"\t" <<HT[i]. lchild <<"\t" <<HT[i]. rchild<<endl;
	}
}
posted on 2024-06-20 17:51  findscripter  阅读(13)  评论(0)    收藏  举报