-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHuffmanEncoding.cpp
76 lines (70 loc) · 1.51 KB
/
HuffmanEncoding.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
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
struct MinHeapNode {
int freq;
MinHeapNode *left, *right;
MinHeapNode(int f) {
this->freq = f;
this->left = nullptr;
this->right = nullptr;
}
};
class comp {
public:
bool operator()(MinHeapNode* m1, MinHeapNode* m2) {
return m1->freq > m2->freq; // for extracting minimum
}
};
void fillVector(MinHeapNode* root, string s, vector<string> &vec) {
if (!root) return;
if (root->left == nullptr && root->right == nullptr) {
vec.push_back(s);
return;
}
fillVector(root->left, s+'0', vec);
fillVector(root->right, s+'1', vec);
}
vector<string> huffmanCodes(string s, vector<int> f, int n) {
priority_queue<MinHeapNode*, vector<MinHeapNode*>, comp> pq;
for (auto ele : f) pq.push(new MinHeapNode(ele));
while (pq.size() > 1) {
MinHeapNode* left = pq.top();
pq.pop();
MinHeapNode* right = pq.top();
pq.pop();
MinHeapNode* top = new MinHeapNode(left->freq + right->freq);
top->left = left;
top->right = right;
pq.push(top);
}
vector<string> ans;
fillVector(pq.top(), "", ans);
return ans;
}
};
// { Driver Code Starts.
int main() {
int T;
cin >> T;
while (T--)
{
string S;
cin >> S;
int N = S.length();
vector<int> f(N);
for (int i = 0; i < N; i++) {
cin >> f[i];
}
Solution ob;
vector<string> ans = ob.huffmanCodes(S, f, N);
for (auto i : ans)
cout << i << " ";
cout << "\n";
}
return 0;
} // } Driver Code Ends