-
Notifications
You must be signed in to change notification settings - Fork 1
/
哈夫曼stl.cpp
72 lines (68 loc) · 1.19 KB
/
哈夫曼stl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
int weight;
struct node *left, *right;
node(){
weight = 0;
left = right = NULL;
}
};
int m,n,sum;
vector<node> vec;
int main(){
void create(), solve();
cin >> m;
while (m--){
create();
solve();
}
return 0;
}
void create(){
cin >> n;
for (int i = 0; i < n; i++){
node temp;
cin >> temp.weight;
vec.push_back(temp);
}
}
void solve(){
bool mysort(node a, node b);
void show(node * root, int level);
sum = 0;
while (vec.size()>1){
sort(vec.begin(), vec.end(),mysort);
node *p1=new node, *p2 = new node, *q=new node;
*p1 = vec[0], *p2 = vec[1];
q->weight=p1->weight+p2->weight;
q->left=p1,q->right=p2;
vec.erase(vec.begin());
vec[0] = *q;
}
show(&vec[0], 0);
cout << sum<<endl;
vec.clear();
}
bool mysort(node a, node b){
return (a.weight < b.weight);
}
void show(node * root, int level){
if (root->left)
show(root->left, level + 1);
if (root->right)
show(root->right, level + 1);
if (root->left == NULL && root->right == NULL)
sum += root->weight*level;
}
void trase(node * root)
{
if(root)
{
cout<<root->weight<<' ';
trase(root->left);
trase(root->right);
}
}