Cod sursa(job #2739089)

Utilizator FrostfireMagirescu Tudor Frostfire Data 6 aprilie 2021 20:00:41
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int type;
char s[25];

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

Trie *T = new Trie;

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

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

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

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

int main()
{
	while(fin >> type >> s)
		{	if(!type)
				ins(s, T);
			else if(type == 1)
				del(s, T);
			else if(type == 2)
				fout << nrap(s, T) << '\n';
			else
				fout << bestPref(s, T, 0) << '\n';
		}
	return 0;
}