-
Notifications
You must be signed in to change notification settings - Fork 0
/
huffman-coding.cpp
100 lines (81 loc) · 2.28 KB
/
huffman-coding.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
#include <bits/stdc++.h>
using namespace std;
// This class represents each node of the min heap
class MinHeapNode {
public:
char data; // chararcter
int freq; // frequency
MinHeapNode *left, *right; // left & right child
// default constructor
MinHeapNode() {
data = '$';
freq = 0;
left = right = nullptr;
}
// initialize value node value
MinHeapNode(char data, int freq) {
this->data = data;
this->freq = freq;
left = right = nullptr;
}
};
// This comparator will be used for creating min heap
class compare {
public:
bool operator()(MinHeapNode* l, MinHeapNode* r) {
// if left freq > right freq return true
// else false
return (l->freq > r->freq);
}
};
// utility function for printing heap
void printCodes(MinHeapNode* root, string str) {
// if root == null then return
if(!root)
return;
// if current node is not a internal node
// print its code
if(root->data != '$')
cout<<root->data<<" : "<<str<<endl;
// according to huffman code
// moving left adds 0 to the code
printCodes(root->left, str + "0");
// moving right adds 1 to the code
printCodes(root->right, str + "1");
}
void findHuffmanCodes(vector<char> &data, vector<int> &freq, int n) {
MinHeapNode *first, *second, *top;
// initailize priority queue [min-heap]
priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> pq;
for(int i=0; i<n; i++)
pq.push(new MinHeapNode(data[i], freq[i]));
// iterate over all nodes
while(pq.size() != 1) {
// pop first minimum
first = pq.top();
pq.pop();
// pop second minimum
second = pq.top();
pq.pop();
// make internal node by adding two minimums
top = new MinHeapNode('$', first->freq + second->freq);
top->left = first;
top->right = second;
// push the node to pq
pq.push(top);
}
// print the codes created using huffman coding
printCodes(pq.top(), "");
}
int main() {
int n;
cin>>n;
vector<char> data(n);
vector<int> freq(n);
for(int i=0; i<n; i++) {
cin>>data[i];
cin>>freq[i];
}
cout<<"\nOutput :\n";
findHuffmanCodes(data, freq, n);
}