Cod sursa(job #406415)

Utilizator RobytzzaIonescu Robert Marius Robytzza Data 1 martie 2010 15:18:13
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <stdio.h>
#include <string.h>

using namespace std;

struct cuv
{
    cuv *a[26];
    int ap,ap_f;
    cuv ()
    {
        ap=ap_f=0;
        memset(a,0,sizeof(a));
    }
}*C;

int k;
char s[21];

void adauga()
{
    cuv *Q = C;
    int lg = strlen(s);
    int poz,i=0;
    while (i < lg-1)
    {
        poz = s[i] - 'a';
        if(Q->a[poz]==NULL)
            Q->a[poz]=new cuv;
        Q=Q->a[poz];
        Q->ap++;
        i++;
    }
        poz=s[lg-1] - 'a';
        if(!Q->a[poz])
            Q->a[poz]=new cuv;
        Q=Q->a[poz];
        Q->ap++;
        Q->ap_f++;
}

void sterge()
{
     cuv*Q=C,*Q1;
    int lg=strlen(s);
     for (int i=0;i<lg;i++)
     {
          Q1=Q;
          Q=Q->a[s[i]-'a'];
          Q->ap--;
          if (Q1->ap==0)
               delete Q1;
          else
               if (Q->ap==0)
                    Q1->a[s[i]-'a']=NULL;
     }
     Q->ap_f--;
     if (Q->ap==0)
          delete Q;
}

int nr_ap()
{
   cuv *Q = C;
    int lg = strlen(s);
    int poz,i=0;
    while (i < lg-1)
    {
        poz = s[i] - 'a';
        if (Q->a[poz]!=NULL)
            Q=Q->a[poz];
        else
            return 0;
        i++;
    }
    if (Q->a[s[lg-1]-'a']!=NULL)
        return Q->a[s[lg-1]-'a']->ap_f;
    return 0;
}

int lg_max()
{
    int nr=0;
    cuv *Q = C;
    int lg = strlen(s);
    int poz,i=0;
    while (i < lg-1)
    {
        poz = s[i] - 'a';
        if (Q->a[poz]!=NULL)
            Q=Q->a[poz];
        else
            return nr;
        nr++;
        i++;
    }
    if (Q->a[s[lg-1]-'a']!=NULL)
        return nr+1;
    return nr;
}

void solve()
{
    C=new cuv;
    C->ap=1;
    while (!feof(stdin))
    {
        scanf ("%d %s\n",&k,&s);
        if (k == 0)
            adauga();
        if (k==1)
            sterge();
        if (k==2)
            printf("%d\n",nr_ap());
        if (k==3)
            printf("%d\n",lg_max());
    }
}

int main ()
{
    freopen ("trie.in","r",stdin);
    freopen ("trie.out","w",stdout);
    solve();
    return 0;
}