Advertisement
AlexG2230954

Untitled

Mar 18th, 2022
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. struct Node {
  8. map<char, struct Node*> next;
  9. int count; // в скольких словах используется этот узел
  10. int end; // для скольки слов символ является конечным
  11. };
  12.  
  13. struct Trie {
  14. struct Node* root;
  15.  
  16. void insert(string s) {
  17. struct Node* current = root;
  18.  
  19. for(char c : s) {
  20. if(!current->next.count(c))
  21. current->next[c] = new Node();
  22.  
  23. current->count++;
  24. current = current->next[c];
  25. }
  26.  
  27. current->count++;
  28. current->end++;
  29. }
  30.  
  31. string find(struct Node* root, int k, int & found) {
  32. if(root->end > 0) found += root->end;
  33. if(found >= k) root->end--;
  34.  
  35. for(auto el : root->next) {
  36. string res = find(el.second, k, found);
  37. if(found >= k) {
  38. el.second->count--;
  39. return el.first + res;
  40. }
  41. }
  42.  
  43. return "";
  44. }
  45.  
  46. string get(int k) {
  47. int found = 0;
  48. return find(root, k, found);
  49. }
  50.  
  51. Trie() {
  52. root = new Node();
  53. }
  54. };
  55.  
  56. bool is_digit(string s) {
  57. for(char c : s)
  58. if(!isdigit(c)) return false;
  59. return true;
  60. }
  61.  
  62. int main() {
  63. Trie t = Trie();
  64. string s;
  65. int k;
  66.  
  67. cin >> k;
  68.  
  69. while(k--) {
  70. cin >> s;
  71.  
  72. if(!is_digit(s)) t.insert(s);
  73. else cout << '+' << t.get(stoi(s)) << endl;
  74. }
  75.  
  76. struct Node* curr = t.root;
  77. for(char c : "badest") {
  78. cout << curr->count << ' ' << curr->end << endl;
  79. curr = curr->next[c];
  80. }
  81.  
  82. cout << t.get(2) << endl;
  83.  
  84. // curr = t.root;
  85. // for(char c : "badest") {
  86. // cout << curr->count << ' ' << curr->end << endl;
  87. // curr = curr->next[c];
  88. // }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement