Advertisement
LDG2875

Huffman Tree that made me Cuff Rage

Apr 16th, 2022
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. ifstream in("t.in");
  6. ofstream out("t.out");
  7.  
  8. unordered_map<char, int> M;
  9.  
  10. struct Node
  11. {
  12. string simbol;
  13. int freq;
  14. Node* left_child;
  15. Node* right_child;
  16. Node(string c, int x)
  17. {
  18. simbol = c;
  19. freq = x;
  20. left_child = right_child = NULL;
  21. }
  22. ~Node()
  23. {
  24. cout <<"destructor apelat!\n";
  25. }
  26. };
  27.  
  28. class greaterr
  29. {
  30. public:
  31. bool operator()(Node* first, Node* second) const
  32. {
  33. return first -> freq > second -> freq;
  34. }
  35. };
  36.  
  37. vector<pair<string, string>> A;
  38.  
  39. void Traversal(Node* nod, string bins)
  40. {
  41. // cout << depth << '\n';
  42. if(nod -> left_child)
  43. {
  44. Traversal(nod -> left_child, bins + "0");
  45. }
  46. if(nod -> right_child)
  47. {
  48. Traversal(nod -> right_child, bins + "1");
  49. }
  50. if(!nod -> left_child && !nod -> right_child)
  51. {
  52. A.push_back({nod -> simbol, bins});
  53. delete nod;
  54. }
  55. }
  56.  
  57. int main()
  58. {
  59. string S;
  60. getline(in, S);
  61. for(int i = 0; i < (int)S.size(); ++i)
  62. M[S[i]]++;
  63. priority_queue<Node*, vector<Node*>, greaterr> Q;
  64. Node* nod;
  65. for(auto i : M)
  66. {
  67. string c;
  68. c += i.first;
  69. nod = new Node(c, i.second);
  70. Q.push(nod);
  71. }
  72.  
  73. Node *left, *right, *father;
  74. while(Q.size() > 1)
  75. {
  76. left = Q.top();
  77. Q.pop();
  78. right = Q.top();
  79. Q.pop();
  80. father = new Node("", left -> freq + right -> freq);
  81. father -> left_child = left;
  82. father -> right_child = right;
  83. Q.push(father);
  84. }
  85. Node* Tata = Q.top();
  86. string bins = "";
  87. Traversal(Tata, bins);
  88. for(auto i : A)
  89. {
  90. out << i.first << " " << i.second << '\n';
  91. }
  92. return 0;
  93. }
  94.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement