PkU ACM 1521(哈夫曼编码)

虽然对huffman树的算法思想已经了解,但是却不能将之熟练的变成代码程序,希望通过此次训练使自己对huffman的编程思想更加的了解!

(下面的程序为请教同学而得到!)

#include<iostream> 
#include<cstring> 
using namespace std;
struct T{
	int weight; //权值 
	int parent,lchild,rchild;
}node[60];
int main()
{
	char ch[100000];
	int hash[35];
	int i,j,k,len;
	while(cin>>ch,strcmp(ch,"END")!=0)
	{
		memset(hash,0,sizeof(hash));
		len=strlen(ch);
		for(i=0;i<len;i++)
		{
			hash[ch[i]-64]++;    //ch数组为大写字母串 
		}
		for(i=1,j=1;i<35;i++)
		{
			if(hash[i]!=0)
			{
				node[i].weight=hash[i];
				node[j].parent=node[j].lchild=node[j].rchild=0;
				j++;
			}
		}
		j--;
	    for(i=j+1;i<j*2;i++)
	    node[i].parent=node[i].lchild=node[i].rchild=0;
	    for(i=j+1;i<j*2;i++)
	    {
	    	int m1,m2;
	    	m1=m2=999999;    //!!老是忘记对定义初始值
	    	int x1,x2;
	    	for(k=1;k<i;k++)
	    	{
	    		if(node[k].weight<m1&&node[k].parent==0)
	    		{
	    			m2=m1;
	    			x2=x1;
	    			m1=node[k].weight;
	    			x1=k;
	    		}
	    		else
	    		  if(node[k].weight<m2&&node[k].parent==0)
	    		  {
	    		  	m2=node[k].weight;
	    		  	x2=k;
	    		  }
	    	}
	    	node[i].weight=m1+m2;
	    	node[i].rchild=x1;
	    	node[i].lchild=x2;
	    	node[x1].parent=i;
	    	node[x2].parent=i;
	    }
	    int sum=0;
	    int cnt;
	    for(i=1;i<j+1;i++)
	    {
	    	k=i;
	    	cnt=0;
	    	while(node[k].parent!=0)
	    	{
	    		k=node[k].parent;
	    		cnt++;
	    	}
	    	sum+=cnt*node[i].weight;
	    }
	    if(j==1)
	    sum=len;
	    float ratio;
	    ratio=float(len*8)/sum;
	    printf("%d %d %.1f\n",len*8,sum,ratio); 
	} 
	return 0;
}

你可能感兴趣的:(PkU ACM 1521(哈夫曼编码))