hdu 1053Entropy

(顺便说一下,前面的一道Box Relations,这一题我是根据别人的代码写的,构造那个图很难的说,我也是品味了好久才品出真味来的。

http://blog.csdn.net/me4546/article/details/6576517

huffman编码是也

一用到指针就容易出错,~~~~(>_<)~~~~ 该死的,是我对指针没有理解清楚吗?~_~

View Code
  1 #include <cstdio>
2 #include <cstring>
3 #include <queue>
4 using namespace std;
5
6 struct node
7 {
8 int num;
9 bool term;
10 struct node *right,*left;
11 bool friend operator < (const node& a,const node& b)
12 {
13 return a.num > b.num;
14 }
15 }fir,*pa,*pb;
16
17 priority_queue<node> q;
18 int ins;
19 int re[1000];
20 bool vis[1000];
21 int sum;
22 char s[2000];
23
24 void create()
25 {
26 while(!q.empty())
27 {
28 if(q.size() == 1)
29 break;
30 node a = q.top();
31 q.pop();
32 node b = q.top();
33 q.pop();
34 pa = new node;
35 pb = new node;
36 pa ->num = a.num;//这里将a,b装换成指针是根据别人的代码来的
37 pa ->left = a.left;
38 pa -> term = a.term;
39 pa ->right = a.right;
40 pb ->num = b.num;
41 pb ->left = b.left;
42 pb -> term = b.term;
43 pb ->right = b.right;
44 fir.num = a.num + b.num;
45 fir.right = pa;
46 fir.left = pb;
47 fir.term = false;
48 q.push(fir);
49 }
50 fir = q.top();
51 }
52
53 void find(node *t,int n)
54 {
55 //printf("t:%d %d %d %d %d %d\n",&t,t->num,t->term,t->left,t->right,n);
56 if(t -> term == true)
57 {
58 sum += t -> num * n;
59 return;
60 }
61 find((t -> right),n + 1);
62 find((t -> left),n + 1);
63 }
64
65 int main()
66 {
67 while(scanf("%s",s) == 1)
68 {
69 if(!strcmp(s,"END"))
70 break;
71
72 memset(vis,false,sizeof(vis));
73 memset(re,0,sizeof(re));
74
75 ins = 0;
76 int len = strlen(s);
77 for(int i = 0;i < len;i ++)
78 {
79 if(!vis[i])
80 {
81 for(int j = i;j < len;j ++)
82 {
83 if(s[j] == s[i])
84 {
85 re[ins] ++;
86 vis[j] = true;
87 }
88 }
89 ins ++;
90 }
91 }
92 if(ins == 1)
93 {
94 printf("%d %d 8.0\n",re[0]*8,re[0]);
95 continue;
96 }
97 while(!q.empty())
98 q.pop();
99
100 for(int i = 0;i < ins;i ++)
101 {
102 node a;
103 a.num = re[i];
104 a.left = NULL;
105 a.right = NULL;
106 a.term = true;
107 q.push(a);
108 }
109
110 create();
111 sum = 0;
112 find(&fir,0);//如果把fir换成指针就容易出错,可是这是为什么啊?
113 printf("%d %d %.1lf\n",len*8 ,sum,len*8.0/sum);
114 }
115
116 return 0;
117 }
原文地址:https://www.cnblogs.com/Shirlies/p/2411480.html