Cod sursa(job #3143512)

Utilizator VladNANegoita Vlad-Andrei VladNA Data 31 iulie 2023 00:35:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 kb
#include <bits/stdc++.h>

using namespace std;

class Trie {
private:
  static const int alphabet_size = 26;
  Trie *node[alphabet_size] = {};
  int words_in_subtree = 0;
  int current_word_count = 0;

public:
  void insert_word(string &word);
  void erase_word(string &word, int index);
  int count_word(string &word);
  int longest_common_prefix(string &word);
};

void Trie::insert_word(string &word) {
  Trie *current_node = this;
  for (int i = 0; i < word.size(); ++i) {
    ++current_node->words_in_subtree;
    if (!current_node->node[word[i] - 'a'])
      current_node->node[word[i] - 'a'] = new Trie;
    current_node = current_node->node[word[i] - 'a'];
  }

  ++current_node->words_in_subtree;
  ++current_node->current_word_count;
}

// we assume the word exists
void Trie::erase_word(string &word, int index = 0) {
  --words_in_subtree;

  if (index == word.size()) {
    --current_word_count;
    return;
  }

  node[word[index] - 'a']->erase_word(word, index + 1);
  if (node[word[index] - 'a']->words_in_subtree == 0) {
    delete node[word[index] - 'a'];
    node[word[index] - 'a'] = NULL;
  }
}

// we assume the correct management of memory
int Trie::count_word(string &word) {
  Trie *current_node = this;
  for (int i = 0; i < word.size() && current_node; ++i)
    current_node = current_node->node[word[i] - 'a'];

  if (!current_node)
    return 0;

  return current_node->current_word_count;
}

// we assume the correct management of memory
int Trie::longest_common_prefix(string &word) {
  Trie *current_node = this;
  for (int i = 0; i < word.size(); ++i) {
    if (!current_node->node[word[i] - 'a'])
      return i;
    current_node = current_node->node[word[i] - 'a'];
  }

  return word.size();
}

int main() {
  freopen("trie.in", "rt", stdin);
  freopen("trie.out", "wt", stdout);

  int type;
  string word;
  auto trie = new Trie;
  while (cin >> type >> word) {
    switch (type) {
    case 0:
      trie->insert_word(word);
      break;
    case 1:
      trie->erase_word(word);
      break;
    case 2:
      cout << trie->count_word(word) << endl;
      break;
    case 3:
      cout << trie->longest_common_prefix(word) << endl;
      break;
    default:
      cout << "Unrecognized operation" << endl;
      exit(-1);
    }
  }
  return 0;
}