xiao菜鸡也要有大成长


私信TA

用户名:dotcpp0729093

访问量:326

签 名:

believe or not

等  级
排  名 814
经  验 3599
参赛次数 0
文章发表 14
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

#icnlude<iostream>
using namespace std;//每次都从权值中重新挑选最小的两位 
typedef struct
{
	int weight;//权值 
	int parent,lchild,rchild;//结点的双亲,左孩,右孩 
}HTNode,*HuffmanTree;
void Select(HuffmanTree HT,int end,&si,&s2)
{
	int min1,min2;
	int i=1;
	while(HT[i].parent!=0&&i<=end)//找到第一个点 
	{
		i++;
	}
	min1=HT[i].weight;
	s1=i;
	i++;
	while(HT[i].parent!=0&&i<=end)//找到第二个点 
	{
		i++;
	}
	if(HT[i].weight<min1)//比较大小 ,如果更小,则,min1保留更小,min2保留一般小 
	{min2=min1;
	s2=s1;
	min1=HT[i].weight;
	s1=i;	
	}
	else 
	{
		min2=HT[i].weight;
		s2=i;
	}
	/*接着往下找*/ 
	for(int j=i+1;j<=end;j++)
	{
		if(HT[i].parent!=0)//从剩余的点里找到更小的比较 
		continue;
		if(HT[i].weight<min1)
		{
			min2=min1;
			min1=HT[i].weight;
			s2=s1;
			s1=j;
		}
		else if(HT[i].weight>=min1&&HT[i].weight<min2)
		{
			min2=HT[j].weight;
			s2=j;
		}
	}
	
}
void CreateHuffmanTree(HuffmanTree &HT,int n)
{
	if(n<=1) 
	return;
	m=2*n-1;//有n个叶子结点的哈夫曼树有2n-1个结点 ????
	HT=new HTNode[m+1];//0号坐标不使用,但有2n个结点,所以+1 
	for(int i=1;i<=m;i++)//初始化 
	{
		HT[i].parent=0;
		HT[i].lchild=0;
		HT[i].rchild=0;
	}
//////////*创建部分*/////////////
int s1=0,s2=0; 
	for(int i=1;i<=m;i++) 
	cin>>HT[i].weight;//输入各点的权值
	for(int i=n+1;i<=m;++i)
	{
		Select(HT,i-1,s1,s2);//在HT[k](k>=1&&k<=i-1)里找两个双亲域为0,且权值最小的结点,并返回他们的序号 
		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;
	}
 }


 

0.0分

0 人评分

  评论区