-
Notifications
You must be signed in to change notification settings - Fork 0
/
Huffman_code.cpp
104 lines (85 loc) · 1.8 KB
/
Huffman_code.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//2019055078_½Å俵
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <string.h>
#include <queue>
using namespace std;
int freq[30001];
int arr[30001];
int n;
int N;
typedef struct node
{
node* right;
node* left;
int length;
double freq;
}node;
struct cmp {
bool operator()(const node& u, const node& v) {
return u.freq > v.freq;
}
};
priority_queue < node, vector<node>, cmp> pq;
node Tree() {
while (!pq.empty()) {
node* n1 = new node;
node* n2 = new node;
node* n3 = new node;
*n2 = pq.top();
pq.pop();
*n3 = pq.top();
pq.pop();
n1->left = n2;
n1->right = n3;
n1->freq = n2->freq + n3->freq;
pq.push(*n1);
if (pq.size() == 1) break;
}
return pq.top();
}
void bfs(node* r, int length) {
node* root1 = new node;
root1 = r;
root1->length = length;
if (root1->right == NULL && root1->left == NULL) {
freq[n] = length;
arr[n] = root1->freq;
n++;
delete[] root1;
}
else {
root1->left->length = length + 1;
root1->right->length = length + 1;
bfs(root1->left, root1->left->length);
bfs(root1->right, root1->right->length);
}
}
void HuffmanCodes() {
string s; int f;
cin >> N;
for (int i = 0; i < N; i++) {
node n;
cin >> s >> f;
n.freq = f;
n.left = NULL;
n.right = NULL;
pq.push(n);
}
int total;
cin >> total;
int fixed_length = int((log(N - 1) / log(2) + 1)) * total;
cout << fixed_length << endl;
node root = Tree();
bfs(&root, 0);
}
int main(void) {
HuffmanCodes();
int hc = 0;
for (int i = 0; i < N; i++) {
hc += freq[i] * arr[i];
}
cout << hc;
}