Cod sursa(job #3234188)

Utilizator AndreasBossGamerBaragau Andreas AndreasBossGamer Data 6 iunie 2024 21:46:03
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 kb
#include <fstream>

using namespace std;

ifstream cin("trie.in");
ofstream cout("trie.out");

struct trieNode
{
	trieNode* v[26];
	int wordCount;

	trieNode()
	{
		wordCount = 0;
		for (int i = 0; i < 26; i++)
			v[i] = NULL;
	}
};

void insert(trieNode* root, string cuv)
{
	trieNode* current = root;

	for (char litera : cuv)
	{
		if (current->v[litera - 'a'] == NULL)
		{
			trieNode* newNode = new trieNode();
			current->v[litera - 'a'] = newNode;
		}
		current = current->v[litera - 'a'];
	}
	current->wordCount++;
}

int search(trieNode* root, string cuv)
{
	trieNode* current = root;
	for (char litera : cuv)
	{
		
		if (current->v[litera - 'a'] == NULL)
			return 0;

		current = current->v[litera - 'a'];
	}

	return current->wordCount;
}

void sterge(trieNode* root, string cuv)
{
	trieNode* current = root;
	trieNode* lca = NULL;
	char lcaChar = 'a';

	for (char litera : cuv)
	{
		if (current->v[litera - 'a'] == NULL)
			return;
		else
		{
			int count = 0;
			for (int i = 0; i < 26; i++)
			{
				if (current->v[i] != NULL)
					count++;
			}

			if (count > 1)
			{
				lca = current;
				lcaChar = litera;
			}
			current = current->v[litera - 'a'];
		}
	}
	
	int count = 0;
	for (int i = 0; i < 26; i++)
	{
		if (current->v[i] != NULL)
			count++;
	}

	if (count > 0)
		current->wordCount--;
	else if (lca != NULL)
		lca->v[lcaChar - 'a'] = NULL;
	else
		root->v[cuv[0] - 'a'] = NULL;

	//cout << cuv[0] << " ";
}

int longestPrefix(trieNode* root, string cuv)
{
	trieNode* current = root;
	int lMax = 0;

	for (char litera : cuv)
	{
		if (current->v[litera - 'a'] == NULL)
			return lMax;

		current = current->v[litera - 'a'];
		lMax++;
	}
	return lMax;
}

int main()
{
	trieNode* root = new trieNode();
	int n;
	string cuvant;
	while (cin >> n >> cuvant)
	{
		if (n == 0)
			insert(root, cuvant);
		else if (n == 1)
			sterge(root, cuvant);
		else if (n == 2)
			cout << search(root, cuvant) << '\n';
		else
			cout << longestPrefix(root, cuvant) << '\n';
	}
}