Cod sursa(job #2382199)

Utilizator vlad_popaVlad Popa vlad_popa Data 17 martie 2019 20:45:22
Problema Trie Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <iostream>
#include <fstream>
#include <string>
#include <vector>


typedef struct _Trie 
{
	std::vector<_Trie *> son;
	int nrSons;
	int val;
	
	_Trie() : son(std::vector<_Trie*>(26, nullptr)),
			nrSons(0), 
			val(0)
	{	
	}
} Trie;


void insertTrie(Trie *node, const char *s)
{	
	if (*s - 'a' < 0 || *s - 'a' > 26) {
		node->val++;
	} else {
		if (node->son[*s - 'a'] == nullptr) {
			node->son[*s - 'a'] = new Trie();
			node->nrSons++;
		}
		
		insertTrie(node->son[*s - 'a'], s+1);
	}
}

bool deleteTrie(Trie *&node, const char *s)
{	
	if (*s - 'a' < 0 || *s - 'a' > 26) {
		node->val --;
		if (node->nrSons == 0 && node->val <= 0) {
			delete node;
			node = nullptr;
			return true;
		}
	} else {
		if (node->son[*s - 'a']) {
			if (deleteTrie(node->son[*s - 'a'], s+1)) {
				node->nrSons--;
				if (node->nrSons == 0 && node->val <= 0) {
					delete node;
					node = nullptr;
					return true;
				}
			}
		}
	}
	
	return false;
}

int nrOfWordsInTrie(Trie *node, const char *s) 
{
	if (*s - 'a' < 0 || *s - 'a' > 26) {
		return node->val;
	} else {
		if (node->son[*s - 'a']) {
			return nrOfWordsInTrie(node->son[*s - 'a'], s+1);
		} else {
			return 0;
		}
	}
	
	return 0;
}

int longestPrefix(Trie *node, const char *s, int length)
{
	if (*s - 'a' < 0 || *s - 'a' > 26) {
		return length;
	} else {
		if (node->son[*s - 'a']) {
			return longestPrefix(node->son[*s - 'a'], s+1, length+1);
		} else {
			return length;
		}
	}
}

int main ()
{
	std::ifstream input;
	input.open("trie.in");
	
	std::ofstream output("trie.out");
	
	Trie *root = new Trie();
	
	std::string line;
	while (getline (input,line)) {
		switch (line[0]) {
			case '0':
				insertTrie(root, (line.c_str()+2));
				break;
			case '1':
				deleteTrie(root, (line.c_str()+2));
				break;
			case '2':
				output << nrOfWordsInTrie(root, (line.c_str()+2)) << "\n";
				break;
			case '3':
				output << longestPrefix(root, (line.c_str()+2), 0) << "\n";
				break;
			default:
			// should not be the case: DO NOTHING
				break;
		}
    }
		
	input.close();
	output.close();
	
	return 0;
}