-
Notifications
You must be signed in to change notification settings - Fork 5
/
GFG_HuffmanEncoding.cpp
123 lines (100 loc) · 2.52 KB
/
GFG_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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
Huffman Encoding
https://practice.geeksforgeeks.org/problems/huffman-encoding3345/1
*/
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// class Solution
class HuffmanNode
{
public:
char c; // character
int f; // frequency
HuffmanNode* leftc;
HuffmanNode* rightc;
HuffmanNode(char ch, int freq)
{
c = ch;
f = freq;
leftc = nullptr;
rightc = nullptr;
}
HuffmanNode(char ch, int freq, HuffmanNode* &lptr, HuffmanNode* &rptr)
{
c = ch;
f = freq;
leftc = lptr;
rightc = rptr;
}
};
struct compareHuffmanNodes
{
bool operator()(const HuffmanNode* const &a, const HuffmanNode* const &b )
{
return a->f > b->f;
}
};
class Solution
{
public:
vector<string> result;
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
if(N==0) return {};
if(N==1) return {"0"};
priority_queue<HuffmanNode*, vector<HuffmanNode*>, compareHuffmanNodes> pq;
for(int i=0; i<N; i++)
pq.push(new HuffmanNode(S[i], f[i]));
while(pq.size() > 1)
{
HuffmanNode* hn1 = pq.top(); pq.pop();
HuffmanNode* hn2 = pq.top(); pq.pop();
// cout<<hn1->f<<" "<<hn2->f<<endl;
HuffmanNode* combined = new HuffmanNode('\0',hn1->f + hn2->f );
combined->leftc = hn1;
combined->rightc = hn2;
pq.push(combined);
// pq.push('\0', hn1->f + hn2->f, hn1, hn2);
}// while
HuffmanNode* root = pq.top(); pq.pop();
preorder(root, "");
return result;
}// end
void preorder(const HuffmanNode* root, string path)
{
if(!root->leftc && !root->rightc)
{
result.push_back(path);
return;
}
// path += '0';
preorder(root->leftc, path+'0');
// path.pop_back();
// path += '1';
preorder(root->rightc, path+'1');
// path.pop_back();
}// preorder
};
// { 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