Cod sursa(job #2949243)

Utilizator ezluciPirtac Eduard ezluci Data 30 noiembrie 2022 11:55:13
Problema Trie Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.17 kb
#ifdef EZ
   #include "./ez/ez.h"
#else
   #include <bits/stdc++.h>
#endif
#define mp make_pair
#define mt make_tuple
#define ll long long
#define pb push_back
#define fi first
#define se second
using namespace std;
const string FILE_NAME = "trie";
ifstream fin (FILE_NAME + ".in");
ofstream fout (FILE_NAME + ".out");

class Nod {

private:
   Nod* fii[26];
   Nod* tat = nullptr;
   int words_count = 0;
   int childs_count = 0;

   Nod* getLastCharNod(char s[])
   {
      Nod *nod = this;
      for (int i = 0; s[i]; ++i)
      {
         char car = s[i];
         if (nod->fii[car-'a'])
            nod = nod->fii[car-'a'];
         else
         {
            nod->fii[car-'a'] = new Nod();
            nod->fii[car-'a']->tat = nod;
            nod->childs_count ++;
            nod = nod->fii[car-'a'];
         }
      }

      return nod;
   }

public:
   Nod()
   {
      fill(fii, fii + 26, nullptr);
   }

   void addCuv(char s[])
   {
      getLastCharNod(s)->words_count ++;
   }

   void delCuv(char s[])
   {
      Nod* last = getLastCharNod(s);
      last->words_count --;

      int i = strlen(s) - 1;
      while (last && last->words_count == 0 && last->childs_count == 0)
      {
         ;
         Nod *aux = last;
         last = last->tat;
         delete aux;
         last->childs_count --;
         last->fii[s[i]-'a'] = nullptr;
         i--;
      }
   }

   int nrApCuv(char s[])
   {
      return getLastCharNod(s)->words_count;
   }

   int lcpCuv(char s[])
   {
      int max = 0;

      Nod *nod = this;  int i;
      for (i = 0; s[i]; ++i)
      {
         char car = s[i];
         if (nod->fii[car-'a'])
            nod = nod->fii[car-'a'];
         else
            return max;
         
         max = std::max(max, i+1);
      }

      return max;
   }
};

int main()
{
   Nod *root = new Nod;

   int op;  char s[21];
   
   while (fin >> op >> s)
   {
      switch (op)
      {
         case 0:
            root->addCuv(s);
            break;
         case 1:
            root->delCuv(s);
            break;
         case 2:
            fout << root->nrApCuv(s) << '\n';
            break;
         case 3:
            fout << root->lcpCuv(s) << '\n';
            break;
      }
   }
}