Skip to content

Commit 80a6abe

Browse files
authored
decoding huffman-algos
Input: 17 98 -> 000 110 -> 001 104 -> 0100 115 -> 01010 100 -> 01011 107 -> 011 106 -> 100 108 -> 1010 114 -> 1011 99 -> 110000 105 -> 110001 103 -> 11001 101 -> 1101 117 -> 111000 102 -> 111001 97 -> 11101 118 -> 1111 000101011110001001101111010011111001011100111100110010101101111011011011001100001111010111011001110101100101011110000100000010000010101010110001111111100011010111011100010011001110011101111001010100111111010011100100011110111000101100001010101110011001011
1 parent 651b9aa commit 80a6abe

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

huffman-decode.cpp

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
struct pixel{
6+
int label;
7+
pixel* left, *right;
8+
9+
pixel(int x): label(x){
10+
left = NULL;
11+
right = NULL;
12+
}
13+
14+
};
15+
16+
pixel* add(pixel* root, int i, string s, string label){
17+
18+
if(root == NULL){
19+
root = new pixel(-1);
20+
}
21+
22+
if(i == s.length()){
23+
cout << s << " " << label << endl;
24+
root->label = stoi(label);
25+
return root;
26+
}
27+
28+
if(s[i] == '0'){
29+
root->left = add(root->left, i+1, s, label);
30+
}
31+
else{
32+
root->right = add(root->right, i+1, s, label);
33+
}
34+
35+
return root;
36+
}
37+
38+
void preoder(pixel* root, string s){
39+
40+
if(root == NULL)
41+
return;
42+
43+
if(root->label != -1){
44+
cout << setfill(' ') << setw(3) << root->label
45+
<< " -> " << setw(7) << s << endl;
46+
return;
47+
}
48+
49+
preoder(root->left, s + '0');
50+
preoder(root->right, s + '1');
51+
52+
return;
53+
}
54+
55+
int main(){
56+
int n;
57+
cin>>n;
58+
pixel* root = new pixel(-1);
59+
for(int i=0; i<n; i++){
60+
string a,b,c;
61+
cin>>a>>b>>c;
62+
add(root, 0, c, a);
63+
}
64+
65+
// for checking
66+
preoder(root, "");
67+
68+
string w;
69+
cin >> w;
70+
71+
pixel* ptr = root;
72+
73+
vector<int> v;
74+
75+
for(auto i:w){
76+
if(i=='0')
77+
ptr = ptr->left;
78+
else
79+
ptr = ptr->right;
80+
if(ptr->label != -1){
81+
v.push_back(ptr->label);
82+
ptr = root;
83+
}
84+
}
85+
86+
for(auto i:v){
87+
cout << (char)i ;
88+
} cout << endl;
89+
90+
return 0;
91+
}
92+
93+
blvbjeanvnkjvnjlearknjnakrnekndcjbhbllivuekrjhggefskvhfbvkjdbsrjgk

0 commit comments

Comments
 (0)