Cod sursa(job #1065526)

Utilizator danny794Dan Danaila danny794 Data 23 decembrie 2013 14:10:33
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <cstdio>
#include <string>

using namespace std;

#define MAXN 26

typedef struct trie {
	int words, prefix;
	trie *child[MAXN];
} trie;

trie *t;

void read() {
	freopen( "trie.in", "r", stdin );
	freopen( "trie.out", "w", stdout );
	t = new trie;
}

void add(char *s, trie *tree) {
	if (s[0] == '\n' || s[0] == '\0') {
		tree -> words++;
	} else {
		int index = s[0] - 'a';
		if(!tree -> child[index]) {
			tree -> child[index] = new trie;
		}
		tree -> prefix++;
		add(s + 1, tree -> child[index]);
	}
}

trie* remove(char *s, trie *tree) {
	if (s[0] == '\n' || s[0] == '\0') {
		tree -> words--;
		if (tree -> words == 0)
			return 0;
	} else {
		int index = s[0] - 'a';
		tree -> prefix--;
		tree -> child[index] = remove(s + 1, tree -> child[index]);
	}

	return tree;
}

int search_words(char *s, trie *tree) {
	if (s[0] == '\n' || s[0] == '\0') {
		return tree -> words;
	} else {
		int index = s[0] - 'a';
		if (!tree -> child[index])
			return 0;
		else
			return search_words(s + 1, tree -> child[index]);
	}
}

int search_prefixes(char *s, trie *tree) {
	if (s[0] == '\n' || s[0] == '\0') {
		return 0;
	} else {
		int index = s[0] - 'a';
		if (!tree -> child[index])
			return 0;
		else
			return 1 + search_prefixes(s + 1, tree -> child[index]);
	}
}

void print(trie *p) {
	printf("words: %d, prefix: %d\n", p -> words, p -> prefix);
	for(int i = 0; i < MAXN; i++)
		if(p -> child[i]) {
			printf("%c ", (char)(i + 'a'));
			print(p -> child[i]);
		}
}

void solve() {
	char s[26];
	fgets(s, 26, stdin);
	while(!feof(stdin)) {
		switch(s[0]){
			case '0': add(s + 2, t); break;
			case '1': t = remove(s + 2, t); break;
			case '2': printf("%d\n", search_words(s + 2, t)); break;
			case '3': printf("%d\n", search_prefixes(s + 2, t)); break;
		}
		fgets(s, 26, stdin);
	}
}

int main() {
	read();
	solve();
	return 0;
}