【模板】哈夫曼编码实现

哈夫曼树的模板(堆优化)

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
#include<iostream>
#include<queue>

using namespace std;
struct node {
int key;
char ch;
node *l, *r;
};

struct cmp {
bool operator()(node *a, node *b) {
return a->key > b->key;
}
};

priority_queue<node *, vector<node *>, cmp> q;
const int freq[8] = {7, 19, 2, 6, 32, 3, 21, 10};

node *init(int key, char ch) {
node *cur = new node;
cur->key = key;
cur->ch = ch;
cur->l = cur->r = NULL;
return cur;
}

int main() {
for (int i = 0; i < 8; i++) q.push(init(freq[i], i + 'a'));
while (q.size() != 1) {

node *cur1 = q.top();
q.pop();
node *cur2 = q.top();
q.pop();
node *cur = init(cur1->key + cur2->key, 0);
cur->l = cur1;
cur->r = cur2;
q.push(cur);
}
node *root = q.top(), *cur = q.top();
char ch;
while (~scanf("%c", &ch)) {
if (ch == '0') cur = cur->l;
else if (ch == '1') cur = cur->r;

if (cur->ch) {
printf("%c", cur->ch);
cur = root;
}
}

return 0;
}