Cod sursa(job #2744305)

Utilizator FrostfireMagirescu Tudor Frostfire Data 24 aprilie 2021 12:59:14
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

int t;
char s[25];

struct Trie
{	int nrfii, cnt;
	Trie *fii[26];
	Trie()
		{	nrfii = cnt = 0;
			for(int i=0; i<26; i++)
				fii[i] = 0;
		}		
};

Trie *T = new Trie;

void adaug(char *s, Trie *nod)
{	if(!(*s))
		{	nod->cnt++;
			return;
		}
	int ch = *s - 'a';
	if(!nod->fii[ch])
		{	nod->fii[ch] = new Trie;
			nod->nrfii++;
		}
	adaug(s + 1, nod->fii[ch]);
}

int sterg(char *s, Trie *nod)
{	int ch = *s - 'a';
	if(!(*s))
		nod->cnt--;
	else if(sterg(s + 1, nod->fii[ch]))
		{	nod->nrfii--;
			nod->fii[ch] = 0;
		}
	if(!nod->nrfii && !nod->cnt && nod != T)
		{	delete nod;
			return 1;
		}
	return 0;
}

int cntap(char *s, Trie *nod)
{	if(!(*s))
		return nod->cnt;
	int ch = *s - 'a';
	return cntap(s + 1, nod->fii[ch]);
}

int cmlpc(char *s, Trie *nod, int len)
{	int ch = *s - 'a';
	if(!(*s) || !nod->fii[ch])
		return len;
	return cmlpc(s + 1, nod->fii[ch], len + 1);
}

int main()
{
	while(fin >> t >> s)
		{	if(!t)
				adaug(s, T);
			else if(t == 1)
				sterg(s, T);
			else if(t == 2)
				fout << cntap(s, T) << '\n';
			else
				fout << cmlpc(s, T, 0) << '\n';
		}
	return 0;
}