哈夫曼建树

模板

建哈夫曼树方法

 1 //哈夫曼树的构造
 2 #include <iostream>
 3 #include <queue>
 4 using namespace std;
 5 
 6 //树的节点
 7 struct node{
 8     int num;//该点权值
 9     node* l;
10     node* r;
11 };
12 
13 //哈夫曼树根节点
14 node* root;
15 
16 struct cmp{
17     bool operator () (node* a, node* b){
18         return a-> num > b-> num;
19     }
20 };
21 
22 priority_queue<node*, vector<node*>, cmp> q;
23 
24 //建树思想:最开始每个节点都是一棵树,
25 //然后选最小权值的根节点2个,并移除这2个节点,
26 //将他们并成新树,加入到优先队列中
27 void create(){
28     //直到只剩一棵树时停止
29     while(q.size() > 1){
30         node* node1 = q.top();
31         q.pop();
32         node* node2 = q.top();
33         q.pop();
34 
35         node* sum = new node();
36         sum->l = node1;
37         sum->r = node2;
38         sum->num = node1->num+node2->num;
39 
40         root = sum;
41         q.push(sum);
42     }
43 }
44 
45 //遍历哈夫曼树,求WPL
46 long long dfs(node* node1){
47     if(node1->l == NULL){
48         return 0;
49     }
50     else{
51         return dfs(node1->l)+dfs(node1->r)+node1->num;
52     }
53 }
54 
55 int main()
56 {
57     int n, num;
58     while(cin >> n){
59         while(n--){
60             cin >> num;
61             node* data = new node();
62             data->l=data->r = NULL;
63             data->num = num;
64             q.push(data);
65         }
66         create();
67         if(n == 1) cout << 0 << endl;
68         else{
69             long long result = dfs(root);
70             cout << result << endl;
71         }
72         while(q.size()) q.pop();
73     }
74     return 0;
75 }
76 //POJ3253 G++

不建树的哈夫曼,思想和哈夫曼建树思想类似

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 int main()
 5 {
 6     int n, num;
 7     priority_queue<int, vector<int>, greater<int> > q;
 8     while(cin >> n){
 9         while(n--){
10             cin >>num;
11             q.push(num);
12         }
13         long long sum = 0;
14         while(q.size() > 1){
15             int num1 = q.top();
16             q.pop();
17             int num2 = q.top();
18             q.pop();
19             int he = num1 + num2;
20             sum+=he;
21             q.push(he);
22         }
23         cout << sum << endl;
24         while(q.size())q.pop();
25     }
26     return 0;
27 }
28 //POJ3252

 

posted @ 2016-02-21 16:17  喷水小火龙  阅读(77)  评论(0)    收藏  举报