coloriot

HA55

Jun 7th, 2025
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <string>
  4. using namespace std;
  5.  
  6. struct TrieNode {
  7.     unordered_map<char, TrieNode*> children;
  8.     int counter;
  9.  
  10.     TrieNode() : counter(0) {}
  11. };
  12.  
  13. class Trie {
  14. public:
  15.     Trie() {
  16.         root = new TrieNode();
  17.     }
  18.  
  19.     void insert(const string& word) {
  20.         TrieNode* node = root;
  21.         node->counter++; // увеличиваем счетчик в корне
  22.         for (char ch : word) {
  23.             if (!node->children.count(ch)) {
  24.                 node->children[ch] = new TrieNode();
  25.             }
  26.             node = node->children[ch];
  27.             node->counter++;
  28.         }
  29.     }
  30.  
  31.     int query(const string& word) {
  32.         TrieNode* node = root;
  33.         int depth = 0;
  34.         for (char ch : word) {
  35.             if (!node->children.count(ch)) {
  36.                 break;
  37.             }
  38.             node = node->children[ch];
  39.             ++depth;
  40.         }
  41.         return node->counter + depth;
  42.     }
  43.  
  44. private:
  45.     TrieNode* root;
  46. };
  47.  
  48. int main() {
  49.     ios::sync_with_stdio(false);
  50.     cin.tie(nullptr);
  51.  
  52.     int n;
  53.     cin >> n;
  54.     Trie trie;
  55.     for (int i = 0; i < n; ++i) {
  56.         string word;
  57.         cin >> word;
  58.         trie.insert(word);
  59.     }
  60.  
  61.     int q;
  62.     cin >> q;
  63.     while (q--) {
  64.         string query;
  65.         cin >> query;
  66.         cout << trie.query(query) << '\n';
  67.     }
  68.  
  69.     return 0;
  70. }
Add Comment
Please, Sign In to add comment