Cod sursa(job #2074938)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 25 noiembrie 2017 10:05:25
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>
using namespace std;

int operation;
char argument[30];

struct Trie{
  int ends;
  int counter;
  Trie* next[27];

  Trie();
}*root;

Trie::Trie() {
  ends = counter = 0;
  for (int i = 0; i < 27; i++)
    next[i] = NULL;
}

void trieInsert(Trie*& node, char *p) {
  if(!*p) {
    node->ends++;
    return;
  }
  if(!node->next[*p - 'a']) {
    node->next[*p - 'a'] = new Trie;
    node->counter++;
  }
  trieInsert(node->next[*p - 'a'], p + 1);
}


bool trieRemove(Trie*& node, char *p) {
  if(!*p) {
    node->ends--;
  } else if(trieRemove(node->next[*p - 'a'], p + 1)) {
    node->next[*p - 'a'] = NULL;
    node->counter--;
  }

  if(!node->ends && !node->counter && node != root) {
    delete node;
    return true;
  }

  return false;
}

int trieSearch(Trie*& node, char *p) {
  if(!*p) {
    return node->ends;
  }
  if(!node->next[*p - 'a'])
    return 0;
  return trieSearch(node->next[*p - 'a'], p + 1);
}

int trieLongestCommonPrefix(Trie*& node, char *p, int result) {
  if(!*p || !node->next[*p - 'a'])
        return result;
  return trieLongestCommonPrefix(node->next[*p - 'a'],p + 1, result + 1);
}

int main() {
  root = new Trie;

  freopen("trie.in", "r", stdin);
  freopen("trie.out", "w", stdout);

  while(!feof(stdin)) {
    scanf("%d %s ", &operation, argument);

    switch(operation) {
      case 0:
        trieInsert(root, argument);
        break;
      case 1:
        trieRemove(root, argument);
        break;
      case 2:
        printf("%d\n", trieSearch(root, argument));
        break;
      case 3:
        printf("%d\n", trieLongestCommonPrefix(root, argument, 0));
        break;
    }
  }

  return 0;
}