#pragma warning(disable:4996) using namespace std; struct node { node() { this->weight = 0; this->msg = '?'; this->encode = ""; this->left = this->right = NULL; } node(int weight,node* left,node* right) { this->weight = weight; this->msg = '?'; this->encode = ""; this->left = left; this->right = right; } char msg; string encode; int weight; node *left; node *right; }; bool cmp(node* n1, node* n2) { return n1->weight weight; } void Create_HuffmanTree(int size,node** data,node*& root) { int current_position = 0; node* min1; node* min2; while (current_position != size -1) { min1 = data[current_position]; min2 = data[current_position+1]; node* newnode = new node(min1->weight+min2->weight,min1,min2); root = newnode; current_position++; data[current_position] = newnode; sort(data+current_position,data+size,cmp); } } void Huffman_Encoding(node* ptr) { if(ptr->left == NULL && ptr->right == NULL) { printf("%c %d %s\n",ptr->msg,ptr->weight,ptr->encode.c_str()); return; } if(ptr->left != NULL) { ptr->left->encode = ptr->encode +"0"; Huffman_Encoding(ptr->left); } if(ptr->right != NULL) { ptr->right->encode = ptr->encode + "1"; Huffman_Encoding(ptr->right); } } void Inorder_traversal(node* ptr) { if(ptr != NULL) { Inorder_traversal(ptr->left); printf("%c %d\n",ptr->msg,ptr->weight); Inorder_traversal(ptr->right); } } int main() { freopen("in.txt","r",stdin); int size = 0; char msg; int frequency; node* root = new node; scanf("%d",&size); node** data = new node* [size]; for(int i = 0 ; i msg,&data[i]->weight); } sort(data+0,data+size,cmp);
Create_HuffmanTree(size,data,root); Inorder_traversal(root); Huffman_Encoding(root); return 0; }
|