Cod sursa(job #2080862)

Utilizator ice_creamIce Cream ice_cream Data 3 decembrie 2017 16:26:47
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

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

const int NMAX = 20;
char s[NMAX + 2];

class Trie {
	public:
		int cuvinte;
		int aparitii;
		Trie *fii[26];
	
		Trie() {
			cuvinte = 0;
			for (int i = 0; i < 26; i++)
				fii[i] = NULL;
		}
};

Trie *t;

Trie *adauga(char *s, Trie *t) {
	if (t == NULL) t = new Trie();
	t->aparitii++;
	if (s[0] == 0) {
		t->cuvinte++;
		return t;
	}
	t->fii[s[0] - 'a'] = adauga(s + 1, t->fii[s[0] - 'a']);
	return t;
}


Trie *sterge(char *s, Trie *t) {
	if (t == NULL) return NULL;
	t->aparitii--;
	if (s[0] == 0) {
		t->cuvinte--;
		if (t->aparitii == 0) {
			delete t;
			return NULL;
		}
		return t;
	}
	t->fii[s[0] - 'a'] = sterge(s + 1, t->fii[s[0] - 'a']);
	return t;
}

int nr_aparitii(char *s, Trie *t) {
	if (t == NULL) return 0;
	if (s[0] == 0) return t->cuvinte;
	return nr_aparitii(s + 1, t->fii[s[0] - 'a']);
}

int prefix(char *s, Trie *t) {
	if (t == NULL) return -1;
	if (s[0] == 0) return 0;
	return 1 + prefix(s + 1, t->fii[s[0] - 'a']);
}

void rezolva() {
	int op;

	while (f >> op >> s) {
		if (op == 0) t = adauga(s, t);
		if (op == 1) t = sterge(s, t);
		if (op == 2) g << nr_aparitii(s, t) << '\n';
		if (op == 3) g << prefix(s, t) << '\n';;
	}
}

int main() {
	rezolva();
}