Cod sursa(job #833509)

Utilizator RaileanuCristian Raileanu Raileanu Data 12 decembrie 2012 17:27:50
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>
#include <cstring>

#define CH (*s - 'a')

struct trie{
        int nfii, nap;
        trie *fiu[26];
        trie(){
            nfii=nap=0;
            memset(fiu,0,sizeof(fiu) ); } };
trie *t;

void insert(trie *nod, char *s ) {
        while (*s!= '\n' )
            {   if (!nod->fiu[CH ])
                {nod->fiu[CH]= new trie; nod->nfii++; }
                nod=nod->fiu[CH];
                s++; }
        nod->nap++;
        }

int del(trie *nod, char *s){
        if (*s=='\n' )
            nod->nap--;  else
            if (del(nod->fiu[CH],s+1 ))
                { nod->fiu[CH]=0;
                  nod->nfii--;  }

            if (nod->nap==0 && nod->nfii==0 && nod!=t) {delete nod; return 1;}
            return 0;
        }

int nrap(trie *nod, char *s){
       while (*s!= '\n' )
          if (nod->fiu[CH] )
            {  nod=nod->fiu[CH];
               s++; }
               else return 0;
        return nod->nap; }

int clpc(trie *nod, char *s) {
        int ad=0;
        while (*s!= '\n' && nod->fiu[CH])
            {  nod=nod->fiu[CH];
               s++;  ad++;}
        return ad; }

int main()
{   char line[32];
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    t= new trie;

    fgets(line,32,stdin);
    while   (!feof(stdin) ) {
            switch (line[0]) {
            case '0': insert(t, line+2); break;
            case '1': del(t, line+2); break;
            case '2': printf("%d\n",nrap(t, line+2)); break;
            case '3': printf("%d\n",clpc(t, line+2)); break; }
     fgets(line,32,stdin);
    }


    return 0;
}