Skip to content

Commit bc48a2b

Browse files
authored
This is temporary Huffman.cpp code
1 parent 70920c1 commit bc48a2b

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

huffman.cpp

+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
struct pixel{
6+
int freq;
7+
int label;
8+
pixel* left, *right;
9+
10+
pixel(int x, int y): label(x), freq(y){
11+
left = NULL;
12+
right = NULL;
13+
}
14+
15+
void print(){
16+
cout << label << " " << freq << endl;
17+
}
18+
};
19+
20+
struct compare{
21+
bool operator() (pixel* a, pixel* b){
22+
return a->freq > b->freq;
23+
}
24+
};
25+
26+
string code[256];
27+
28+
void preoder(pixel* root, string s){
29+
30+
if(root->label != -1){
31+
cout << setfill(' ') << setw(3) << root->label
32+
<< " -> " << setw(7) << s << endl;
33+
code[root->label] = s;
34+
return;
35+
}
36+
37+
preoder(root->left, s + '0');
38+
preoder(root->right, s + '1');
39+
40+
return;
41+
}
42+
43+
int main(){
44+
// Uploading Image
45+
46+
string s;
47+
cin >> s;
48+
49+
int freq[256] = {0};
50+
51+
for(auto i: s){
52+
freq[i] += 1;
53+
}
54+
55+
priority_queue<pixel*, vector<pixel*>, compare> pq;
56+
57+
for(int i = 0; i < 256; i++){
58+
if (freq[i] > 0){
59+
pixel* tmp = new pixel(i, freq[i]);
60+
pq.push(tmp);
61+
}
62+
}
63+
64+
while(pq.size() > 1){
65+
pixel* first = pq.top();
66+
pq.pop();
67+
pixel* second = pq.top();
68+
pq.pop();
69+
pixel* tmp = new pixel(-1, first->freq + second->freq);
70+
tmp->left = first;
71+
tmp->right = second;
72+
pq.push(tmp);
73+
}
74+
75+
pixel* root = pq.top();
76+
77+
preoder(root, "");
78+
79+
string w;
80+
81+
for(auto i:s){
82+
w += code[i];
83+
}
84+
85+
cout << w << endl;
86+
cout << w.length() << " " << s.length() * 4 << endl;
87+
88+
return 0;
89+
}

0 commit comments

Comments
 (0)