Skip to content

Commit 6372448

Browse files
committed
2 parents 82a3be1 + 80a6abe commit 6372448

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)