Advertisement
LDG2875

Untitled

Apr 16th, 2022
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 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. };
  17.  
  18. template <class Node> struct greaterr
  19. {
  20. bool operator()(const Node& first, const Node& second) const
  21. {
  22. return first.freq > second.freq;
  23. }
  24. };
  25.  
  26. /*void atribuire(Node* nod, string S, int x, Node* lc, Node* rc)
  27. {
  28. (*nod).simbol = S;
  29. (*nod).freq = x;
  30. (*nod).left_child = lc;
  31. (*nod).right_child = rc;
  32. }*/
  33.  
  34. vector<pair<string, string>> A;
  35.  
  36. void Traversal(Node nod, string bins)
  37. {
  38. bool OK = 0;
  39. if(nod.left_child)
  40. {
  41. OK = 1;
  42. Traversal(*nod.left_child, bins + "0");
  43. }
  44. if(nod.right_child)
  45. {
  46. OK = 1;
  47. Traversal(*nod.right_child, bins + "1");
  48. }
  49. if(!OK)
  50. {
  51. A.push_back({nod.simbol, bins});
  52. }
  53. }
  54.  
  55. int main()
  56. {
  57. string S;
  58. getline(in, S);
  59. for(int i = 0; i < S.size(); ++i)
  60. M[S[i]]++;
  61. priority_queue<Node, vector<Node>, greaterr<Node>> Q;
  62. Node* nod;
  63. for(auto i : M)
  64. {
  65. nod = new Node;
  66. nod -> simbol = i.first;
  67. nod -> freq = i.second;
  68. nod -> left_child = nullptr;
  69. nod -> right_child = nullptr;
  70. //atribuire(nod, i.first, i.second, nullptr, nullptr);
  71. Q.push(*nod);
  72. }
  73. Node *left, *right, *father;
  74. while(Q.size() > 1)
  75. {
  76. left = new Node;
  77. right = new Node;
  78.  
  79. left -> simbol = Q.top().simbol;
  80. left -> freq = Q.top().freq;
  81. left -> left_child = nullptr;
  82. left -> right_child = nullptr;
  83. Q.pop();
  84.  
  85. right -> simbol = Q.top().simbol;
  86. right -> freq = Q.top().freq;
  87. right -> left_child = nullptr;
  88. right -> right_child = nullptr;
  89. Q.pop();
  90.  
  91. father = new Node;
  92.  
  93. father -> freq = left -> freq + right -> freq;
  94. father -> simbol = "";
  95. father -> left_child = left;
  96. father -> right_child = right;
  97.  
  98. Q.push(*father);
  99. }
  100. Node Tata = Q.top();
  101. string bins = "";
  102. //cout << typeid(Tata).name() << '\n';
  103. Traversal(Tata, bins);
  104. for(auto i : A)
  105. {
  106. out << i.first << " " << i.second << '\n';
  107. }
  108. return 0;
  109. }
  110.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement