Cod sursa(job #1095889)

Utilizator dunhillLotus Plant dunhill Data 1 februarie 2014 09:00:00
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <cstring>
using namespace std;

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

int n, op;
char a[21];

struct nod {
	int letters;
	int words;
	nod *next[26];
};
nod *R;

void init(nod *&R) {
	R = new nod;
	R->letters = 0;
	R->words = 0;
	memset(R->next, 0, sizeof(R->next));
}

void insert(nod *R, int n, char a[]) {
	for (int i = 1; i <= n; ++i) {
		if (R->next[a[i] - 'a'] == NULL) 
			init(R->next[a[i] - 'a']);
		R = R->next[a[i] - 'a'];
		++R->letters;
	}
	++R->words;
}

void erase(nod *&R, int i) {
	if (i == n + 1) {
		--R->letters;
		--R->words;
		if (!R->letters) {
			delete R;
			R = NULL;
		}
		return;
	}
	else {
		erase(R->next[a[i] - 'a'], i + 1);
		--R->letters;
		if (!R->letters) {
			delete R;
			R = NULL;
		}
	}
}

int CountWords(nod *R, int n, char a[]) {
	for (int i = 1; i <= n; ++i) {
		if (R->next[a[i] - 'a'] == NULL) return 0;
		R = R->next[a[i] - 'a'];
	}
	return R->words;
}

int prefix(nod *R, int n, char a[]) {
	for (int i = 1; i <= n; ++i) {
		if (R->next[a[i] - 'a'] == 0) return (i - 1);
		R = R->next[a[i] - 'a'];
	}
	return n;
}

int main() {
	init(R);
	while (fin >> op) {
		fin >> (a + 1);
		n = strlen(a + 1);
		if (op == 0) 
			insert(R, n, a);
		if (op == 1) 
			erase(R, 1);
		if (op == 2)
			fout << CountWords(R, n, a) << '\n';
		if (op == 3) 
			fout << prefix(R, n, a) << '\n';
	}
	return 0;
}