Cod sursa(job #3229015)

Utilizator dariustgameTimar Darius dariustgame Data 12 mai 2024 22:34:42
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <fstream>

using namespace std;

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

struct nod
{
	nod* nextNode[27] = { NULL };
	int nrConnections = 0;
	int nrWordEnd = 0;
};

nod rad;
int op;
string cuv;

void add(string word)
{
	nod* p = &rad;
	for (int i = 0; i < word.size() && p != NULL; i++)
	{
		nod* p2 = p->nextNode[word[i] - 'a'];
		if (p2 == NULL)
		{
			nod* leg = new nod;
			p->nextNode[word[i] - 'a'] = leg;
			p->nrConnections++;
		}
		p = p->nextNode[word[i] - 'a'];
	}
	if (p != NULL) p->nrWordEnd++;
}

void del(nod* p, string word, int i)
{
	if (i < word.size() - 1)
	{
		del(p->nextNode[word[i] - 'a'], word, i + 1);
		nod* p2 = p->nextNode[word[i] - 'a'];
		if (p2->nrWordEnd == 0 && p2->nrConnections == 0)
		{
			p->nrConnections--;
			delete p->nextNode[word[i] - 'a'];
			p->nextNode[word[i] - 'a'] = NULL;
		}
	}
	else
	{
		nod* p2 = p->nextNode[word[i] - 'a'];
		p2->nrWordEnd--;
		if (p2->nrWordEnd == 0 && p2->nrConnections == 0)
		{
			p->nrConnections--;
			delete p->nextNode[word[i] - 'a'];
			p->nextNode[word[i] - 'a'] = NULL;
		}
	}
}

int count(string word)
{
	nod* p = &rad;
	for (int i = 0; i < word.size() && p != NULL; i++)
	{
		nod* p2 = p->nextNode[word[i] - 'a'];
		if (p2 == NULL)
		{
			return 0;
		}
		p = p->nextNode[word[i] - 'a'];
	}
	if (p != NULL) return p->nrWordEnd;
	return 0;
}

int longestPrefix(string word)
{
	int cnt = 0;
	nod* p = &rad;
	for (int i = 0; i < word.size() && p != NULL; i++)
	{
		nod* p2 = p->nextNode[word[i] - 'a'];
		if (p2 == NULL)
		{
			return cnt;
		}
		cnt++;
		p = p->nextNode[word[i] - 'a'];
	}
	return cnt;
}

int main()
{
	while (fin >> op >> cuv)
	{
		if (op == 0)
		{
			add(cuv);
		}
		else if (op == 1)
		{
			if (count(cuv) > 0)
			{
				del(&rad, cuv, 0);
			}
		}
		else if (op == 2)
		{
			fout << count(cuv) << '\n';
		}
		else
		{
			fout << longestPrefix(cuv) << '\n';
		}
	}
}