Cod sursa(job #2913631)

Utilizator avtobusAvtobus avtobus Data 15 iulie 2022 16:44:44
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <stdio.h>
#include <bits/stdc++.h>
#include <string>
#include <string_view>

#define rep(i, n) for(int i = 0; i < (int)(n); i++)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
struct Node {
  int cnt{0},stop{0};
  array<int, 26> children{0};
};

int main(void) {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(nullptr);
  freopen("trie.in", "r", stdin);
  freopen("trie.out", "w", stdout);
  // each T[nod] represents a prefix;
  // T[0] is the empty prefix ("")
  vector<Node> T(1);
  function<void(const string&, size_t, int)> add, del;
  function<int(const string&, size_t, int)> count, l_prefix;
  add = [&](const string &word, size_t ind, int nod)->void{
    T[nod].cnt++;
    if (ind == word.size()) {
      T[nod].stop++;
      return;
    }
    int c = word[ind] - 'a';
    if (!T[nod].children[c]) {
      T[nod].children[c] = T.size();
      T.emplace_back();
    }

    add(word, ind+1, T[nod].children[c]);
  };
  del = [&](const string &word, size_t ind, int nod)->void {
    T[nod].cnt--;
    if (ind == word.size()) {
      T[nod].stop--;
      return;
    }
    int c = word[ind] - 'a';
    if (T[nod].children[c]) {
      del(word, ind+1, T[nod].children[c]);
    }
  };
  count = [&](const string &word, size_t ind, int nod)->int{
    if (ind == word.size()) {
      return T[nod].stop;
    }
    int c = word[ind] - 'a';
    if (!T[nod].children[c]) {
      return 0;
    }
    return count(word, ind+1, T[nod].children[c]);
  };
  l_prefix = [&](const string &word, size_t ind, int nod)->int {
    if (!T[nod].cnt) {
      return -1;
    }
    if (ind == word.size()) {
      return 0;
    }
    int c = word[ind] - 'a';
    if (!T[nod].children[c]){
      return 0;
    }
    return 1 + l_prefix(word, ind+1, T[nod].children[c]);
  };

  int q;
  string word;
  while(cin >> q) {
    cin >> word;
    if (q == 0) {
      add(word, 0, 0);
    } else if (q == 1) {
      del(word, 0, 0);
    } else if (q == 2) {
      cout << count(word, 0, 0) << "\n";
    } else if (q == 3) {
      cout << l_prefix(word, 0, 0) << "\n";
    }
  }

  return 0;
}