Cod sursa(job #1630207)

Utilizator PaulCbnCiobanu Paul PaulCbn Data 4 martie 2016 23:23:52
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

struct nod
{
    int val,nr;
    nod *adr[27];
    nod()
    {
        val = 0;
        nr = 0;
        memset( adr, 0, sizeof( adr ) );
    }
};

void adauga(nod *curent, char *s)
{
    if(*s == 0)
    {
        curent->val++;
        return;

    }
    if(curent->adr[*s - 'a']==NULL)
    {
        curent->adr[*s - 'a'] = new nod;
        curent->nr++;
    }

    adauga(curent->adr[*s - 'a'],s+1);
}

void sterge(nod *curent, char *s,int &ok)
{
    if(*s == 0)
    {
        curent->val--;
        if(curent->val == 0)
            ok = 1;
        return;

    }
    sterge(curent->adr[*s - 'a'],s+1,ok);
    if(ok&&curent->nr == 1)
    {
        curent->adr[*s - 'a'] = 0;
    }
    else if(ok&&curent->nr >= 2)
    {
        curent->adr[*s - 'a'] = 0;
        ok = 0;
    }

}

void aparitii(nod *curent, char *s)
{
    if(*s == 0)
    {
        printf("%d\n",curent->val);
        return;

    }
    aparitii(curent->adr[*s - 'a'],s+1);
}

void prefix(nod *curent, char *s, int m)
{

    m++;
    if((*s)&&curent->adr[*s-'a'])
        prefix(curent->adr[*s-'a'],s+1,m);
    else
        printf("%d\n",m-1);


}

int main()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    nod *arbore = new nod;
    char s[25];
    int op;
    while(scanf("%d",&op)>0)
    {
        int m = 0;
        int ok=0;
        scanf("%s",&s);
        if(op==0)
            adauga(arbore,s);
        if(op==1)
            sterge(arbore,s,ok);
        if(op==2)
            aparitii(arbore,s);
        if(op==3)
            prefix(arbore,s,m);


    }

    return 0;
}