-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuffmantree
83 lines (76 loc) · 1.15 KB
/
huffmantree
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
73
74
75
76
77
78
79
80
81
82
83
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
class Hftree {
private:
int val;
char sym;
Hftree* left;
Hftree* right;
public:
Hftree(int v, char s, Hftree *l, Hftree *r)
{
val = v;
sym = s;
left = l;
right = r;
}
~Hftree()
{
}
int weight()
{
return val;
}
void PreOrder(Hftree *r)
{
if (r)
{
cout << r->val << " " << r->sym << "\t";
PreOrder(r->left);
PreOrder(r->right);
}
}
};
class cmp {
public:
bool operator()(Hftree*l, Hftree *r)
{
return l->weight() > r->weight();
}
};
Hftree* CreateHftree(int v[], char s[], int n)
{
priority_queue < Hftree*, vector<Hftree*>, cmp> Q;
for (int i = 0; i < n; i++)
{
Hftree *r = new Hftree(v[i], s[i], NULL, NULL);
Q.push(r);
}
while (Q.size() > 1)
{
Hftree *lc = Q.top();
Q.pop();
Hftree *rc = Q.top();
Q.pop();
Hftree *parent = new Hftree(lc->weight() + rc->weight(), 't', lc, rc);
Q.push(parent);
}
return Q.top();
}
int main()
{
Hftree *r;
int n;
cin >> n;
int *v = new int[n + 1];
char *s = new char[n + 1];
for (int i = 0; i < n; i++)
{
cin >> s[i] >> v[i];
}
r = CreateHftree(v, s, n);
r->PreOrder(r);
return 0;
}