Cod sursa(job #2144842)

Utilizator dorin31Geman Dorin Andrei dorin31 Data 26 februarie 2018 22:49:03
Problema Trie Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 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() {
	ifstream fin("trie.in");
	ofstream fout("trie.out");

	char line[maxLength];

	while(fin.getline(line, maxLength)) {
		if (line[0] == '0')
			trieInsert(T, line+2);
		else if (line[0] == '1')
			trieDelete(T, line+2);
		else if (line[0] == '2')
			fout << trieWordCount(T, line+2) << '\n';
		else if (line[0] == '3')
			fout << trieWordPrefix(T, line+2, 0) << '\n';
		line[0] = '\0';
	}

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

	return 0;
}