Advertisement
Alex_tz307

Trie

Sep 11th, 2020 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define CH (*s - 'a')
  3.  
  4. using namespace std;
  5.  
  6. ifstream fin ("trie.in");
  7. ofstream fout ("trie.out");
  8.  
  9. struct Trie {
  10.     int cnt, nrfii;
  11.     Trie *fiu[26];
  12.     Trie() {
  13.         cnt = nrfii = 0;
  14.         memset(fiu, 0, sizeof(fiu));
  15.     }
  16. };
  17.  
  18. Trie* T = new Trie;
  19.  
  20. void Insert(Trie *nod, char *s) {
  21.     if(*s == '\n') {
  22.         ++nod -> cnt;
  23.         return;
  24.     }
  25.     if(nod -> fiu[CH] == 0) {
  26.         nod -> fiu[CH] = new Trie;
  27.         ++nod -> nrfii;
  28.     }
  29.     Insert(nod -> fiu[CH], s + 1);
  30. }
  31.  
  32. bool Delete(Trie *nod, char *s) {
  33.     if(*s == '\n')
  34.         --nod -> cnt;
  35.     else
  36.         if(Delete(nod -> fiu[CH], s + 1)) {
  37.             nod -> fiu[CH] = 0;
  38.             --nod -> nrfii;
  39.         }
  40.     if(nod -> cnt == 0 && nod -> nrfii == 0 && nod != T) {
  41.         delete nod;
  42.         return true;
  43.     }
  44.     return false;
  45. }
  46.  
  47. int Count(Trie *nod, char *s) {
  48.     if(*s == '\n')
  49.         return nod -> cnt;
  50.     if(nod -> fiu[CH])
  51.         return Count(nod -> fiu[CH], s + 1);
  52.     return 0;
  53. }
  54.  
  55. int Preffix(Trie *nod, char *s, int k) {
  56.     if(*s == '\n' || nod -> fiu[CH] == 0)
  57.         return k;
  58.     return Preffix(nod -> fiu[CH], s + 1, k + 1);
  59. }
  60.  
  61. int main() {
  62.     short op;
  63.     char s[32];
  64.     while(fin >> op) {
  65.         fin >> s;
  66.         s[strlen(s)] = '\n';
  67.         if(op == 0)
  68.             Insert(T, s);
  69.         if(op == 1)
  70.             Delete(T, s);
  71.         if(op == 2)
  72.             fout << Count(T, s) << '\n';
  73.         if(op == 3)
  74.             fout << Preffix(T, s, 0) << '\n';
  75.     }
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement