Cod sursa(job #2144826)

Utilizator dorin31Geman Dorin Andrei dorin31 Data 26 februarie 2018 22:36:25
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <cstring>
#define maxAlpha 26
#define maxLength 23
#define currentChar (*s - 'a')

using namespace std;

struct Trie {
	int sons, words;
	Trie *son[maxAlpha];

	Trie() {
		sons = words = 0;
		memset(son, 0, sizeof(son));
	}
};
Trie *T = new Trie;

void trieInsert(Trie *node, char *s) {
	if (*s == 0) {
		node->words++;
		return;
	}
	if (node->son[currentChar] == 0) {
		node->son[currentChar] = new Trie;
		node->sons++;
	}
	trieInsert(node->son[currentChar], s+1);
}

bool trieDelete(Trie *node, char *s) {
	if (*s == 0)
		node->words--;
	else if (trieDelete(node->son[currentChar],s+1) == true) {
		node->son[currentChar] = 0;
		node->sons--;
	}
	if (node->words == 0 && node->sons == 0 && node != T) {
		delete node;
		return true;
	}
	return false;
}

int trieWordCount(Trie *node, char *s) {
	if (*s == 0)
		return node->words;
	if (node->son[currentChar] != 0)
		return trieWordCount(node->son[currentChar], s+1);
	return 0;
}

int trieWordPrefix(Trie *node, char *s, int k) {
	if (*s == 0 || node->son[currentChar] == 0)
		return k;
	return(trieWordPrefix(node->son[currentChar], s+1, k+1));
}

int main() {
	fstream fin("trie.in");
	ofstream fout("trie.out");

	char line[maxLength];

	while(fin.getline(line, maxLength)) {
		switch(line[0]) {
			case '0':
				trieInsert(T, line+2);
				break;
			case '1':
				trieDelete(T, line+2);
				break;
			case '2':
				fout << trieWordCount(T, line+2) << '\n';
				break;
			case '3':
				fout<< trieWordPrefix(T, line+2, 0) << '\n';
				break;
			default:
				break;
		}
	}

	fin.close();
	fout.close();

	return 0;
}