Cod sursa(job #2820514)

Utilizator andreic06Andrei Calota andreic06 Data 20 decembrie 2021 16:30:06
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
const int TOTAL_LEN = 1e5;
const int SIGMA = 26;
const int ROOT = 0;


struct TRIE {
      struct node {
            int link[SIGMA];
            int frecv;
      } ds[1 + TOTAL_LEN * SIGMA];

      int node_index = 0;
      void add_string ( string elem ) {
          int node = ROOT;
          for ( auto letter : elem ) {
             int code = letter - 'a';
             if ( !ds[node].link[code] )
               ds[node].link[code] = ++ node_index;
             node = ds[node].link[code];
             ds[node].frecv ++;
          }
      }

      void delete_string ( string elem ) {
          int node = ROOT;
          for ( auto letter : elem ) {
             int code = letter - 'a';
             if ( ds[node].frecv == 1 )
               ds[node].link[code] = 0;
             node = ds[node].link[code];
             ds[node].frecv --;
          }
      }

      int count_app ( string target ) {
          int node = ROOT;
          auto letter = target.begin (); int code = *letter - 'a';
          int last_frecv = 0;
          while ( letter != target.end () && ds[node].link[code] ) {
             letter ++;
             node = ds[node].link[code];
             last_frecv = ds[node].frecv;
          }
          if ( letter == target.end () )
            return last_frecv;
          return 0;
      }

      int longest_common_pref ( string prefix ) {
         int node = ROOT;
         auto letter = prefix.begin (); int code = *letter - 'a';
         int last_frecv = 0;
         while ( letter != prefix.end () && ds[node].link[code] ) {
            letter ++;
            node = ds[node].link[code];
            last_frecv = ds[node].frecv;
         }
         return last_frecv;
      }

} trie;

ifstream fin ( "trie.in" );
ofstream fout ( "trie.out" );
int main()
{
   int t; string input;
   while ( fin >> t >> input ) {
      if ( t == 1 )
        trie.add_string ( input );
      else if ( t == 2 )
        trie.delete_string ( input );
      else if ( t == 3 ) {
        fout << trie.count_app ( input );
        fout << "\n";
      }
      else {
        fout << trie.longest_common_pref ( input );
        fout << "\n";
      }
   }
    return 0;
}