|
| 1 | + |
| 2 | +#include <bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// A Huffman tree node |
| 6 | +struct Node { |
| 7 | + char data; |
| 8 | + unsigned freq; |
| 9 | + Node *left, *right; |
| 10 | + |
| 11 | + Node(char data, unsigned freq, Node* l = NULL, Node* r = NULL) |
| 12 | + |
| 13 | + { |
| 14 | + |
| 15 | + this->left = l; |
| 16 | + this->right = r; |
| 17 | + this->data = data; |
| 18 | + this->freq = freq; |
| 19 | + } |
| 20 | +}; |
| 21 | + |
| 22 | +// For comparison |
| 23 | +struct compare { |
| 24 | + |
| 25 | + bool operator()(Node* l, Node* r) |
| 26 | + |
| 27 | + { |
| 28 | + return (l->freq > r->freq); |
| 29 | + } |
| 30 | +}; |
| 31 | + |
| 32 | +// Prints huffman codes from |
| 33 | +void printCodes(struct Node* root, string str) |
| 34 | +{ |
| 35 | + |
| 36 | + if (!root) |
| 37 | + return; |
| 38 | + |
| 39 | + if (root->data != '$') |
| 40 | + cout << root->data << ": " << str << "\n"; |
| 41 | + |
| 42 | + printCodes(root->left, str + "0"); |
| 43 | + printCodes(root->right, str + "1"); |
| 44 | +} |
| 45 | + |
| 46 | +void printHcodes(char arr[], int freq[], int size) |
| 47 | +{ |
| 48 | + |
| 49 | + priority_queue<Node*, vector<Node*>, compare> h; |
| 50 | + |
| 51 | + for (int i = 0; i < size; ++i) |
| 52 | + h.push(new Node(arr[i], freq[i])); |
| 53 | + |
| 54 | + while (h.size() > 1) { |
| 55 | + |
| 56 | + Node *l = h.top();h.pop(); |
| 57 | + |
| 58 | + Node *r = h.top();h.pop(); |
| 59 | + |
| 60 | + |
| 61 | + Node *top = new Node('$', l->freq + r->freq, l, r); |
| 62 | + |
| 63 | + h.push(top); |
| 64 | + } |
| 65 | + printCodes(h.top(), ""); |
| 66 | +} |
| 67 | + |
| 68 | +int main() |
| 69 | +{ |
| 70 | + |
| 71 | + char arr[] = { 'a', 'd', 'e', 'f' }; |
| 72 | + int freq[] = { 30, 40, 80, 60 }; |
| 73 | + |
| 74 | + int size = sizeof(arr) / sizeof(arr[0]); |
| 75 | + |
| 76 | + printHcodes(arr, freq, size); |
| 77 | + |
| 78 | + return 0; |
| 79 | +} |
| 80 | + |
0 commit comments