Skip to content

Commit 517ddf1

Browse files
authored
Uploaded
1 parent 4c8d11d commit 517ddf1

File tree

1 file changed

+131
-0
lines changed

1 file changed

+131
-0
lines changed

improved-huffman-decode.cpp

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
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+
bool flag[256];
17+
int cnt = 256;
18+
19+
pixel* add(pixel* root, int i, string s, string label, int level = 0){
20+
21+
if(root == NULL){
22+
root = new pixel(cnt++);
23+
}
24+
25+
if(i == s.length()){
26+
cout << s << " " << char(stoi(label)) << " " << label << endl;
27+
root->label = stoi(label);
28+
if(level > 3){
29+
flag[root->label] = 1;
30+
}
31+
return root;
32+
}
33+
34+
if(s[i] == '0'){
35+
root->left = add(root->left, i+1, s, label, level+1);
36+
}
37+
else{
38+
root->right = add(root->right, i+1, s, label, level+1);
39+
}
40+
41+
return root;
42+
}
43+
44+
void preoder(pixel* root, string s){
45+
46+
if(root == NULL)
47+
return;
48+
49+
if(root->label < 256){
50+
cout << setfill(' ') << setw(3) << (char)root->label
51+
<< " -> " << setw(7) << s << endl;
52+
return;
53+
}
54+
55+
preoder(root->left, s + '0');
56+
preoder(root->right, s + '1');
57+
58+
return;
59+
}
60+
61+
int main(){
62+
int n;
63+
cin>>n;
64+
pixel* root = new pixel(cnt++);
65+
for(int i=0; i<n; i++){
66+
string b, c;
67+
string a;
68+
cin>>a>>b>>c;
69+
add(root, 0, c, a);
70+
}
71+
72+
// for checking
73+
preoder(root, "");
74+
75+
string w;
76+
cin >> w;
77+
78+
pixel* ptr = root;
79+
pixel* tmp = root;
80+
81+
vector<int> v;
82+
bool f = 0;
83+
int level = 0;
84+
85+
for(auto i:w){
86+
87+
if(f){
88+
if(i == '0'){
89+
// do nothing
90+
}
91+
else{
92+
ptr = tmp;
93+
}
94+
f = 0;
95+
continue;
96+
}
97+
98+
if(i=='0')
99+
ptr = ptr->left;
100+
else
101+
ptr = ptr->right;
102+
103+
level += 1;
104+
105+
if(level == 3)
106+
tmp = ptr;
107+
108+
if(ptr->label < 256){
109+
110+
v.push_back(ptr->label);
111+
112+
level = 0;
113+
114+
// cout << ptr->label << endl;
115+
// cout << char(ptr->label) << flag[ptr->label] << endl;
116+
117+
if(flag[ptr->label])
118+
f = 1;
119+
120+
ptr = root;
121+
}
122+
}
123+
124+
for(auto i:v){
125+
cout << (char)i ;
126+
} cout << endl;
127+
128+
return 0;
129+
}
130+
131+
// blvbjeanvnkjvnjlearknjnakrnekndcjbhbllivuekrjhggefskvhfbvkjdbsrjgk

0 commit comments

Comments
 (0)