poj 1521 Entropy

来源:互联网 发布:二次元淘宝店 编辑:程序博客网 时间:2024/05/16 08:42

//哈夫曼树应用     

//一种特殊情况  全为一种字符时,特殊处理

点击打开链接

#include<stdio.h>
#include<string.h>
int N=27;
typedef struct
{
        char c;
  int w;
  int f,l,r;
}HNode,*Htree;
typedef struct
{
  char c;
  int codenum;
}Hcode, *Huffman;

void creat_HuffmanTree(HNode HT[],int n1 )
{
  int i,j;
  int low1,low2;
  int p1=0,p2=0; 
  for ( i=N+1; i<=n1; i++ )
          {
    low1=999,low2=999;
    for ( j=1;j<i;j++)
    {
      if ( HT[j].f==0 && HT[j].w<low1)
      {
        low1=HT[j].w;
        p1=j;
      }    
    }
    for ( j=1;j<i;j++)
      if ( HT[j].f==0 && HT[j].w<low2 && j!=p1 )
      {
        low2=HT[j].w;
        p2=j;
      }
    HT[p1].f=i;   
    HT[p2].f=i; 
    HT[i].l=p1; 
    HT[i].r=p2;    
    HT[i].w=low1+low2; 
  }
}
void creat_Huffmancoding( HNode HT[],Hcode HC[],int n2)
{            
  int i,j,ff;
  for ( i=1;i<=n2;i++ )
  {
    ff=i;
    j=0;
    while ( HT[ff].f!=0 )
    {
      j++;
      ff=HT[ff].f;
    }
    HC[i].codenum=j;
  }
}
int main()
{
    char s[1000];
    int i,j,t1,t2;
    HNode HT[54];
    Hcode HC[28];
    while (scanf ("%s",s)  &&  strcmp(s,"END")!=0)
    {         int a[28]={0};
              for ( i=0;i<strlen(s);i++)
              if (s[i]=='_')
                 a[27]++;
              else  
                 a[s[i]-'A'+1]++;
              for ( j=i=1;i<=27;i++ )
                  if (a[i]!=0)
                  {
                              if (i!=27)
                              HT[j].c=i-1+'A';
                              else HT[j].c='_';
                  HT[j++].w=a[i]; 
                  }
         N=j-1;
         for ( i=1;i<=2*N-1;i++)
               {      
      HT[i].f=HT[i].l=HT[i].r=0;
               }
               creat_HuffmanTree(HT,2*N-1);
               creat_Huffmancoding( HT,HC,N);
               for ( t2=0,i=1;i<=N;i++)
               {
               t2+=HT[i].w*HC[i].codenum;
               }
               if (N!=1)
               printf ("%d %d %0.1f\n",strlen(s)*8,t2,strlen(s)*8*1.0/t2);
               else printf ("%d %d %0.1f\n",strlen(s)*8,strlen(s),8.0);
    }
    return 0;
    }