在网上搜到一篇比较全面的讲解Huffman,先保存。

    http://blog.csdn.net/hairetz/archive/2009/05/05/4151866.aspx

   

    POJ1521 Entropy

    http://acm.pku.edu.cn/JudgeOnline/problem?id=1521

    题目很长,读完后就发现时赤裸裸的哈夫曼编码

代码
1 #include <iostream>
2 #include <queue>
3 #include <vector>
4  using namespace std;
5
6 const int maxn = 1000000;
7
8 struct cmp {
9 bool operator () (const int &x, const int &y) const {
10 return x > y;
11 }
12 } ;
13 priority_queue< int , vector<int> , cmp > que;
14 int A, B, len;
15 char a[maxn], c;
16
17 void init()
18 {
19 len = strlen(a);
20 A = len * 8 , B = 0;
21 while(!que.empty()) que.pop();
22 sort(a, a + len);
23 }
24
25 void push_val()
26 {
27 c = a[0];
28 int t = 1;
29 for(int i=1; i < len; i++) {
30 if(c == a[i]) {
31 t ++;
32 } else {
33 que.push(t);
34 c = a[i];
35 t = 1;
36 }
37 }
38 que.push(t);
39 }
40
41 int main()
42 {
43 while(gets(a)) {
44 if(strcmp(a , "END") == 0) break;
45
46 init();
47 push_val();
48
49 if(c == a[0]) {
50 B = len;
51 printf("%d %d %.1f\n", A, B, double(A) / double(B));
52 continue;
53 }
54
55 while(!que.empty())
56 {
57 int x = que.top();
58 que.pop();
59
60 if(que.empty()) break;
61
62 int y = que.top();
63 que.pop();
64
65 B += (x + y);
66 que.push(x + y);
67 }
68 printf("%d %d %.1f\n", A, B, double(A) / double(B));
69 }
70 return 0;
71 }
72

 

posted on 2010-05-22 01:14  xIao.wU 思维磁场  阅读(260)  评论(0编辑  收藏  举报