Cod sursa(job #3297419)

Utilizator Arhiva_Educationala_2Arhiva Educationala doi Arhiva_Educationala_2 Data 22 mai 2025 16:38:51
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>

const int SIGMA = 26;

struct Trie {
  Trie *c[SIGMA];
  int cnt = 0;
  int all = 0;
};

void insert( Trie* &root, const std::string &str, int idx ) {
  if( !root ) root = new Trie();
  root->all++;

  if( idx == (int)str.size() ){
    root->cnt++;
    return;
  }

  insert( root->c[str[idx]], str, idx + 1 );
}

void erase( Trie* &root, const std::string &str, int idx ) {
  root->all--;
  if( idx == (int)str.size() ){
    root->cnt--;
    return;
  }

  erase( root->c[str[idx]], str, idx + 1 );
}

int count( Trie* root, const std::string &str, int idx ) {
  if( !root ) return 0;
  if( idx == (int)str.size() )
    return root->cnt;

  return count( root->c[str[idx]], str, idx + 1 );
}

int maxpref( Trie *root, const std::string &str, int idx ) {
  if( !root || !root->all ) return -1;
  if( idx == (int)str.size() ) return 0;
  return 1 + maxpref( root->c[str[idx]], str, idx + 1 );
}

int main() {
  std::ifstream fin( "trie.in" );
  std::ofstream fout( "trie.out" );

  Trie *root = new Trie();

  int task;
  while( fin >> task ){
    std::string str;
    fin >> str;
    for( auto &ch : str ) ch -= 'a';

    if( task == 0 ) insert( root, str, 0 );
    if( task == 1 ) erase( root, str, 0 );
    if( task == 2 ) fout << count( root, str, 0 ) << '\n';
    if( task == 3 ) fout << maxpref( root, str, 0 ) << '\n';
  }

  return 0;
}