-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday28.cpp
More file actions
91 lines (69 loc) · 2.13 KB
/
Copy pathday28.cpp
File metadata and controls
91 lines (69 loc) · 2.13 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
87
88
89
90
91
#include<bits/stdc++.h>
using namespace std;
typedef struct node {
int freq;
char data;
node * left;
node * right;
} node;
struct deref:public binary_function<node*, node*, bool> {
bool operator()(const node * a, const node * b)const {
return a->freq > b->freq;
}
};
typedef priority_queue<node *, vector<node*>, deref> spq;
node * huffman_hidden(string s) {
spq pq;
vector<int>count(256,0);
for(int i = 0; i < s.length(); i++ ) {
count[s[i]]++;
}
for(int i=0; i < 256; i++) {
node * n_node = new node;
n_node->left = NULL;
n_node->right = NULL;
n_node->data = (char)i;
n_node->freq = count[i];
if( count[i] != 0 )
pq.push(n_node);
}
while( pq.size() != 1 ) {
node * left = pq.top();
pq.pop();
node * right = pq.top();
pq.pop();
node * comb = new node;
comb->freq = left->freq + right->freq;
comb->data = '\0';
comb->left = left;
comb->right = right;
pq.push(comb);
}
return pq.top();
}
void print_codes_hidden(node * root, string code, map<char, string>&mp) {
if(root == NULL)
return;
if(root->data != '\0') {
mp[root->data] = code;
}
print_codes_hidden(root->left, code+'0', mp);
print_codes_hidden(root->right, code+'1', mp);
}
void decode_huff(node * root, string s) {
// We need a helper pointer to traverse the tree without losing the root
node* current = root;
// Loop through each bit ('0' or '1') in the encoded string
for (int i = 0; i < s.length(); i++) {
if (s[i] == '0') {
current = current->left;
} else {
current = current->right;
}
// Check if we have reached a leaf node (both left and right are null)
if (current->left == nullptr && current->right == nullptr) {
cout << current->data; // Print the decoded character
current = root; // Reset back to the root for the next character
}
}
}