Sie sind auf Seite 1von 3

/*! * Huffman Coding * * Author : Pushkar Anand * * Complexity : O(n) * Algorithm taken from http://en.wikipedia.

org/wiki/Huffman_coding Start with as many leaves as there are symbols. Enqueue all leaf nodes into the first queue (by probability in increasing or der so that the least likely item is in the head of the queue). While there is more than one node in the queues: Dequeue the two nodes with the lowest weight by examining the fronts of both queues. Create a new internal node, with the two just-removed nodes as children (either node can be either child) and the sum of their weights as the new weight . Enqueue the new node into the rear of the second queue. The remaining node is the root node; the tree has now been generated. */ #include <iostream> #include <string> #include <cstdio> #include <cstdlib> #include <queue> using namespace std; // Tree node struct node { char ch; int p; bool set; node *left, *right; }; // Compare Function int cmp(const void *da, const void *db) { char *a, *b; a = (char *)da; b = (char *)db; return ((a[0] > b[0]) - (a[0] < b[0])); } // Prints Huffman code generated void print(node *root, string str) { if(root->set == true) cout<<root->ch<<" "<<str<<endl; else { string a, b; a = b = str; a.append("0"); b.append("1"); print(root->right, b); print(root->left, a); } } // Assigning value to node void assign(node * new_node, char ch, int p, bool set, node *left, node *right) {

new_node->ch = ch; new_node->p = p; new_node->set = set; new_node->left = left; new_node->right = right; } // Fetch node with least weight from queue node* getnode(queue<node*> *qa, queue<node*> *qb) { node* nodea; if(!(*qa).empty() && !(*qb).empty()) { if((*qa).front()->p < (*qb).front()->p) { nodea = (*qa).front(); (*qa).pop(); } else { nodea = (*qb).front(); (*qb).pop(); } } else if((*qa).empty()) { nodea = (*qb).front(); (*qb).pop(); } else { nodea = (*qa).front(); (*qa).pop(); } return nodea; } int main() { // Initializations string str; char arr[256][2] ={0}; int i; for(i = 0; i < 256; i++) arr[i][1] = i; queue<node*> qa; queue<node*> qb; node *new_node, *nodea, *nodeb; // Main Program getline(cin, str); // Sorting in inc. order of probability for(i = 0; i < str.length(); i++) arr[str[i]][0]++; qsort(arr, 256, sizeof(char)*2, cmp); // Inserting leaf nodes in queue for(i = 0; i < 256; i++) { if(arr[i][0] > 0) { new_node = new node; assign(new_node, arr[i][1], arr[i][0], true, NULL, NULL) ; qa.push(new_node); } } while(qa.size() + qb.size() != 1) {

// geting least probabilty first node and second node nodea = getnode(&qa, &qb); nodeb = getnode(&qa, &qb); // Creating parent node new_node = new node; assign(new_node, ' ',nodea->p + nodeb->p, false, nodea, nodeb); // Pushing the node created in second queue qb.push(new_node); } // Printing Huffman code generated print(qb.front(), ""); return 0; }

Das könnte Ihnen auch gefallen