|
| 1 | +#include <bits/stdc++.h> |
| 2 | +#define ll long long |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +struct node { |
| 6 | + char letter; |
| 7 | + ll freq; |
| 8 | + struct node* left; |
| 9 | + struct node* right; |
| 10 | + |
| 11 | + node(char letter, ll freq) { |
| 12 | + this->letter = letter; |
| 13 | + this->freq = freq; |
| 14 | + this->left = this->right = NULL; |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +/* |
| 19 | + * Comparison function for min_heap |
| 20 | + */ |
| 21 | +class Prioritize { |
| 22 | + public: |
| 23 | + int operator() (struct node* a, struct node* b) { |
| 24 | + return a->freq > b->freq; |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +/* |
| 29 | + * function to build the huffman tree |
| 30 | + * time complexity : O(nlogn) as each heap operation takes O(logn) time |
| 31 | + */ |
| 32 | +struct node* build_huffman(vector<pair<char,ll> > &chars, int n) { |
| 33 | + int i; |
| 34 | + priority_queue<node*, vector<node*>, Prioritize> min_heap; |
| 35 | + for(i=0; i<n; i++) { |
| 36 | + min_heap.push(new node(chars[i].first, chars[i].second)); |
| 37 | + } |
| 38 | + for(i=0; i<n-1; i++) { |
| 39 | + struct node* left_child = min_heap.top(); |
| 40 | + min_heap.pop(); |
| 41 | + struct node* right_child = min_heap.top(); |
| 42 | + min_heap.pop(); |
| 43 | + struct node* new_node = new node('$', left_child->freq + right_child->freq); |
| 44 | + new_node->left = left_child; |
| 45 | + new_node->right = right_child; |
| 46 | + min_heap.push(new_node); |
| 47 | + } |
| 48 | + struct node* root = min_heap.top(); |
| 49 | + min_heap.pop(); |
| 50 | + return root; |
| 51 | +} |
| 52 | + |
| 53 | +/* |
| 54 | + * function to print huffman codes for the characters |
| 55 | + * time complexity : O(n) as there are 2n-1 nodes in the tree (n leaf nodes and n-1 internal nodes) |
| 56 | + * and each node is visited only once |
| 57 | + */ |
| 58 | +void print_huffman_codes(struct node* root, string str) { |
| 59 | + if(root == NULL) { |
| 60 | + return; |
| 61 | + } |
| 62 | + if(root->letter == '$') { |
| 63 | + print_huffman_codes(root->left, str+"0"); |
| 64 | + print_huffman_codes(root->right, str+"1"); |
| 65 | + } |
| 66 | + else { |
| 67 | + cout<<root->letter<<" : "<<str<<endl; |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +int main() { |
| 72 | + int i,n; |
| 73 | + cin>>n; //number of characters |
| 74 | + vector<pair<char,ll> > chars(n); |
| 75 | + for(i=0; i<n; i++) { |
| 76 | + cin>>chars[i].first>>chars[i].second; |
| 77 | + } |
| 78 | + struct node* root = build_huffman(chars, n); |
| 79 | + print_huffman_codes(root, ""); |
| 80 | + return 0; |
| 81 | +} |
0 commit comments