Cod sursa(job #1159432)

Utilizator CypyNXEnculescu Ciprian CypyNX Data 29 martie 2014 16:32:15
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.67 kb
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#define litera (*c-'a')

using namespace std;

ifstream in("trie.in");
ofstream out("trie.out");
/**_______________________________________________________________________________________________ Clasa Nod */
class Nod
{
    int APARITII;
    int NR_FII;
    Nod *FII[26];
    public:
        Nod ();
    friend class Trie;
};

Nod::Nod()
{
    APARITII=NR_FII=0;
    memset(FII,0,sizeof(FII));
}
/**______________________________________________________________________________________________ Clasa Trie */
class Trie
{
    public:
    Nod *START;
        Trie();
        void insert(Nod*,char*);
        int sterge(Nod*,char*);
        void getAPARITII(char*);
        void prefix(Nod*,char*,int);
};

Trie::Trie()
{
    START=new Nod();
}

void Trie::insert(Nod *v,char *c)
{
    if(! *c) {
              v->APARITII ++;
              return;
             }

    if(!v->FII[ litera ]) {
                           v->NR_FII ++;
                           v->FII[ litera ] = new Nod();
                          }

    insert(v->FII[ litera ],c+1);
}

int Trie::sterge(Nod *v,char *c)
{
    if(! *c) v->APARITII --;
      else if(sterge(v->FII[ litera ],c+1)) {
                                             v->NR_FII-- ;
                                             v->FII[litera] = 0;
                                            }
    if(v->APARITII == 0 && v->NR_FII == 0 && v != START)
        {
         delete(v);
         return 1;
        }
    return 0;
}

void Trie::getAPARITII(char *c)
{
    Nod *v=START;
    int i;
    for(i=0;i<strlen(c);i++)
        if(v->FII[*(c+i)-'a']) v=v->FII[*(c+i)-'a'];
          else {out<<"0"<<endl;i=strlen(c)+2;}
    if(i!=strlen(c)+3) out<<v->APARITII<<endl;
}

void Trie::prefix(Nod *v,char *c,int k=0)
{
   if ( !*c || v->FII[litera] == 0) out<<k<<endl;
     else prefix(v->FII[litera],c+1,k+1);
}
/**____________________________________________________________________________________________ Functia Main */
int main()
{
Trie dictionar;
char cuvant[20];
int n;
in>>n;
while(in.get()!=EOF)
    {
     in>>cuvant;
     switch (n) {case  0  : {dictionar.insert(dictionar.START,cuvant);
                             break;}
                 case  1  : {dictionar.sterge(dictionar.START,cuvant);
                             break;}
                 case  2  : {dictionar.getAPARITII(cuvant);
                             break;}
                 case  3  : {dictionar.prefix(dictionar.START,cuvant);
                             break;}
                 }
     in>>n;
    }
in.close();
return 0;
}