Cod sursa(job #2070660)

Utilizator Kzsolty96SAPIENTIA OSZTIAN DANIEL KUCSVAN Kzsolty96 Data 19 noiembrie 2017 19:55:20
Problema Trie Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>

using namespace std;

struct Trie {

	int nr = 0, n = 0;
	Trie *t[26];

	Trie() {
		for (int i = 0; i < 26; ++i) {
			t[i] = nullptr;
		}
	}

};

Trie *T = new Trie;

void add(Trie *root, const char *w) {
	if (w[0] == '\0') {
		++root->nr;
		return;
	}

	if (nullptr == root->t[w[0] - 'a']) {
		root->t[w[0] - 'a'] = new Trie;
		++root->n;
	}
	add(root->t[w[0] - 'a'], w + 1);
}

int del(Trie *root, const char *w) {
	if (w[0] == '\0') {
		--root->nr;
	} else
	if (del(root->t[w[0] - 'a'], w + 1)) {
		root->t[w[0] - 'a'] = nullptr;
		--root->n;
	}

	if (0 == root->n && 0 == root->nr && root != T) {
		delete root;
		return 1;
	}

	return 0;
}

int prefix(Trie *root, const char *w) {
	if (w[0] == '\0') {
		return 0;
	}
	if (nullptr == root->t[w[0] - 'a']) {
		return 0;
	}
	return 1 + prefix(root->t[w[0] - 'a'], w + 1);
}

int stat(Trie *root, const char *w) {
	if (w[0] == '\0') {
		return root->nr;
	}
	if (nullptr == root->t[w[0] - 'a']) {
		return 0;
	}
	return stat(root->t[w[0] - 'a'], w + 1);
}

int main() {

	ifstream f("trie.in");
	ofstream g("trie.out");

	char w[21];
	int i;

	while (!f.eof()) {
		f >> i >> w;
		switch (i) {
		case 0:
			add(T, w);
			break;
		case 1: 
			del(T, w);
			break;
		case 2: 
			g << stat(T, w) << "\n";
			break;
		case 3: 
			g << prefix(T, w) << "\n";
			break;
		}
	}


}