哈夫曼树 SDUT 2127

链接 :http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2127&cid=1184

 

AC code  

130ms  和优先队列还是有一定差距的  

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <iostream>
 5 
 6 using namespace std;
 7 
 8 struct N
 9 {
10     int data;
11     N *l,*r;
12 };
13 
14 struct N *creat()
15 {
16     N *p = (N *)malloc(sizeof(N));
17     p->l = p->r = NULL;
18     return p;
19 }
20 
21 void insert(N *&root,int data)
22 {
23     if(root == NULL)
24     {
25         root = creat();
26         root->data = data;
27     }
28     else if(data >= root->data)
29     {
30         insert(root->r,data);
31     }
32     else
33     {
34         insert(root->l,data);
35     }
36 }
37 
38 int check(N *&root)
39 {
40     if(root->l == NULL)
41     {
42         int t = root->data;
43         root = root->r;
44         return t;
45     }
46     else
47         return check(root->l);
48 }
49 
50 int main()
51 {
52     int n,t,i,sum = 0;
53     cin>>n;
54     N *root = NULL;
55     for(i = 0 ;i < n; i++)
56     {
57         cin>>t;
58         insert(root,t);
59     }
60 
61     int a,b;
62 
63     for(i = 1;i < n; i++)
64     {
65         a = check(root);
66         b = check(root);
67         sum += a+b;
68         insert(root,a+b);
69     }
70 
71     cout<<sum<<endl;
72 
73     return 0;
74 
75 }

 

 

你可能感兴趣的:(哈夫曼树 SDUT 2127)