Cod sursa(job #1010359)

Utilizator crushackPopescu Silviu crushack Data 14 octombrie 2013 19:20:34
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <stdio.h>

#define LMax 30
#define NUMSONS 26

const char IN[] = "trie.in", OUT[] = "trie.out";

struct trie {
  int all;
  int ending;
  trie * next[NUMSONS];
  trie () {
    ending = 0; all = 0;
    for (int i = 0 ; i < NUMSONS ; ++ i)
      next[i] = NULL;
  }
} *T = new trie();

void add( trie * node, char * s) {

  ++ node -> all;
  for (int i = 0 ; s[i] ; ++ i) {
    if ( ! node -> next[ s[i] - 'a' ] )
      node -> next[ s[i] - 'a' ] = new trie();
    node = node -> next[ s[i] - 'a' ];
    ++ node -> all;
  }

  ++ node -> ending;
}

void erase( trie * node, char * s) {

  -- node -> all;
  for (int i = 0 ; s[i] ; ++ i) {
    if ( !node -> next[ s[i] - 'a' ] )
      return;
    node = node -> next[ s[i] - 'a' ];
    -- node -> all;
  }

  -- node -> ending;
  if ( node -> ending < 0 )
    node -> ending = 0;
}

int getapp( trie * node, char * s) {
  for (int i = 0 ; s[i] ; ++ i) {
    if ( !node -> next[ s[i] - 'a' ] )
      return 0;
    node = node -> next[ s[i] - 'a'];
  }

  return node -> ending;
}

int prefix( trie * node, char * s) {
  int i;
  for (i = 0 ; s[i] ; ++ i) {
    if ( !node -> next[ s[i] - 'a' ] )
      return i;
    node = node -> next[ s[i] - 'a'];
    if ( !node -> all )
      return i;
  }
  return i;
}

int main() {

  int command;
  char s[LMax];
  freopen(IN, "r", stdin);
  freopen(OUT, "w", stdout); 
  while ( scanf("%d", &command) != EOF ) {
    scanf("%s", s);

    switch(command) {
      case 0:
        add(T, s);
      break;

      case 1:
        erase(T, s);
      break;

      case 2:
        printf("%d\n", getapp(T, s));
      break;

      case 3:
        printf("%d\n", prefix(T, s));
      break;
    }
  }
  fclose(stdout);
  fclose(stdin);
  return 0;
}