Cod sursa(job #413525)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 8 martie 2010 18:15:52
Problema Trie Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include<stdio.h>
#include<string.h>
#define Nmx 50


using namespace std;
char c[Nmx];
struct trie
{
    int nra,nrap;
    trie *vec[Nmx];
    trie()
    {
        nra=nrap=0;
        memset(vec,0,sizeof(vec));
    }
};
trie *rad;

void add(trie *nod,char *s)
{
    int nr1=strlen(s)-1;
    for(int i=0;i<nr1-1;++i,++s)
    {
        int pz=*s-'a';
        if(nod->vec[pz]==NULL)
            nod->vec[pz]=new trie;
        nod=nod->vec[pz];
        nod->nra++;
    }
    int pz=*s-'a';
    if(nod->vec[pz]==NULL)
        nod->vec[pz]=new trie;
    nod=nod->vec[pz];
    nod->nra++;
    nod->nrap++;
}

void scot(trie *nod,char *s)
{
    trie *nod1;
    int nr1=strlen(s)-1;
    for(int i=0;i<nr1;++i,++s)
    {
        nod1=nod;
        int pz=*s-'a';
        nod=nod->vec[pz];
        nod->nra--;
        if(nod1->nra==0)
            delete(nod1);
        else if(nod->nra==0)
                nod1->vec[pz]=NULL;
    }
    nod->nrap--;
    if(nod->nra==0)
        delete(nod);
}

int nr_ap(trie *nod,char *s)
{
    int nr1=strlen(s)-1;
    for(int i=0;i<nr1;++i,++s)
    {
        int pz=*s-'a';
        if(nod->vec[pz]!=NULL)
            nod=nod->vec[pz];
        else return 0;
    }
    return nod->nrap;
}

int nr_prefix(trie *nod,char *s)
{
    int nr1=strlen(s)-1;
    int sol=0;
    for(int i=0;i<nr1;++i,++s)
    {
        int pz=*s-'a';
        if(nod->vec[pz]!=NULL)
        {
            nod=nod->vec[pz];
            ++sol;
        }
        else return sol;
    }
    return sol;
}

void citire()
{
    rad=new trie;
    rad->nra=1;
    fgets(c,Nmx,stdin);
    while(!feof(stdin))
    {
        if(c[0]=='0') add(rad,c+2);
        else if(c[0]=='1')  scot(rad,c+2);
        else if(c[0]=='2') printf("%d\n",nr_ap(rad,c+2));
        else if(c[0]=='3') printf("%d\n",nr_prefix(rad,c+2));
        fgets(c,Nmx,stdin);
    }
}

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