Cod sursa(job #832132)

Utilizator unholyfrozenCostea Andrei unholyfrozen Data 9 decembrie 2012 21:50:09
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <string>
#include <cstdio>

using namespace std;

class Trie {
  int sigma;
  Trie **children;
  int words, prefix_words;
public:
  Trie(int sigma) : sigma(sigma) {
    children = new Trie*[sigma];
    for (int i = 0; i < sigma; i++)
      children[i] = 0;
    words = 0, prefix_words = 0;
  }
  
  ~Trie() {
    for (int i = 0; i < sigma; i++)
      if (children[i])
	delete children[i];
      
    delete[] children;
  }
  
  void insert(string& c, string::iterator& it) {
    if (it != c.end()) {
      if (children[*it - 'a'] == 0)
	children[*it - 'a'] = new Trie(sigma);
      
      Trie *child = children[*it - 'a'];
      child->insert(c, ++it);
    } else {
      words++;
    }
    prefix_words++;
  }
  
  void Delete(string& c, string::iterator& it) {
    if (it != c.end()) {
      Trie *child = children[*it - 'a'];
      child->Delete(c, ++it);
    } else {
      words--;
    }
    prefix_words--;
  }
  
  int get_words(string& c, string::iterator& it) {
    if (it != c.end()) {
      if (children[*it - 'a']) {
	Trie *child = children[*it - 'a'];
	return child->get_words(c, ++it);
      }
      else
	return 0;
    } else {
      return words;
    }
  }
  
  int get_lcp(string& c, string::iterator& it) {
    if (it != c.end() && children[*it - 'a']) {
      Trie *child = children[*it - 'a'];
      if (child->prefix_words == 0)
	return 0;
      else
	return child->get_lcp(c, ++it) + 1;
    }
    else
      return 0;
  }
};
int main()
{
  freopen("trie.in", "r", stdin);
  freopen("trie.out", "w", stdout);
  
  Trie T(26);
  
  int type;
  char s[21];
  string S;
  string::iterator it;
  do {
    if (scanf("%d %s ", &type, s) < 2)
      break;
    S.assign(s);
    it = S.begin();
    switch(type) {
      case 0: T.insert(S, it); break;
      case 1: T.Delete(S, it); break;
      case 2: printf("%d\n", T.get_words(S, it)); break;
      case 3: printf("%d\n", T.get_lcp(S, it)); break;
    }
  } while(true);
  
  return 0;
}