Cod sursa(job #1696358)

Utilizator DragosDADDorneanu Dragos - Andrei DragosDAD Data 28 aprilie 2016 22:34:02
Problema Trie Scor 25
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <iostream>
#include <fstream>
#define CH (*s - 'a')

using namespace std;

struct NodeTrie
{
	unsigned int count = 0, noKids = 0;
	NodeTrie *children[26];
};

NodeTrie *trie = new NodeTrie;

void insert(NodeTrie *root, char *s)
{
	if (*s == '\0') {
		++root->count;
	}
	else
	{
		if (root->children[CH] == NULL)
		{
			root->children[CH] = new NodeTrie;
			NodeTrie *init = root->children[CH];
			for (unsigned int i = 0; i <= 26; ++i) {
				init->children[i] = NULL;
			}
			++root->noKids;
		}
		insert(root->children[CH], s + 1);
	}
}

unsigned int getWordCount(NodeTrie *root, char *s)
{
	if (*s == '\0') {
		return root->count;
	}
	if (root->children[CH] != NULL) {
		return getWordCount(root->children[CH], s + 1);
	}
	return 0;
}

bool erase(NodeTrie *root, char *s)
{
	if (*s == '\0') {
		--root->count;
	}
	else
	{
		if (erase(root->children[CH], s + 1) == true)
		{
			root->children[CH] = NULL;
			--root->noKids;
		}
	}
	if (root->count == 0 && root->noKids == 0 && root != trie)
	{
		root = NULL;
		delete root;
		return true;
	}
	return false;
}

unsigned int getGreatestPrefix(NodeTrie *root, char *s)
{
	if (*s == '\0' || root->children[CH] == NULL) {
		return 0;
	}
	return 1 + getGreatestPrefix(root->children[CH], s + 1);
}

int main()
{
	ifstream fin("trie.in");
	ofstream fout("trie.out");
	unsigned int i;
	for (i = 0; i <= 26; ++i) {
		trie->children[i] = NULL;
	}
	char op;
	char *s = new char;
	while (fin >> op >> s)
	{
		if (op == '0') {
			insert(trie, s);
		}
		else if (op == '1') 
		{
			if (getWordCount(trie, s)) {
				erase(trie, s);
			}
		}
		else if (op == '2') {
			fout << getWordCount(trie, s) << '\n';
		}
		else fout << getGreatestPrefix(trie, s) << '\n';
	}
	fin.close();
	fout.close();
	return 0;
}