Cod sursa(job #348248)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 15 septembrie 2009 01:02:40
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.46 kb
#include<stdio.h>
#include<cstring>
char w[50];
int NrAp;
int cmlpc;
struct NodT {
    int V;
    int NrFii;
    NodT *E[28];

    NodT()
    {
        V = 0;
        NrFii = 0;
        for(int i = 0; i <= 26; i++)
         E[i] = 0;
    }
};

NodT *T = new NodT;
void Insert(NodT *t, int poz)
{
        if (w[poz] == '\n')
         {
             t-> V++;
             return;
         }
         else
         {
        if (t -> E[w[poz] - 'a']) Insert(t -> E[w[poz] - 'a'], poz + 1);
                        else
                         {
                             t -> NrFii++;
                             t -> E[w[poz] - 'a'] = new NodT;
                             Insert(t -> E[w[poz] - 'a'], poz + 1);
                         }
         }


}

int Delete(NodT *t, int poz)
{
        if (w[poz] == '\n') t -> V--;
         else
          {
              if (Delete(t -> E[w[poz] - 'a'], poz + 1))
               {
                   t -> E[w[poz] - 'a'] = 0;
                   t -> NrFii --;
               }

          }
         if (!t -> V && !t -> NrFii && t != T)
          {
              delete t;
              return 1;
          }
        return 0;


}

int Query1(NodT *t, int poz) // - numarul de aparitii
{
        if (w[poz] == '\n') NrAp = t -> V;
         else
        if (t -> E[w[poz] - 'a']) Query1(t -> E[w[poz] - 'a'], poz + 1);
         else
        NrAp = 0;

}
void Query2(NodT *t, int poz) // - cel mai lung prefix comun
{
        if (w[poz] == '\n') return;
         else
        if (t -> E[w[poz] - 'a'])
         {
             cmlpc++;
             Query2(t -> E[w[poz] - 'a'], poz + 1);
         }


}
int main()
{
        freopen("trie.in","r",stdin);
        freopen("trie.out","w",stdout);
        fgets(w, 32, stdin);
        while (!feof(stdin))
           {
               if (w[0] == '0')
                {
                    Insert(T, 2);
                }
               if (w[0] == '1')
                {
                    Delete(T,2);
                }
               if (w[0] == '2')
                {
                    Query1(T,2);
                    printf("%d\n", NrAp);
                }
               if (w[0] == '3')
                {
                    cmlpc = 0;
                    Query2(T,2);
                    printf("%d\n", cmlpc);
                }

               fgets(w, 32, stdin);
           }

        return 0;
}