Cod sursa(job #3149002)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 5 septembrie 2023 17:46:50
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include<fstream>
#include<cstring>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct T
{
	char c;
	int n,p,s,b;
}t[5200026];
char w[25];
int z,o;
void A()
{
	int r=0,b=0,p,l=strlen(w),o;
	bool f;
	for(p=1;p<l;++p) {
        f=0;
		for(f=0,o=t[r].s;o;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;
				break;
			} else
                b=o;
		if(f)
            continue;
		t[++z].c=w[p];
		if(p==l-1)
            t[z].n=t[z].p=1;
		else
            t[z].n=0,t[z].p=1;
		if(!t[r].s)
            t[r].s=z;
		else
            t[b].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()
{
	while(f>>o) {
		f.getline(w,25);
		if(!o)
            A();
		else if(o==1)
            D();
		else if(o==2)
            g<<C()<<'\n';
		else
            g<<M()<<'\n';
	}
	return 0;
}