Cod sursa(job #1629542)

Utilizator NacuCristianCristian Nacu NacuCristian Data 4 martie 2016 16:09:53
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.11 kb
#include <iostream>
#include <stdio.h>
#include <cstring>

using namespace std;

char s[30];

struct nod
{
    int nr_copii, nr_aparitii;
    nod* copii[30];

    nod()
    {
        nr_copii=0;
        nr_aparitii=0;
        memset(copii,0,sizeof(copii));
    }

}*st=new nod();

void adaugare(char *p, nod *x)
{
    if(p[0]!=0 && p[0]!='\n')
    {
        int k=p[0]-'a';
        if(x->copii[k]!=NULL)
        {
            adaugare(p+1,x->copii[k]);
            return;
        }
        x->copii[k]=new nod();
        x->nr_copii++;
        adaugare(p+1,x->copii[k]);
        return;
    }
    x->nr_aparitii++;
    return;

}

int srch(char *p, nod *x)
{
    if(p[0]!=0 && p[0]!='\n')
    {
        int k=p[0]-'a';
        if(x->copii[k]!=NULL)
            return srch(p+1,x->copii[k]);
        return 0;
    }
    return x->nr_aparitii;
}

void del(char *p, nod *x)
{
    if(p[0]!=0 && p[0]!='\n')
    {
        int k=p[0]-'a';
        if(x->copii[k]!=NULL)
        {
            del(p+1,x->copii[k]);
            if(x->copii[k]->nr_aparitii==0 && x->copii[k]->nr_copii==0)
            {
                delete x->copii[k];
                x->copii[k]=NULL;
                x->nr_copii--;
            }
            return;
        }
        return;
    }
    if(x->nr_aparitii)
        x->nr_aparitii--;
    return;

}


int pref(char *p, nod *x)
{
   if(p[0]!=0 && p[0]!='\n')
    {
        int k=p[0]-'a';
        if(x->copii[k]!=NULL)
            return pref(p+1,x->copii[k])+1;
        return 0;
    }
    return 0;
}


void citire()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    while(fgets(s,sizeof(s),stdin))
    {
        if(s[0]=='0')
        {
            adaugare(s+2, st);
        }
        else if(s[0]=='1')
        {
            del(s+2,st);
        }
        else if(s[0]=='2')
        {
            printf("%d\n",srch(s+2, st));
        }
        else if(s[0]=='3')
        {
            printf("%d\n",pref(s+2, st));
        }
    }


}


int main()
{
    citire();

    return 0;
}