Guest User

Untitled

a guest
Dec 16th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. #include<iostream>
  2. #include<utility>
  3. #include<vector>
  4. #include<queue>
  5.  
  6. using namespace std;
  7.  
  8. struct node{
  9. int freq;
  10. string c;
  11. node *left,*right;
  12. }*root, *ptr;
  13.  
  14. struct cmp{
  15. bool operator()(node* left, node* right){
  16. if(left->freq== right->freq){
  17. if((left->c).size()==(right->c).size()){
  18. return (left->c)< (right->c);
  19. }
  20. return (left->c).size()< (right->c).size();
  21. }
  22. return left->freq > right->freq;
  23. }
  24. };
  25.  
  26. void print(priority_queue<node*, vector <node*>, cmp> q){
  27. cout<<"Heap State:\n";
  28. while (!q.empty()){
  29. cout<<q.top()->c<<" "<<q.top()->freq<< endl;
  30. q.pop();
  31. }
  32. cout<<endl;
  33. }
  34. node* create_node(int freq, string c){
  35. ptr=new(struct node);
  36. ptr->freq= freq;
  37. ptr->c= c;
  38. ptr->left=NULL;
  39. ptr->right=NULL;
  40. return ptr;
  41. }
  42.  
  43. void gen_code(node *np,string op){
  44. if (np->left==NULL || np->right==NULL){
  45. cout<<np->c<<" "<<op<<endl;
  46. return;
  47. }
  48. gen_code(np->left,op+"1");
  49. gen_code(np->right,op+"0");
  50. }
  51. int main(){
  52. root=NULL;
  53. vector< pair<int,string> > v;
  54. //string s[]={"A","B","C","D","E","F"};
  55. //int occ[]={ 5, 9, 12, 13, 16, 45 };
  56. int n;
  57. cout<<"Enter n: ";
  58. cin>>n;
  59. cout<<"Enter character and frequency: \n";
  60. for (int i=0;i<n;i++){
  61. string s;
  62. int occ;
  63. cin>>s>>occ;
  64. v.push_back(make_pair(occ,s));
  65. }
  66. priority_queue<node*, vector <node*>, cmp> heap;
  67. for(int i = 0; i < n; i++) {
  68. node* newptr = create_node(v[i].first, v[i].second);
  69. heap.push(newptr);
  70. }
  71. print(heap);
  72. while(heap.size() != 1) {
  73. node* ptr1 = heap.top();
  74. heap.pop();
  75. node* ptr2 = heap.top();
  76. heap.pop();
  77. int add_freq = (ptr1->freq)+(ptr2->freq);
  78. string add_char= (ptr1->c)+ (ptr2->c);
  79. node* parent = create_node(add_freq, add_char);
  80. parent->left = ptr1;
  81. parent->right = ptr2;
  82. heap.push(parent);
  83. root = parent;
  84. print(heap);
  85. }
  86. cout<<"Codewords: \n";
  87. gen_code(root,"");
  88. }
Add Comment
Please, Sign In to add comment