Cod sursa(job #2814077)

Utilizator iancupoppPopp Iancu Alexandru iancupopp Data 7 decembrie 2021 16:15:27
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>

using namespace std;

class Node {
public:
  Node(): fii(new Node*[26]()), nr_a(0), nr_c(0) {}
  Node** fii;
  int nr_a, nr_c;
};

class Trie {
private:
  Node* root;
  Node* _insert(char s[], Node* nod) {
    if (nod == nullptr)
      nod = new Node;
    ++nod->nr_a;
    if (s[0] == NULL)
      ++nod->nr_c;
    else
      nod->fii[s[0] - 'a'] = _insert(s + 1, nod->fii[s[0] - 'a']);
    return nod;
  }
  Node* _erase(char s[], Node* nod) {
    if (nod == nullptr)
      return nullptr;
    --nod->nr_a;
    if (s[0] == NULL)
      --nod->nr_c;
    else
      nod->fii[s[0] - 'a'] = _erase(s + 1, nod->fii[s[0] - 'a']);
    if (nod->nr_a == 0) {
      delete nod;
      nod = nullptr;
    }
    return nod;
  }
  int _query_pref(char s[], Node* nod) {
    if (nod == nullptr || s[0] == NULL)
      return 0;
    if (nod->fii[s[0] - 'a'] == nullptr)
      return 0;
    return _query_pref(s + 1, nod->fii[s[0] - 'a']) + 1;
  }
  int _query_cuv(char s[], Node* nod) {
    if (nod == nullptr)
      return 0;
    if (s[0] == NULL)
      return nod->nr_c;
    return _query_cuv(s + 1, nod->fii[s[0] - 'a']);
  }

public:
  Trie(): root(nullptr) {}
  void insert(char s[]) {
    root = _insert(s, root);
  }
  void erase(char s[]) {
    root = _erase(s, root);
  }
  int query_pref(char s[]) {
    return _query_pref(s, root);
  }
  int query_cuv(char s[]) {
    return _query_cuv(s, root);
  }
};

int main() {
  ifstream cin("trie.in");
  ofstream cout("trie.out");
  int op;
  char s[21];
  Trie t;
  while (cin >> op >> s) {
    if (op == 0)
      t.insert(s);
    else if (op == 1)
      t.erase(s);
    else if (op == 2)
      cout << t.query_cuv(s) << "\n";
    else
      cout << t.query_pref(s) << "\n";
  }
  cin.close();
  cout.close();
  return 0;
}