-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhuffmancoding.cpp
More file actions
86 lines (68 loc) · 1.27 KB
/
huffmancoding.cpp
File metadata and controls
86 lines (68 loc) · 1.27 KB
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
#include<bits/stdc++.h>
using namespace std;
struct node{
int freq;
char data;
node *left,*right;
node(){
}
node(char dta, int fq){
data = dta;
freq = fq;
left = nullptr;
right = nullptr;
}
~node(){
delete left;
delete right;
}
};
struct cmp{
bool operator()(node* l, node* r){
return (l->freq > r->freq);
}
};
class huffman{
public:
void Encode(string s, vector<int> frequncey){
priority_queue<node*, vector<node*> , cmp > minHeap;
for(int i = 0; i < (int)s.length(); i++){
minHeap.push(new node(s[i], frequncey[i]));
}
while(minHeap.size() != 1){
node *l = minHeap.top();
minHeap.pop();
node *r = minHeap.top();
minHeap.pop();
node *N = new node('$' , l->freq + r->freq);
N->left = l;
N->right = r;
minHeap.push(N);
}
printCode(minHeap.top(), "");
}
void printCode(node *root, string str){
if(root == nullptr){
return;
}
if(root->data != '$'){
cout<<root->data<<" : "<<str<<" ";
}
printCode(root->left,str + "0");
printCode(root->right, str + "1");
}
};
int main(){
int T;
cin>>T;
while(T--){
string s;
cin>>s;
std::vector<int> frequncey((int)s.length());
for(int i = 0; i < (int)s.length(); i++){
cin>>frequncey[i];
}
huffman ob;
ob.Encode(s,frequncey);
}
}