Cod sursa(job #3041329)

Utilizator dorufDoru Floare doruf Data 31 martie 2023 12:10:36
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using pii = pair<int,int>;
#define eb emplace_back

const string TASK("trie");

ifstream fin(TASK + ".in");
ofstream fout(TASK + ".out");

struct Trie {
  int cnt;
  int nrsons;
  Trie* son[26];
  Trie() {
    cnt = nrsons = 0;
    memset(son, 0, sizeof son);
  }
};
Trie *trie = new Trie;

void ins(Trie* node, char* s) {
  int ch = *s - 'a';
  if (*s == '!') {
    node->cnt += 1;
    return;
  }
  if (node->son[ch] == 0) {
    node->son[ch] = new Trie;
    node->nrsons++;
  }
  ins(node->son[ch], s + 1);
}

bool del(Trie* node, char* s) {
  int ch = *s - 'a';
  if (*s == '!')
    node->cnt--;
  else if (del(node->son[ch], s + 1)) {
    node->son[ch] = 0;
    node->nrsons--;
  }
  if (node != trie)
  if (node->cnt == 0 && node->nrsons == 0) {
    delete node;
    return 1;
  }
  return 0;
}

int nrap(Trie* node, char* s) {
  int ch = *s - 'a';
  if (*s == '!')
    return node->cnt;
  if (node->son[ch])
    return nrap(node->son[ch], s + 1);
  return 0;
}

int pref(Trie* node, char* s, int k) {
  int ch = *s - 'a';
  if (*s == '!' || node->son[ch] == 0)
    return k;
  return pref(node->son[ch], s + 1, k + 1);
}

int32_t main() {
  char str[50];
  int op;
  while (fin >> op >> str) {
    str[strlen(str)] = '!';
    if (op == 0) ins(trie, str);
    if (op == 1) del(trie, str);
    if (op == 2) fout << nrap(trie, str) << '\n';
    if (op == 3) fout << pref(trie, str, 0) << '\n';
  }
}