3345=数据结构实验之二叉树六:哈夫曼编码
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 char s[2000]; 5 int num[2000],queue[2000]; 6 void so(int s[],int l,int r) 7 { 8 if(l>=r)return; 9 int i=l,j=r; 10 int temp=s[l]; 11 while(i<j) 12 { 13 while(i<j&&s[j]>=temp)j--; 14 s[i]=s[j]; 15 while(i<j&&s[i]<=temp)i++; 16 s[j]=s[i]; 17 } 18 s[i]=temp; 19 so(s,l,i-1); 20 so(s,i+1,r); 21 } 22 int main() 23 { 24 while(~scanf("%s",s)) 25 { 26 int top = 0,i; 27 int len = strlen(s); 28 memset(num,0,sizeof(num)); 29 memset(queue,0,sizeof(queue)); 30 for(i=0; i<len; i++) 31 { 32 num[s[i]]++; 33 } 34 for(i=0; i<500; i++) 35 { 36 if(num[i]!=0) 37 { 38 queue[top++]=num[i]; 39 } 40 } 41 so(queue,0,top-1); 42 int be=0; 43 int sum=0; 44 //---------------------------------------------------------------------- 45 while(be!=top) 46 { 47 int x = queue[be++]; 48 if(be!=top) 49 { 50 int y = queue[be++]; 51 queue[top++] = x+y; 52 sum = sum+x+y; 53 so(queue,be,top-1); 54 } 55 } 56 printf("%d %d %.1lf\n",8*len,sum,8.0*len/sum); 57 } 58 return 0; 59 }