Cod sursa(job #1476411)

Utilizator salam1Florin Salam salam1 Data 25 august 2015 07:10:36
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <cstdio>
#include <cstring>
const int GAMMA = 26;

struct node {
  int pass, end;
  node* children[GAMMA];
  node() {
    pass = end = 0;
    memset(children, 0, sizeof(children));
  }
};
node* root = new node();

void trieInsert(node* curr, char* s) {
  curr -> pass++;
  if (*s == '\0') {
    curr -> end++;
    return ;
  }
  
  if (curr -> children[*s - 'a'] == 0) {
    curr -> children[*s - 'a'] = new node();
  }
  trieInsert(curr -> children[*s - 'a'], s + 1);
}

void trieDelete(node* curr, char* s) {
  curr -> pass--;
  if (*s == '\0') {
    curr -> end--;
    return ;
  }
  trieDelete(curr -> children[*s - 'a'], s + 1);
  if ((curr -> children[*s - 'a']) -> pass == 0) {
    delete curr -> children[*s - 'a'];
    curr -> children[*s - 'a'] = 0;
  }
}

int trieCnt(node* curr, char* s) {
  if (*s == '\0') {
    return curr -> end;
  }
  
  if (curr -> children[*s - 'a'] == 0) {
    return 0;
  }
  return trieCnt(curr -> children[*s - 'a'], s + 1);
}

int trieLcp(node* curr, char* s) {
  if (*s == '\0' || curr -> children[*s - 'a'] == 0) {
    return 0;
  }
  return 1 + trieLcp(curr -> children[*s - 'a'], s + 1);
}

void solve() {
  int type;
  char word[GAMMA];
  
  while (scanf("%d%s", &type, word) == 2) {
    switch (type) {
      case 0: {
        // add word
        trieInsert(root, word);
        break;
      }
      case 1: {
        trieDelete(root, word);
        break;
      }
      case 2: {
        printf("%d\n", trieCnt(root, word));
        break;
      }
      case 3: {
        printf("%d\n", trieLcp(root, word));
        break;
      }
    }
  }
}

int main() {
  freopen("trie.in", "r", stdin);
  freopen("trie.out", "w", stdout);
  
  solve();
  return 0;
}