Cod sursa(job #2313637)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 7 ianuarie 2019 11:37:44
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cstring>
#include <string>

using namespace std;

#define maxN 200005 * 26
#define maxLeng 25

struct TRIE
{
	char car;
	int NrW, Pref;
	int son, bro;
} Trie[maxN];

char word[maxLeng];
int DIM;


void Add ()
{
	int root = 0, br = 0;
	int leng = strlen (word);

	for (int p = 1; p < leng; ++ p)
	{
		bool find = false;

		for (int nod = Trie[root].son; nod; nod = Trie[nod].bro)
			if (Trie[nod].car == word[p])
			{
				Trie[nod].Pref ++;
				if (p == leng - 1)
				{
					Trie[nod].NrW ++;
					return;
				}

				root = nod;
				find = true;

				break;
			}
			else br = nod;

		if (find) continue;

		Trie[++ DIM].car = word[p];

		if (p == leng - 1) Trie[DIM].NrW = Trie[DIM].Pref = 1;
		else Trie[DIM].NrW = 0, Trie[DIM].Pref = 1;
		if (! Trie[root].son) Trie[root].son = DIM;
		else Trie[br].bro = DIM;

		root = DIM;
	}
}


void Delete ()
{
	int root = 0, leng = strlen (word);

	for (int i = 1; i < leng; ++ i)
		for (int nod = Trie[root].son; nod; nod = Trie[nod].bro)
			if (Trie[nod].car == word[i])
			{
				Trie[nod].Pref --;
				if (i == leng - 1) Trie[nod].NrW --;
				root = nod;

				break;
			}
}


int Count_Word ()
{
	int root = 0, leng = strlen (word);
	bool ok = true;

	for (int i = 1; i < leng && ok; ++ i)
	{
		ok = false;

		for (int nod = Trie[root].son; nod; nod = Trie[nod].bro)
			if (Trie[nod].car == word[i] && Trie[nod].Pref)
			{
				if (i == leng - 1) return Trie[nod].NrW;
				root = nod;
				ok = true;

				break;
			}
	}

	return 0;
}


int Max_Prefix ()
{
	int res = 0, leng = strlen (word), root = 0;
	bool ok = true;

	for (int i = 1; i < leng && ok; ++ i)
	{
		ok = false;

		for (int nod = Trie[root].son; nod; nod = Trie[nod].bro)
			if (Trie[nod].car == word[i] && Trie[nod].Pref)
			{
				res ++;
				root = nod, ok = true;

				break;
			}
	}

	return res;
}


int main()
{
	ifstream f ("trie.in");
	ofstream g ("trie.out");

	int cod;

	while (f >> cod)
	{
		f.getline (word, maxLeng);

		if (! cod) Add ();
		if (cod == 1) Delete ();
		if (cod == 2) g << Count_Word () << '\n';
		if (cod == 3) g << Max_Prefix () << '\n';
	}

	return 0;
}