`
java-mans
  • 浏览: 11521061 次
文章分类
社区版块
存档分类
最新评论

poj1521 (huffman +优先队列)

 
阅读更多

//第一次写huffman,顺便学一下STL

#include<iostream>
#include<queue>
#include<cstdio>

using namespace std;

//以下STL是参考过来的,再次感到STL的强大
class cmp
{
public:
	bool operator()(int x,int y)
	{
		return x>y;
	}
};
priority_queue<int ,vector<int>,cmp> Q;

int main()
{
	char str[500];
	
	while(gets(str))
	{
		if(!strcmp(str,"END"))break;
		int len=strlen(str),i;
		int c[200];
		memset(c,0,sizeof(c));
		for(i=0;i<len;i++)
			c[str[i]]++;
		for(i=0;i<200;i++)
			if(c[i])
				Q.push(c[i]),c[i]=0;
			int sum=0;
			if(Q.size()==1)sum=len;//要注意的一点,只有一种字母时sum为len
			while(Q.size()>1)//队列的实现
			{
				int a=Q.top();Q.pop();
				int b=Q.top();Q.pop();
				sum+=a+b;
				Q.push(a+b);
			}
			while(!Q.empty())
				Q.pop();
			printf("%d %d %.1lf\n",8*len,sum,(double)8*len/double(sum));
	}
	return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics