Cod sursa(job #2788330)

Utilizator Rares31100Popa Rares Rares31100 Data 25 octombrie 2021 15:50:18
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <bits/stdc++.h>
using namespace std;

class Trie
{
private:
	int sizeAlf;
	int (*Hash)(char);

	struct nod
	{
		int apar = 0, term = 0;
		nod **alf;
	};
	nod *origin;

public:
	Trie(int sizeAlfabet, int (*HashFunction)(char))
	{
		sizeAlf = sizeAlfabet;
		Hash = HashFunction;

		origin = new nod();
		origin->alf = new nod*[sizeAlf]();
	}
	void inserare(string sir)
	{
		nod* poz = origin;

		for (auto lit : sir)
		{
			int nr = Hash(lit);
			if (poz->alf[nr] == NULL)
			{
				nod* newRam = new nod();
				newRam->alf = new nod * [sizeAlf]();
				poz->alf[nr] = newRam;
			}

			poz = poz->alf[nr];
			poz->apar++;
		}

		poz->term++;
	}
	void stergere(string sir)
	{
		if (!aparitii(sir))
			return;

		stack <nod*> s;
		nod* poz = origin;

		for (auto lit : sir)
		{
			s.push(poz);
			poz = poz->alf[Hash(lit)];
		}

		s.top()->alf[Hash(sir[sir.size() - 1])]->term--;

		for(int i = sir.size() - 1; i >= 0; i--)
		{
			nod* curent = s.top();
			nod* urm = curent->alf[Hash(sir[i])];
			s.pop();
			urm->apar--;

			if (urm->apar == 0)
			{
				delete urm;
				curent->alf[Hash(sir[i])] = NULL;
			}
		}
	}
	int aparitii(string sir)
	{
		nod* poz = origin;

		for (auto lit : sir)
			if (poz->alf[Hash(lit)] == NULL)
				return 0;
			else
				poz = poz->alf[Hash(lit)];

		return poz->term;
	}
	int prefix(string sir)
	{
		int lung = 0;
		nod* poz = origin;

		for (auto lit : sir)
			if (poz->alf[Hash(lit)] == NULL)
				return lung;
			else
			{
				lung++;
				poz = poz->alf[Hash(lit)];
			}

		return lung;
	}
};

int Hash(char litera)
{
	return litera - 'a';
}

ifstream fin("trie.in");
ofstream fout("trie.out");
int c;
string sir;

int main()
{
	Trie trie(26, Hash);
	
	while (fin >> c)
	{
		fin >> sir;

		switch (c)
		{
		case 0: trie.inserare(sir); break;
		case 1: trie.stergere(sir); break;
		case 2: fout << trie.aparitii(sir) << '\n'; break;
		case 3: fout << trie.prefix(sir) << '\n'; break;
		}
	}

	return 0;
}