Cod sursa(job #1065129)

Utilizator vendettaSalajan Razvan vendetta Data 22 decembrie 2013 20:15:30
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 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, countPrefix;
   Trie *son[Sigma];
   Trie(){
      countWord = 0; countPrefix = 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()){
      //cout << S << " " << node->countWord<< "\n";
      node->countWord++;// here it`s an word
      //cout << node->countWord << "\n";
      return;
   }
   int letter = S[pos] - 'a';
   if (node->son[letter] == NULL){// new appereance
      Trie *newNode = new Trie();
      node->son[letter] = newNode;
      newNode->countPrefix++;
      add(pos+1, newNode);
   }else{
      node->son[letter]->countPrefix++;
      add(pos+1, node->son[letter]);
   }
}

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

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 || node->son[letter]->countPrefix == 0)
         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 || node->son[ S[pos]-'a' ]->countPrefix==0){
      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
            cout << countOcc(2, root) << "\n";
            break;
         case '3':
            cout << lcp(2, root, 0) << "\n";
            break;
      }
   }

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

   return 0;
}