Cod sursa(job #2820516)

Utilizator andreic06Andrei Calota andreic06 Data 20 decembrie 2021 16:50:56
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.39 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, count_word;
      } 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 ++;
          }
          ds[node].count_word ++;
      }

      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] ) {
             node = ds[node].link[code];
             last_frecv = ds[node].frecv;
             letter ++; code = *letter - 'a';
          }
          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';
         while ( letter != prefix.end () && ds[node].link[code] ) {
            node = ds[node].link[code];
            letter ++; code = *letter - 'a';
         }
         if ( letter == prefix.end () )
           return ds[node].count_word;
         return 0;
      }

} trie;

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