Cod sursa(job #3239403)

Utilizator alextmAlexandru Toma alextm Data 5 august 2024 14:20:17
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <bits/stdc++.h>
using namespace std;

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

class Trie {
private:
	struct Node {
		int lvs{};
		int cnt{};
		Node* links[26] = {nullptr};
	};

	Node* root;

	bool eraseHelper(Node* node, const string& word, int depth) {
		if(!node) {
			return false;
		}

		if(depth == word.length()) {
			if(node->cnt == 0) {
				return false;
			}

			node->cnt--;
			node->lvs--;

			return node->lvs == 0;
		}

		char letter = word[depth];
		Node* childNode = node->links[letter - 'a'];
		if(!childNode) {
			return false;
		}

		bool shouldBeDeleted = eraseHelper(childNode, word, depth + 1);

		if(shouldBeDeleted) {
			delete node->links[letter - 'a'];
			node->links[letter - 'a'] = nullptr;
		}

		node->lvs--;
		return node->lvs == 0 && node->cnt == 0;
 	}

public:
	Trie() {
		root = new Node();
		root->lvs = 0;
		root->cnt = 0;
	}

	void insert(const string& word) {
		Node* current = root;
		for(auto letter : word) {
			if(!current->links[letter - 'a']) {
				current->links[letter - 'a'] = new Node();
			}
			current = current->links[letter - 'a'];
			current->lvs++;
		}
		current->cnt++;
	}

	int nrOccurrences(const string& word) {
		Node* current = root;
		for(auto letter : word) {
			if(!current->links[letter - 'a']) {
				return 0;
			}
			current = current->links[letter - 'a'];
		}
		return current->cnt;
	}

	int longestCommonPrefix(const string& word) {
		Node* current = root;
		int prefLength = 0;
		for(auto letter : word) {
			if(!current->links[letter - 'a']) {
				break;
			}
			current = current->links[letter - 'a'];
			prefLength++;
		}
		return prefLength;
	}

	bool erase(const string& word) {
		return eraseHelper(root, word, 0);
	}
};

int main() {
	Trie trie;

	int operation;
	string word;

	while(fin >> operation >> word) {
		if(operation == 0) {
			trie.insert(word);
		} else if(operation == 1) {
			trie.erase(word);
		} else if(operation == 2) {
			fout << trie.nrOccurrences(word) << '\n';
		} else {
			fout << trie.longestCommonPrefix(word) << '\n';
		}
	}

	return 0;
}