Cod sursa(job #2876130)

Utilizator smunteanuMunteanu Stefan Catalin smunteanu Data 23 martie 2022 04:15:11
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <cstring>
#include <array>
using namespace std;

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

void add(Node *&u, char *s) {
  
  if (!*s) {
    u->end++;
    return;
  }

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

}

void remove(Node *&u, char *s) {
  
  if (!*s) {
    u->end--;
    if (!u->end && !u->suc) delete u, u = NULL;
    return;
  }

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

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

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

}

void print(Node *u, char *b, char *e) {
  for (int i = 0; i < u->end; i++)
    cout << b << endl;
  for (int i = 0; i < 26; i++) {
    Node *&v = u->arr[i];
    if (v == NULL) continue;
    *e++ = 'a' + i;
    print(v, b, e);
    *--e = '\0';
  }
}

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;
    }
  }

}