Cod sursa(job #2313907)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 7 ianuarie 2019 16:57:28
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include<fstream>
#include<cstring>
using namespace std;
struct T
{
	char c;
	int n,p,s,b;
}t[5200026];
char w[25];
int z,o;
void A()
{
	int root = 0, br = 0;
	int leng = strlen (w);
	for (int p = 1; p < leng; ++ p)
	{
		bool find = false;
		for (int nod = t[root].s; nod; nod = t[nod].b)
			if (t[nod].c == w[p])
			{
				t[nod].p++;
				if (p == leng - 1)
				{
					t[nod].n++;
					return;
				}
				root = nod;
				find = true;
				break;
			}
			else br = nod;
		if (find) continue;
		t[++z].c = w[p];
		if (p == leng - 1) t[z].n = t[z].p = 1;
		else t[z].n = 0, t[z].p = 1;
		if (! t[root].s) t[root].s = z;
		else t[br].b = z;
		root = 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()
{
	ifstream f("trie.in");
	ofstream g("trie.out");
	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';
	}
}