Salvens

E

Aug 10th, 2023 (edited)
921
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <array>
  4. #include <vector>
  5. #include <numeric>
  6. #include <random>
  7. #include <chrono>
  8. #include <set>
  9.  
  10.  
  11. using namespace std;
  12.  
  13. const int INF = 1e9 + 7;
  14. const int MAXN = 26 * 100000 + 100;
  15. const int N = 1e5 + 10;
  16.  
  17. struct vertex {
  18.     vertex *next[26];
  19.     bool terminal;
  20.     int cnt = 0;
  21.  
  22.     ~vertex() {
  23.         for (int i = 0; i < 26; ++i) {
  24.             delete next[i];
  25.         }
  26.     }
  27. };
  28.  
  29. vertex* root = new vertex();
  30.  
  31. void add(const string &s) {
  32.     vertex* cur = root;
  33.     for (auto i : s) {
  34.         char x = i - 'a';
  35.         if (cur->next[x] == nullptr) {
  36.             cur->next[x] = new vertex();
  37.         }
  38.         cur = cur->next[x];
  39.         ++cur->cnt;
  40.     }
  41.     cur->terminal = true;
  42. }
  43.  
  44. int get(const string& s) {
  45.     vertex *cur = root;
  46.     for (auto& i : s) {
  47.         char x = i - 'a';
  48.         if (cur->next[x] == nullptr) {
  49.             return 0;
  50.         }
  51.         cur = cur->next[x];
  52.     }
  53.     return cur->cnt;
  54. }
  55.  
  56. signed main() {
  57.     ios_base::sync_with_stdio(false);
  58.     cin.tie(nullptr);
  59.    
  60.     int n;
  61.     cin >> n;
  62.     for (int i = 0; i < n; ++i) {
  63.         string s;
  64.         cin >> s;
  65.         add(s);
  66.     }
  67.  
  68.     int m;
  69.     cin >> m;
  70.     for (int i = 0; i < m; ++i) {
  71.         int type;
  72.         string s;
  73.         cin >> type >> s;
  74.         if (type == 1) {
  75.             add(s);
  76.         } else {
  77.             cout << get(s) << '\n';
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment