Cod sursa(job #2014746)

Utilizator MiricaMateiMirica Matei MiricaMatei Data 24 august 2017 12:44:02
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>

const int SIGMA = 'z' - 'a' + 1;
const int MAX_LENGTH = 20;

class Trie {
  public:

  int freq, ss;
  Trie* son[SIGMA + 5];

  Trie() {
    freq = ss = 0;
    for (int i = 1; i <= SIGMA; ++i)
      son[i] = NULL;
  }

  void add(char s[], int pos, int length) {
    if (pos > length) {
      freq++;
      return ;
    }
    int index = s[pos] - 'a' + 1;
    if (son[index] == NULL) {
      son[index] = new Trie;
      ss++;
    }
    son[index] -> add(s, pos + 1, length);
  }

  bool del(Trie* t, char s[], int pos, int length) {
    if (pos > length) {
      freq--;
    } else {
      int index = s[pos] - 'a' + 1;
      bool aux = son[index] -> del(t, s, pos + 1, length);
      if (aux == 1) {
        ss--;
        son[index] = NULL;
      }
    }
    if (ss == 0 && freq == 0 && this != t) {
      delete this;
      return 1;
    }
    return 0;
  }

  int cnt(char s[], int length) {
    Trie* aux = this;
    for (int pos = 1; pos <= length; ++pos) {
      int index = s[pos] - 'a' + 1;
      if (aux -> son[index] == NULL)
        return 0;
      aux = aux -> son[index];
    }
    return aux -> freq;
  }

  int pref(char s[], int length) {
    Trie* aux = this;
    for (int pos = 1; pos <= length; ++pos) {
      int index = s[pos] - 'a' + 1;
      if (aux -> son[index] == NULL)
        return pos - 1;
      aux = aux -> son[index];
    }
    return length;
  }

};

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

  int v;
  Trie* t;
  t = new Trie;

  while (scanf("%d", &v) != EOF) {
    getc(stdin);
    char s[MAX_LENGTH + 5];
    gets(s + 1);
    int length = std::strlen(s + 1);
    switch (v) {
      case 0: {t -> add(s, 1, length); break;}
      case 1: {t -> del(t, s, 1, length); break;}
      case 2: {printf("%d\n", t -> cnt(s, length)); break;}
      case 3: {printf("%d\n", t -> pref(s, length)); break;}
    }
  }

  return 0;
}