Cod sursa(job #3356641)

Utilizator lefterache_stefanLefterache Stefan lefterache_stefan Data 2 iunie 2026 21:52:20
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.29 kb
#include <fstream>
#include <string>
using namespace std;

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

struct Nod {
	int cnt;
	int desc;
	Nod* children[26];

	Nod() {
		cnt = 0;
		desc = 0;
		for (int i = 0; i < 26; i++) {
			children[i] = nullptr;
		}
	}
};

class Trie {
	Nod* root;
	void free_my_ram_pls(Nod* nod) {
		if (!nod) {
			return;
		}
		for (int i = 0; i < 26; i++) {
			if (nod->children[i] != nullptr) {
				free_my_ram_pls(nod->children[i]);
			}
		}
		delete nod;
	}

   public:
	Trie() { root = new Nod(); }
	~Trie() { free_my_ram_pls(root); }

	void insert(const string& cuvant) {
		Nod* curent = root;
		for (const auto& c : cuvant) {
			const int caracter = c - 'a';
			if (curent->children[caracter] == nullptr) {
				curent->children[caracter] = new Nod();
			}
			curent = curent->children[caracter];
			curent->desc++;
		}
		curent->cnt++;
	}

	void erase(const string& cuvant) {
		Nod* curent = root;
		Nod* parinti[25];

		for (int i = 0; i < cuvant.length(); i++) {
			parinti[i] = curent;
			curent = curent->children[cuvant[i] - 'a'];
		}
		curent->cnt--;

		for (int i = cuvant.length() - 1; i >= 0; i++) {
			Nod* nod = parinti[i]->children[cuvant[i] - 'a'];
			nod->desc--;

			if (nod->desc == 0 && nod->cnt == 0) {
				delete nod;
				parinti[i]->children[cuvant[i] - 'a'] = nullptr;
			}
		}
	}

	[[nodiscard]] int count(const string& cuvant) {
		Nod* curent = root;
		for (const auto& c : cuvant) {
			const int caracter = c - 'a';
			if (curent->children[caracter] == nullptr) {
				return 0;
			}
			curent = curent->children[caracter];
		}
		return curent->cnt;
	}

	[[nodiscard]] int longest_prefix(const string& cuvant) {
		int lungime = 0;
		Nod* curent = root;
		for (auto& c : cuvant) {
			const int caracter = c - 'a';
			if (curent->children[caracter] == nullptr) {
				break;
			}
			curent = curent->children[caracter];
			lungime++;
		}
		return lungime;
	}
};

int main() {
	Trie arbore_prefixe;
	string cuvant;
	int tip_operatie;
	while (fin >> tip_operatie >> cuvant) {
		if (tip_operatie == 0) {
			arbore_prefixe.insert(cuvant);
		} else if (tip_operatie == 1) {
			arbore_prefixe.erase(cuvant);
		} else if (tip_operatie == 2) {
			fout << arbore_prefixe.count(cuvant) << '\n';
		} else if (tip_operatie == 3) {
			fout << arbore_prefixe.longest_prefix(cuvant) << '\n';
		}
	}
}