Cod sursa(job #1948663)

Utilizator SolcanMihaiSolcan Mihai Andrei SolcanMihai Data 1 aprilie 2017 12:21:45
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;

const int N = 100;

class Nod{
public:
	int nr;
	Nod* vecini[230];

	Nod()
	{
		nr = 0;
		for(int i = 0; i < 230; i++)
		{
			vecini[i] = NULL;
		}
	}
};

int operatie;
char cuvant[N];
int lungimeCuvant;
Nod* root;

void insertNode(Nod*& x, int y)
{
	if(x->vecini[cuvant[y]] == NULL)
	{
		x->vecini[cuvant[y]] = new Nod();
	}

	if(y == lungimeCuvant - 1)
	{
		x->vecini[cuvant[y]]->nr++;
	}
	else
	{
		insertNode(x->vecini[cuvant[y]], y + 1);
	}
}

bool isLeaf(Nod* x)
{
	for(int i = 0; i < 230; i++)
	{
		if(x->vecini[i] != NULL)
		{
			return false;
		}
	}

	return true;
}

void deleteNode(Nod*& x, int y)
{
	if(y == lungimeCuvant - 1)
	{
		x->vecini[cuvant[y]]->nr--;
		
		//if(isLeaf(x->vecini[cuvant[y]]) == true)
		//{
		//	delete x->vecini[cuvant[y]];
		//	x->vecini[cuvant[y]] = NULL;
		//}
	}
	else
	{
		deleteNode(x->vecini[cuvant[y]], y + 1);
		
		if(isLeaf(x->vecini[cuvant[y]]) == true && x->vecini[cuvant[y]]->nr == 0)
		{
			delete x->vecini[cuvant[y]];
			x->vecini[cuvant[y]] = NULL;
		}
	}
}

int numberOfAparitions(Nod*& x, int y)
{
	if(x->vecini[cuvant[y]] == NULL)
	{
		return 0;
	}
	else
	{
		if(y == lungimeCuvant - 1)
		{
			return x->vecini[cuvant[y]]->nr;
		}
		else
		{
			return numberOfAparitions(x->vecini[cuvant[y]], y + 1);
		}
	}
}

int lungimePrefix(Nod*& x, int y)
{
	if(y == lungimeCuvant)
	{
		return y;
	}
		
	if(x->vecini[cuvant[y]] == NULL)
	{
		return y;
	}
	else
	{
		return lungimePrefix(x->vecini[cuvant[y]], y + 1);
	}
}

void citire()
{
	char tmp[100];
	tmp[0] = tmp[1] = 0;

	fgets(tmp, 100, stdin);

	if(tmp[1] == 0)
	{
		operatie = -1;
		return;
	}

	char *p = strtok(tmp, ", \n");
	sscanf(p, "%d", &operatie);

	p = strtok(NULL, ", \n");
	strcpy(cuvant, p);

	lungimeCuvant = strlen(cuvant);

	for(int i = 0; i < lungimeCuvant; i++)
	{
		cuvant[i] -= 'a';
	}
}

int main()
{
	freopen("trie.in", "r", stdin);
	freopen("trie.out", "w", stdout);

	root = new Nod();

	while(!feof(stdin))
	{
		citire();

		if(cuvant[0] == 0)
		{
			return 0;
		}

		if(operatie == 0)
		{
			insertNode(root, 0);
		}
		else if(operatie == 1)
		{
			deleteNode(root, 0);
		}
		else if(operatie == 2)
		{
			printf("%d\n", numberOfAparitions(root, 0));
		}
		else if(operatie == 3)
		{
			printf("%d\n", lungimePrefix(root, 0));
		}
	}

	return 0;
}