Cod sursa(job #3295276)

Utilizator Tudor__Holota Tudor-Matei Tudor__ Data 3 mai 2025 22:49:41
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include "bits/stdc++.h"

const int SIGMA = 26;
const int FIRST_LETTER = 'a';

struct Trie{
  Trie* children[SIGMA];
  bool isWord;
  int cnt;
  int subcnt;
};

Trie* root;

Trie* newTrie(){
  Trie* answer = new Trie();
  answer -> isWord = false;
  answer -> cnt = 0;
  answer -> subcnt = 0;
  for(int i = 0; i < SIGMA; i++){
    answer -> children[i] = NULL;
  }
  return answer;
}

void Insert(Trie* root, char *S){
  root -> subcnt++;
  if(S[0] == '\0'){
    root -> isWord = true;
    root -> cnt++;
  }else{
    if(root -> children[S[0] - FIRST_LETTER] == NULL){
      root -> children[S[0] - FIRST_LETTER] = newTrie();
    }
    Insert(root -> children[S[0] - FIRST_LETTER], S + 1);
  }
}

void Erase(Trie* root, char* S){
  root -> subcnt--;
  if(S[0] == '\0'){
    root -> isWord = false;
    root -> cnt--;
  }else{
    if(root -> children[S[0] - FIRST_LETTER] != NULL){
      Erase(root -> children[S[0] - FIRST_LETTER], S + 1);
    }
  }
}

int Find(Trie* root, char* S){
  if(S[0] == '\0'){
    return root -> cnt;
  }else{
    if(root -> children[S[0] - FIRST_LETTER] == NULL){
      return false;
    }else{
      return Find(root -> children[S[0] - FIRST_LETTER], S + 1);
    }
  }
}

int LCP(Trie *root, char* S){
  if(S[0] == '\0'){
    return 0;
  }
  if(root -> children[S[0] - FIRST_LETTER] == NULL or root -> children[S[0] - FIRST_LETTER] -> subcnt == 0){
    return 0;
  }
  return 1 + LCP(root -> children[S[0] - FIRST_LETTER], S + 1);
}

void testcase(){
  Trie* root = newTrie();
  int q;
  char s[21];
  while(std :: cin >> q >> s){
    if(q == 0){
      Insert(root, s);
    }
    if(q == 1){
      Erase(root, s);
    }
    if(q == 2){
      std :: cout << Find(root, s) << '\n';
    }
    if(q == 3){
      std :: cout << LCP(root, s) << '\n';
    }
  }

}

signed main(){
  std :: ios_base :: sync_with_stdio(false);
  std :: cin.tie(0);

  freopen("trie.in", "r", stdin);
  freopen("trie.out", "w", stdout);

  testcase();

  return 0;
}