Cod sursa(job #1065172)

Utilizator vendettaSalajan Razvan vendetta Data 22 decembrie 2013 21:53:03
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.65 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
#include <deque>
#include <map>
#include <cmath>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

#define ll long long
#define pb push_back
#define mp make_pair
#define sz size
#define x first
#define y second

#define nmax
#define inf
#define Sigma 27

struct Trie{
   int countWord;// o sa imi zica de cate ori apare cuvantul adica de cate ori ajung in nodul curent
   int countSons;// o sa imi zica cati fii are nodul curent;
   // o sa am nevoie de el pt a vedea daca sterg nodul curent sau nu
   Trie *son[Sigma];
   Trie(){
      countWord = 0; countSons = 0;
      for(int i=0; i<Sigma; ++i) son[i] = NULL;
   }
};

Trie *root = new Trie;
string S;

void add(int pos, Trie *node){
   if (pos == (int)S.sz()){
      node->countWord++;// here it`s an word
      return;
   }
   int letter = S[pos] - 'a';
   if (node->son[letter] == NULL){// new appereance
      node->son[letter] = new Trie();
      node->countSons++;// new Son
   }
   node = node->son[letter];
   add(pos+1, node);
}

bool del(int pos, Trie *node){
   if (pos == S.sz()){
      node->countWord--;
   }else{
      if ( del(pos+1, node->son[ S[pos]-'a' ]) == 1 ){// daca nodul in care urmeaza sa ma duc l-am sters numarul de fii din ondul curent scade
         node->son[ S[pos]-'a' ] = NULL;
         node->countSons--;
      }
   }
   // acum incerc sa sterg nodul curent
   if ( node->countSons == 0 && node->countWord == 0 && node != root ){// daca numai are nici un fiu, nici un cuvant nu se termina pe el
      // si nu e radacina
      delete node;
      return 1;
   }
   return 0;
}

int countOcc(int pos, Trie *node){
   if (pos == (int)S.sz()){
      return node->countWord;
   }else{
      int letter = S[pos] - 'a';
      if (node->son[letter] == NULL)
         return 0;
      else return countOcc(pos+1, node->son[letter]);
   }
}

int lcp(int pos, Trie *node, int x){
   if (pos == (int)S.sz() || node->son[ S[pos]-'a' ] == NULL){
      return x;
   }else{
      return lcp(pos+1, node->son[ S[pos]-'a' ], x+1);
   }
}

int main(){
   for(; getline(f, S); ){
      switch( S[0] ){
         case '0':// add a new word
            add(2, root);
            break;
         case '1':// delete occurrence of a word
            del(2, root);
            break;
         case '2':// number of occurrence of a word
            g << countOcc(2, root) << "\n";
            break;
         case '3':
            g << lcp(2, root, 0) << "\n";
            break;
      }
   }

   f.close();
   g.close();

   return 0;
}