Cod sursa(job #2875207)

Utilizator smunteanuMunteanu Stefan Catalin smunteanu Data 21 martie 2022 11:34:41
Problema Trie Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <cstring>
#include <array>
using namespace std;

struct Node {
  Node *arr[26];
  int end, suc;
  Node() {
    memset(this, 0, sizeof(*this));
  }
};

void add(Node *u, char *s) {

  Node *&v = u->arr[*s - 'a'];
  if (v == NULL) v = new Node;
  if (s[1]) add(v, s + 1);
  else v->end++;
  u->suc++;

}

void remove(Node *u, char *s) {

  Node *&v = u->arr[*s - 'a'];
  if (!s[1] && --v->end + v->suc == 0) delete v, v = NULL;
  if (s[1]) remove(v, s + 1);
  if (u->end + --u->suc == 0) delete u;

}

void occs(Node *u, char *s) {

  int res = 0;
  Node *v = NULL;

  while (*s) {
    v = u->arr[*s++ - 'a'];
    if (v == NULL) break;
    u = v;
  }

  if (v == NULL) cout << 0;
  else cout << v->end;
  cout << '\n';

}

void longpf(Node *u, char *s) {
  int len = 0;
  Node *v = NULL;

  while (*s) {
    v = u->arr[*s++ - 'a'];
    if (v == NULL) break;
    u = v, len++;
  }

  cout << len << '\n';
}

int main() {

  freopen("trie.in", "r", stdin);
  freopen("trie.out", "w", stdout);
  ios_base::sync_with_stdio(false), cin.tie(NULL);

  int op;
  char s[21];
  Node *r = new Node;

  while (cin >> op >> s) {
    switch (op) {
      case 0: add(r, s); break;
      case 1: remove(r, s); break;
      case 2: occs(r, s); break;
      case 3: longpf(r, s); break;
    }
  }

}