Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.hdu.edu.cn/showproblem.php?pid=1053

哈夫曼树

View Code
 1 //1053
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <queue>
 5 using namespace std;
 6 
 7 const int L=10000,N=60;
 8 char str[L];
 9 int c[30];
10 int lch[N],rch[N],w[N],sz;
11 typedef pair<int,int> pii;
12 priority_queue<pii,vector<pii>,greater<pii> > q;
13 int dfs(int p,int h)
14 {
15     if(lch[p]==0 && rch[p]==0)
16         return w[p]*h;
17     return dfs(lch[p],h+1)+dfs(rch[p],h+1);
18 }
19 int main()
20 {
21     while(scanf("%s",str),strcmp(str,"END"))
22     {
23         memset(c,0,sizeof(c));
24         for(int i=0;str[i];i++)
25         {
26             int ch = str[i]=='_'?26:str[i]-'A';
27             c[ch]++;
28         }
29         sz=0;
30         for(int i=0;i<=26;i++) if(c[i]>0)
31         {
32             sz++;
33             w[sz]=c[i];
34             lch[sz]=rch[sz]=0;
35             q.push(make_pair(w[sz],sz));
36         }
37         int n=sz;
38         for(int i=1;i<n;i++)
39         {
40             int a=q.top().second; q.pop();
41             int b=q.top().second; q.pop();
42             sz++;
43             w[sz]=w[a]+w[b];
44             lch[sz]=a; rch[sz]=b;
45             q.push(make_pair(w[sz],sz));
46         }
47         q.pop();
48         int s1=strlen(str)*8;
49         int s2 = n==1?w[sz]:dfs(sz,0);
50         printf("%d %d %.1lf\n",s1,s2,(double)s1/s2);
51     }
52     return 0;
53 }

 

posted on 2012-05-02 23:31  Qiuqiqiu  阅读(306)  评论(0编辑  收藏  举报