Advertisement
Guest User

Untitled

a guest
Dec 15th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <string>
  7.  
  8. struct Node
  9. {
  10.     int prefixes;
  11.     Node** ch;
  12.     Node()
  13.     {
  14.         prefixes = 0;
  15.         ch = new Node*[26];
  16.         for (int i = 0; i < 26; i++)
  17.         {
  18.             ch[i] = nullptr;
  19.         }
  20.     }
  21. };
  22.  
  23. struct Trie
  24. {
  25.     Node* root;
  26.  
  27.     Trie()
  28.     {
  29.         this->root = new Node;
  30.     }
  31.     void add(char* str)
  32.     {
  33.         int i = 0;
  34.         Node* c = this->root;
  35.         while (str[i] != 0)
  36.         {
  37.             if (c->ch[str[i] - 'a'] == nullptr)
  38.             {
  39.                 c->ch[str[i] - 'a'] = new Node;
  40.             }
  41.             c->prefixes++;
  42.             c = c->ch[str[i] - 'a'];
  43.             i++;
  44.         }
  45.         c->prefixes++;
  46.     }
  47.     int find(char* str)
  48.     {
  49.         int i = 0;
  50.         Node* c = this->root;
  51.         while (str[i] != 0 && c->ch[str[i] - 'a'] != nullptr)
  52.         {
  53.             c = c->ch[str[i] - 'a'];
  54.             i++;
  55.         }
  56.         if (str[i] != 0)
  57.         {
  58.             return 0;
  59.         }
  60.        
  61.         return c->prefixes;
  62.     }
  63. };
  64.  
  65. int main()
  66. {
  67.     std::ios_base::sync_with_stdio(false);
  68.     std::cin.tie(nullptr);
  69.     int n, q;
  70.     std::cin >> n >> q;
  71.     Trie t;
  72.     char s[21];
  73.     for (int i = 0; i < n; i++)
  74.     {
  75.         std::cin >> s;
  76.         t.add(s);
  77.     }
  78.     for (int i = 0; i < q; i++)
  79.     {
  80.         std::cin >> s;
  81.         std::cout << t.find(s) << '\n';
  82.     }
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement