Cod sursa(job #3148011)

Utilizator daristyleBejan Darius-Ramon daristyle Data 28 august 2023 21:26:51
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <fstream>

using namespace std;

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

const int SIGMA = 26;
const char OFFSET = 'a';

class Trie{
private:
		Trie* children[SIGMA];
		int cntWords = 0, cntFinalWords = 0;

		Trie* getEdge(char ch){
			return children[ch - OFFSET];
		}

		Trie* addEdge(char ch){
			Trie* edge = getEdge(ch);

			if(edge == nullptr)
				edge = children[ch - OFFSET] = new Trie;

			++edge->cntWords;

			return edge;
		}

		Trie* removeEdge(char ch){
			Trie* edge = getEdge(ch);

			--edge->cntWords;

			return edge;
		}

public:

		Trie(){
			for(int i = 0; i < SIGMA; ++i)
				children[i] = nullptr;
		}

		void insert(const char* word){
			int i = 0;
			Trie* current = this;

			++current->cntWords;

			while(word[i]){
				current = current->addEdge(word[i]);
				++i;
			}

			++current->cntFinalWords;
		}

		void erase(const char* word){
			int i = 0;
			Trie* current = this;

			while(word[i]){
				current = current->removeEdge(word[i]);
				++i;
			}

			--current->cntFinalWords;
		}

		int count(const char* word){
			int i = 0;
			Trie* current = this;

			while(word[i] && current != nullptr){
				current = current->getEdge(word[i]);
				++i;
			}

			if(current != nullptr)
				return current->cntFinalWords;
			return 0;
		}

		int longestPrefix(const char* word){
			int i = 0;
			Trie* current = this;

			while(word[i] && current != nullptr && current->cntWords > 0){
				current = current->getEdge(word[i]);
				++i;
			}

			if(current != nullptr && current->cntWords > 0)
				return i;
			return i - 1;
		}
};

const int STRLEN_MAX = 20;
int op;
char word[STRLEN_MAX + 1];
Trie trie;

int main(){

	while(fin >> op >> word)
		switch(op){
			case 0:{
				trie.insert(word);
				break;
			}
			case 1:{
				trie.erase(word);
				break;
			}
			case 2:{
				fout << trie.count(word) << '\n';
				break;
			}
			case 3:{
				fout << trie.longestPrefix(word) << '\n';
				break;
			}
		}

	fin.close();
	fout.close();
	return 0;
}