forked from arya2004/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
98 lines (70 loc) · 2.2 KB
/
Copy pathmain.cpp
File metadata and controls
98 lines (70 loc) · 2.2 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
92
93
94
95
96
97
98
#include <bits/stdc++.h>
using namespace std;
struct Node {
char ch;
int freq;
Node* left;
Node* right;
Node(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
struct Compare {
bool operator()(Node* a, Node* b) {
return a->freq > b->freq;
}
};
void generateCodes(Node* root, string code, unordered_map<char, string>& huffmanCode) {
if (!root) return;
if (!root->left && !root->right)
huffmanCode[root->ch] = code;
generateCodes(root->left, code + "0", huffmanCode);
generateCodes(root->right, code + "1", huffmanCode);
}
Node* buildHuffmanTree(const string& text, unordered_map<char, string>& huffmanCode) {
unordered_map<char, int> freq;
for (char ch : text) freq[ch]++;
priority_queue<Node*, vector<Node*>, Compare> pq;
for (auto pair : freq)
pq.push(new Node(pair.first, pair.second));
while (pq.size() > 1) {
Node* left = pq.top(); pq.pop();
Node* right = pq.top(); pq.pop();
Node* merged = new Node('\0', left->freq + right->freq);
merged->left = left;
merged->right = right;
pq.push(merged);
}
Node* root = pq.top();
generateCodes(root, "", huffmanCode);
return root;
}
string encode(const string& text, unordered_map<char, string>& huffmanCode) {
string encoded;
for (char ch : text)
encoded += huffmanCode[ch];
return encoded;
}
string decode(Node* root, const string& encoded) {
string decoded;
Node* curr = root;
for (char bit : encoded) {
curr = (bit == '0') ? curr->left : curr->right;
if (!curr->left && !curr->right) {
decoded += curr->ch;
curr = root;
}
}
return decoded;
}
int main() {
string text = "BCCABBDDAECCBBAEDDCC";
unordered_map<char, string> huffmanCode;
Node* root = buildHuffmanTree(text, huffmanCode);
cout << "codes:\n";
for (auto pair : huffmanCode)
cout << pair.first << ": " << pair.second << '\n';
string encoded = encode(text, huffmanCode);
cout << "encoding: " << encoded << "\n";
string decoded = decode(root, encoded);
cout << "decoding: " << decoded << "\n";
return 0;
}