Cod sursa(job #2679315)

Utilizator lucametehauDart Monkey lucametehau Data 30 noiembrie 2020 11:41:30
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <cstring>
#define ch (*s - 'a')

using namespace std;

ifstream cin ("trie.in");
ofstream cout ("trie.out");

int n;
char c;

char s[30];

struct Trie {
  int val, nr;
  Trie* nxt[26];
  Trie() {
    val = nr = 0;
    for(int i = 0; i < 26; i++)
      nxt[i] = 0;
  }
} *R;

void insert(Trie* T, char *s) {
  if(*s == NULL) {
    T->val++;
    return;
  }
  if(T->nxt[ch] == 0) {
    T->nxt[ch] = new Trie;
    T->nr++;
  }
  insert(T->nxt[ch], s + 1);
}

int erase(Trie *T, char *s) {
  if(*s == NULL)
    T->val--;
  else if(erase(T->nxt[ch], s + 1)) {
    T->nxt[ch] = 0;
    T->nr--;
  }
  if(!T->val && !T->nr && T != R) {
    return 1;
  }
  return 0;
}

int query(Trie* T, char *s) {
  if(*s == NULL)
    return T->val;
  if(T->nxt[ch])
    return query(T->nxt[ch], s + 1);
  return 0;
}

int lcp(Trie* T, char *s, int lg) {
  if(*s == NULL || !T->nxt[ch])
    return lg;
  return lcp(T->nxt[ch], s + 1, lg + 1);
}

int main() {
  R = new Trie;
  while(cin >> c >> (s + 1)) {
    if(c == '0')
      insert(R, s + 1);
    else if(c == '1')
      erase(R, s + 1);
    else if(c == '2')
      cout << query(R, s + 1) << "\n";
    else
      cout << lcp(R, s + 1, 0) << "\n";
  }
  return 0;
}