Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- struct Node {
- int freq;
- char c;
- Node* left;
- Node* right;
- Node(int freq) {
- this->freq = freq;
- this->left = nullptr;
- this->right = nullptr;
- }
- Node(char c, int freq) {
- this->c = c;
- this->freq = freq;
- this->left = nullptr;
- this->right = nullptr;
- }
- };
- struct comp {
- bool operator()(Node* a, Node* b) {
- return a->freq > b->freq;
- }
- };
- bool comp2(pair<char, string> a, pair<char, string> b) {
- if (a.second.size() == b.second.size()) {
- return a.second < b.second;
- }
- return a.second.size() < b.second.size();
- }
- void dfs(Node* curr, string code, vector<pair<char, string>>& ans) {
- // if the current node is leaf
- if (curr->left == nullptr && curr->right == nullptr) {
- ans.push_back({curr->c, code});
- return;
- }
- dfs(curr->left, code + "0", ans);
- dfs(curr->right, code + "1", ans);
- }
- // assume string include lowercase characters only
- vector<pair<char, string>> huffmanCode(string s) {
- int freq[26] = {};
- for (int i = 0; s[i]; i++) {
- freq[s[i] - 'a']++;
- }
- priority_queue<Node*, vector<Node*>, comp> pq;
- for (int i = 0; i < 26; i++) {
- if (freq[i]) {
- Node* newNode = new Node('a' + i, freq[i]);
- pq.push(newNode);
- }
- }
- while (pq.size() >= 2) {
- auto fst = pq.top();
- pq.pop();
- auto snd = pq.top();
- pq.pop();
- Node* newNode = new Node(fst->freq + snd->freq);
- newNode->left = fst;
- newNode->right = snd;
- pq.push(newNode);
- }
- Node* root = pq.top();
- vector<pair<char, string>> ans;
- dfs(root, "", ans);
- sort(ans.begin(), ans.end(), comp2);
- return ans;
- }
- void solve()
- {
- string s = "aaabbbccccccccccccccccccccccccccccccccccccc";
- auto prefixCodes = huffmanCode(s);
- string code[26];
- map<string, char> decode;
- for (auto [c, cooode] : prefixCodes) {
- code[c - 'a'] = cooode;
- decode[cooode] = c;
- }
- string compressed;
- for (auto c : s) {
- compressed += code[c - 'a'];
- }
- cout << "=> Compressed String: " << compressed << '\n';
- string original;
- string temp;
- for (auto c : compressed) {
- temp.push_back(c);
- if (decode.find(temp) != decode.end()) {
- original.push_back(decode[temp]);
- temp = "";
- }
- }
- cout << "=> Original String: " << original << '\n';
- }
- int main()
- {
- solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment