Cod sursa(job #1441237)

Utilizator nimicLeoveanu Mihaita Alexandru nimic Data 23 mai 2015 22:54:00
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include<cstdio>
using namespace std;
 
struct nod{
    nod *fii[26];
    int nrp, nrc;

    nod(){
        nrp = nrc = 0;
        for(int i = 0; i<26; i++)
            fii[i] = NULL;
    }
};
 
int p;
char c[26];
nod *r;
 
nod *add(nod *p,char *s){
    if (p==NULL)
		p = new nod;
    p-> nrp++;

    if (s[0]==0)
	{
        p-> nrc++;
        return p;
    }

    p-> fii[s[0] - 'a'] = add(p-> fii[s[0]-'a'], s + 1);
    return p;
}
 
nod *del(nod *p, char *s)
{
    if (s[0]==0)
	{
        p-> nrp--;
        p-> nrc--;

        if (p-> nrp==0)
		{
            delete p;
            return NULL;
        }

        return p;
    }

    p-> fii[s[0]-'a'] = del(p-> fii[s[0] - 'a'], s + 1);
    p-> nrp--;

    if (p-> nrp==0)
	{
        delete p;
        return NULL;
    }

    return p;
}
 
int nr_ap(nod *p,char *s)
{
    if (p==NULL)
		return 0;

    if (s[0]==0)
		return p-> nrc;

    return nr_ap(p-> fii[s[0]-'a'], s + 1);
}
 
int comun(nod *p, char *s)
{
    if (p==NULL)
		return -1;

    if (s[0]==0)
		return 0;

    return 1+comun(p-> fii[s[0]-'a'],s+1);
}
 
int main(){
	int player_unu=0;
    freopen ("trie.in","r",stdin);
    freopen ("trie.out","w",stdout);

    while(scanf("%d", &p)!=EOF)
	{
        scanf (" ");
        scanf ("%s", &c);
        scanf ("\n");

        if(p==0)
			r = add(r, c);
        if(p==1) 
			r = del(r, c);
        if(p==2) 
			printf("%d\n", nr_ap(r,c));
        if(p==3)
			printf("%d\n", comun(r,c));
    }

    return player_unu;
}