Cod sursa(job #3252004)

Utilizator rockoanaOana Pasca rockoana Data 28 octombrie 2024 10:46:21
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
/*
                    __
                   /\ \
 _ __   ___     ___\ \ \/'\     ___      __      ___     ___      __
/\`'__\/ __`\  /'___\ \ , <    / __`\  /'__`\  /' _ `\ /' _ `\  /'__`\
\ \ \//\ \L\ \/\ \__/\ \ \\`\ /\ \L\ \/\ \L\.\_/\ \/\ \/\ \/\ \/\ \L\.\_
 \ \_\\ \____/\ \____\\ \_\ \_\ \____/\ \__/.\_\ \_\ \_\ \_\ \_\ \__/.\_\
  \/_/ \/___/  \/____/ \/_/\/_/\/___/  \/__/\/_/\/_/\/_/\/_/\/_/\/__/\/_/


*/

#include <bits/stdc++.h>
using namespace std;

#define ft first
#define sd second
#define endl '\n'

using i64 = int64_t;

struct node {
  int cnt, kidz;
  node* v[27];

  node() {
    cnt = 0;
    kidz = 0;
    for (int i = 0; i < 27; i++) {
      v[i] = NULL;
    }
  }
};

node* root = new node();

void add(node* crt, string& s, int idx) {
  if (idx == (int)s.size()) {
    crt->cnt++;
    return;
  }

  if (crt->v[s[idx] - 'a'] == NULL) {
    crt->v[s[idx] - 'a'] = new node();
    crt->kidz++;
  }
  add(crt->v[s[idx] - 'a'], s, idx + 1);
}

bool del(node* crt, string& s, int idx) {
  if (idx == (int)s.size()) {
    if (crt->cnt <= 1 && crt->kidz == 0) {
      delete crt;
      return true;
    }
    crt->cnt--;
    return false;
  }

  bool d = del(crt->v[s[idx] - 'a'], s, idx + 1);
  if (d) {
    crt->kidz -= d;
    crt->v[s[idx] - 'a'] = NULL;
  }
  if (crt == root) {
    return false;
  }
  if (crt->kidz == 0 && crt->cnt == 0) {
    delete crt;
    return true;
  }

  return false;
}

int query_ap(node* crt, string& s, int idx) {
  if (idx == (int)s.size()) {
    return crt->cnt;
  }

  if (crt->v[s[idx] - 'a'] == NULL) {
    return 0;
  }
  return query_ap(crt->v[s[idx] - 'a'], s, idx + 1);
}

int query_pre(node* crt, string& s, int idx) {
  if (idx == (int)s.size()) {
    return 0;
  }

  if (crt->v[s[idx] - 'a'] == NULL) {
    return 0;
  }
  return 1 + query_pre(crt->v[s[idx] - 'a'], s, idx + 1);
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  // #ifdef LOCAL
  //   ifstream cin{"input.txt"};
  //   ofstream cout{"output.txt"};
  // #endif

  ifstream cin{"trie.in"};
  ofstream cout{"trie.out"};

  int x;
  string s;
  while (cin >> x) {
    cin >> s;

    if (x == 0) {
      add(root, s, 0);
    } else if (x == 1) {
      del(root, s, 0);
    } else if (x == 2) {
      cout << query_ap(root, s, 0) << endl;
    } else if (x == 3) {
      cout << query_pre(root, s, 0) << endl;
    }
  }

  return 0;
}