`
wsql
  • 浏览: 11795887 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Hdu 1053 Entropy查出错(修改)

 
阅读更多
#pragma warning(disable : 4786)

#include<iostream>

#include<string>

#include<vector>

#include<algorithm>

using namespace std;



struct Node

{

	int weight;

	int parent,lchild,rchild;

};



int findMinIndex(vector <Node> &ht,int n)

{

	int min=INT_MAX, minIndex=0;



	for(int i=1;i<n;i++)

	{

		if (ht[i].parent==0 && ht[i].weight<min) 

		{

			minIndex=i;

			min=ht[i].weight;

		}

	}



	ht[minIndex].parent=n;



	return minIndex;

}



vector <Node> createHuffman(vector <int> weight)

{

	int n=weight.size();

	int m=2*n-1;



	vector <Node> ht(m+1);

	int i;

	for(i=1;i<=m;i++) 

	{

		ht[i].weight=ht[i].parent=ht[i].lchild=ht[i].rchild=0;

		if (i<=n) ht[i].weight=weight[i-1];		

	}



	for(i=n+1;i<=m;i++)

	{

		int s1=findMinIndex(ht,i);

		int s2=findMinIndex(ht,i);

		ht[i].lchild=s1;

		ht[i].rchild=s2;

		ht[i].weight=ht[s1].weight+ht[s2].weight;

	}



	return ht;

}



vector <string> codeHuffman(vector <Node> ht, int n)

{

	vector <string> hc(n+1,"");



	for(int i=1;i<=n;i++)

	{

		int parent=ht[i].parent, j=i;



		while(parent!=0)

		{

			if (ht[parent].lchild==j) 

				hc[i]='0'+hc[i];

			else

				hc[i]='1'+hc[i];

			j=parent;

			parent=ht[j].parent;

		}

	}



	return hc;

}



bool run()

{

	string s;

	cin>>s;

	if (s=="END") return false;

	

	sort(s.begin(),s.end());



	vector <int> weight;



	int cnt=1,n=s.size();



	for(int i=1;i<n;i++)

	{

		if (s[i-1]==s[i])

		{

			cnt++;

		}

		else

		{

			weight.push_back(cnt);			

			cnt=1;

		}

	}



	weight.push_back(cnt);



	vector <Node> ht=createHuffman(weight);



	vector <string> result=codeHuffman(ht,weight.size());



	int m=0;

	for(int j=0;j<weight.size();j++)

	{

		m+=result[j+1].size()*weight[j];

	}



	if (m==0)

		printf("%d %d %.1lf/n",n*8,n,8.0);

	else

		printf("%d %d %.1lf/n",n*8,m,n*8.0/m);



	return true;

}



int main()

{

	while(run());

	return 0;

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics