Advertisement
LA77

Untitled

Feb 25th, 2025
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define SIGMA 30
  3. using namespace std;
  4.  
  5. ifstream fin("trie.in");
  6. ofstream fout("trie.out");
  7.  
  8. struct Trie
  9. {
  10.     struct Node
  11.     {
  12.         int cnt, rasp;
  13.         Node *fii[SIGMA];
  14.     };
  15.  
  16.     Node *root = new Node();
  17.  
  18.     inline void add(char *s, Node *poz)
  19.     {
  20.         poz->cnt++;
  21.         if(*s == '\0')
  22.         {
  23.             poz->rasp++;
  24.             return;
  25.         }
  26.         int x = *s - 'a';
  27.         if(poz->fii[x] == NULL)
  28.             poz->fii[x] = new Node();
  29.         add(s + 1, poz->fii[x]);
  30.     }
  31.  
  32.     inline void rem(char *s, Node *poz)
  33.     {
  34.         poz->cnt--;
  35.         if(*s == '\0')
  36.         {
  37.             poz->rasp--;
  38.             return;
  39.         }
  40.         int x = *s - 'a';
  41.         rem(s + 1, poz->fii[x]);
  42.     }
  43.  
  44.     inline int search_1(char *s, Node *poz)
  45.     {
  46.         if(*s == '\0')
  47.             return poz->rasp;
  48.         int x = *s - 'a';
  49.         if(poz->fii[x] == NULL)
  50.             return 0;
  51.         return search_1(s + 1, poz->fii[x]);
  52.     }
  53.  
  54.     inline int search_2(char *s, Node *poz)
  55.     {
  56.         int x = *s - 'a';
  57.         if(*s == '\0' || poz->fii[x] == NULL || !poz->fii[x]->cnt)
  58.             return 0;
  59.         return search_2(s + 1, poz->fii[x]) + 1;
  60.     }
  61. };
  62.  
  63. int op;
  64. char s[30];
  65. Trie trie;
  66.  
  67. int main()
  68. {
  69.     ios::sync_with_stdio(false);
  70.     fin.tie(NULL);
  71.     fout.tie(NULL);
  72.  
  73.     while(fin >> op >> s)
  74.     {
  75.         if(op == 0)
  76.         {
  77.             trie.add(s, trie.root);  
  78.         }
  79.         if(op == 1)
  80.         {
  81.             trie.rem(s, trie.root);
  82.         }
  83.         if(op == 2)
  84.         {
  85.             fout << trie.search_1(s, trie.root) << '\n';
  86.         }
  87.         if(op == 3)
  88.         {
  89.             fout << trie.search_2(s, trie.root) << '\n';
  90.         }
  91.         memset(s, 0, sizeof(s));
  92.     }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement