Cod sursa(job #581164)

Utilizator drywaterLazar Vlad drywater Data 13 aprilie 2011 20:34:05
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <stdio.h>
#define Z (*(s+1)-'a')
struct Trie
{int nrc; int nrf; Trie *fiu[26];
Trie()
{nrc=nrf=0; for (int i=0;i<=25;i++) fiu[i]=0;}};
int ti;
Trie *T=new Trie;
char s[30];
int ins(Trie *nod,char *s)
{
    if (!*(s+1))
    {nod->nrc++; return 0;}

    if (!nod->fiu[Z])
    {
        nod->fiu[Z]=new Trie;
        nod->nrf++;
    }
    ins(nod->fiu[Z],s+1);
    return 0;
}
int del(Trie *nod,char *s)
{
    if (!*(s+1)) nod->nrc--;
    else if (del(nod->fiu[Z],s+1))
            {
                nod->fiu[Z]=NULL;
                nod->nrf--;
            }
    if (nod->nrc==0 && nod->nrf==0 && nod!=T) {delete nod; return 1;}
    return 0;
}
int cat(Trie *nod,char *s)
{
    if (!*(s+1)) return nod->nrc;
    if (nod->fiu[Z]) return cat(nod->fiu[Z],s+1);
    return 0;
}
int pre (Trie *nod,char *s,int nr)
{
    if (!*(s+1) || !nod->fiu[Z]) return nr+1;
    return pre(nod->fiu[Z],s+1,nr+1);
}
int main(void)
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    scanf("%d %s",&ti,s);
    while (!feof(stdin))
    {
        if (ti==0) ins(T,s);
        else if (ti==1) del(T,s);
        else if (ti==2) printf("%d\n",cat(T,s));
        else printf("%d\n",pre(T,s,0));
        scanf("%d %s",&ti,s);
    }
    return 0;
}