Cod sursa(job #237765)

Utilizator mika17Mihai Alex Ionescu mika17 Data 30 decembrie 2008 18:11:55
Problema Trie Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>

using namespace std;

struct node
{
 int cuv,pref;
 node * child[26];
} *rad;

ifstream fin("trie.in");
ofstream fout("trie.out");

void init()
{
        rad = new node();
}

void addWord(node * ver,char * word,int l,int r)
{
        if(l > r) ver->cuv++;
        
         else
         {
          ver->pref++;

          node * &ch = ver->child[ word[l] - 'a' ];

          if(!ch) ch = new node();

          addWord(ch,word,l + 1,r);
         }
}

void eraseWord(node * ver,char * word,int l,int r) //tre cautat cuv inainte
{
       if(l > r) ver->cuv--;

        else
        {
         node * &ch = ver->child[ word[l] - 'a'];
         if(ch)
         {
          ver->pref--;
          eraseWord(ch,word,l + 1,r);

          if(!ch->cuv && !ch->pref) {delete ch; ch = 0;}
         }
        }
}

int count(node * ver,char * word,int l,int r)
{
      if(!ver) return 0;
      if(l > r)
         return ver->cuv;
        else return count( ver->child[word[l] - 'a'],word,l + 1,r);
}

int longestPref(node * ver,char * word,int l,int r)
{
      node * ch = ver->child[word[l] - 'a'];
      if(ch && l <= r) return 1 + longestPref(ch,word,l + 1,r);
      return 0;
}

int main()
{
        char c[21];
        int op;

        init();

        while(!fin.eof())
        {
                fin>>op>>c;

                switch(op)
                {
                 case 0: addWord(rad,c,0,strlen(c) - 1); break;
                 case 1: eraseWord(rad,c,0,strlen(c) - 1);   break;
                 case 2: fout<<count(rad,c,0,strlen(c) - 1)<<'\n';   break;
                 case 3: fout<<longestPref(rad,c,0,strlen(c) - 1)<<'\n';  break;
                }
        }

        return 0;
}