Cod sursa(job #2696053)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 15 ianuarie 2021 10:01:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include<cstdio>
#include<cstring>
#define C (*s - 'a')
using namespace std;
struct T
{
	int c,n;
	T *f[26];
	T()
	{
		c=n=0;
		memset(f,0,sizeof(f));
	}
};
T *t=new T;
char l[36];
void I(T *o,char *s)
{
	if(*s=='\n')
    {
		o->c++;
        return;
	}
	if(o->f[C]==0)
    {
		o->f[C]=new T;
		o->n++;
	}
	I(o->f[C],s+1);
}
int D(T *o,char *s)
{
	if(*s=='\n')
		o->c--;
	else if(D(o->f[C],s+1))
    {
        o->f[C]=0;
        o->n--;
    }
	if(o->c==0&&o->n==0&&o!=t)
	{
		delete o;
        return 1;
	}
	return 0;
}
int Q(T *o,char *s)
{
	if(*s=='\n')
        return o->c;
	if(o->f[C])
		return Q(o->f[C],s+1);
	return 0;
}
int P(T *o,char *s,int k)
{
	if(*s=='\n'||o->f[C]==0)
		return k;
	return P(o->f[C],s+1,k+1);
}
int main()
{
	freopen("trie.in","r",stdin),freopen("trie.out","w",stdout),fgets(l,32,stdin);
	while(!feof(stdin))
    {
        if(l[0]=='0')
            I(t,l+2);
        else if(l[0]=='1')
            D(t,l+2);
        else if(l[0]=='2')
            printf("%d\n",Q(t,l+2));
        else if(l[0]=='3')
            printf("%d\n",P(t,l+2,0));
		fgets(l,32,stdin);
	}
	return 0;
}