Cod sursa(job #2391433)

Utilizator alex2209alexPavel Alexandru alex2209alex Data 28 martie 2019 20:47:23
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include<cstdio>
#include<cstring>
const int Q=6000000;
struct T
{
	char c;
	int n,p,s,b;
}t[5200026];
char w[25],r[Q],v[25];
int z,o,e=-1,u,l,k;
int B()
{
  	int s=0;
  	for(e++;r[e]>='0'&&r[e]<='9';e++)
  		s=s*10+r[e]-'0';
  	return s;
}
void S(int x)
{
    int i,d=x>99999?6:x>9999?5:x>999?4:x>99?3:x>9?2:1;
    for(i=d-1;i>=0;x/=10,i--)
        r[l+i]=x%10+48;
    r[l+d]=10,l+=d+1;
}
void A()
{
	int r=0,a=0,l=strlen(w),p,f,o;
	for(p=1;p<l;p++)
	{
		for(f=0,o=t[r].s;o&&!f;o=t[o].b)
			if(t[o].c==w[p])
			{
				t[o].p++;
				if(p==l-1)
				{
					t[o].n++;
					return;
				}
				r=o,f=1;
			}
			else
                a=o;
		if(f)
            continue;
		t[++z].c=w[p],t[z].p=1,t[z].n=(p==l-1?1:0),!t[r].s?t[r].s=z:t[a].b=z,r=z;
	}
}
void D()
{
	int q=0,l=strlen(w),i,o;
	for(i=1;i<l;i++)
		for(o=t[q].s;o;o=t[o].b)
			if(t[o].c==w[i])
			{
				t[o].p--;
				if(i==l-1)
                    t[o].n --;
				q=o;
				break;
			}
}
int C()
{
	int q=0,l=strlen(w),o=1,i,e;
	for(i=1;i<l&&o;i++)
		for(o=0,e=t[q].s;e&&!o;e=t[e].b)
			if(t[e].c==w[i]&&t[e].p)
			{
				if(i==l-1)
                    return t[e].n;
				q=e,o=1;
			}
	return 0;
}
int M()
{
	int i,q,r=0,l=strlen(w),e=0,o=1;
	for(i=1;i<l&&o;i++)
		for(o=0,q=t[e].s;q&&!o;q=t[q].b)
			if(t[q].c==w[i]&&t[q].p)
				r++,e=q,o=1;
	return r;
}
int main()
{
	freopen("trie.in","r",stdin),freopen("trie.out","w",stdout),fread(r,1,Q,stdin);
	while(1)
    {
        for(o=B(),u=0;(r[e]>='a'&&r[e]<='z')||r[e]==' ';e++)
            w[u++]=r[e];
        if(!u)
            break;
        w[u++]='\0';
        if(!o)
            A();
		else if(o==1)
            D();
		else if(o==2)
            S(C());
		else
            S(M());
    }
	fwrite(r,1,l,stdout);
}