Cod sursa(job #1456348)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 30 iunie 2015 12:53:52
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>
#include <iostream>
#include <array>
#include <algorithm>
#include <iterator>
using namespace std;

struct nod{
	array<nod*, 26> copii;
	int num_treceri = 0, num_aparitii = 0;
	nod(){
		for(auto& x : copii){
			x = nullptr; } }
	~nod(){
		for(auto x : copii){
			delete x; } }
	nod* get_copil(char la){
		la -= 'a';
		return copii[la]; }
	void adauga_copil(char la){
		la -= 'a';
		if(copii[la] == nullptr){
			copii[la] = new nod; } }
	void scoate_copil(char la){
		la -= 'a';
		if(copii[la] != nullptr){
			delete copii[la]; }
		copii[la] = nullptr; }
	void add(string::iterator st, string::iterator dr){
		if(st != dr){
			adauga_copil(*st);
			++num_treceri;
			get_copil(*st)->add(st+1, dr); }
		else{
			++num_aparitii; } }
	void remove(string::iterator st, string::iterator dr){
		--num_treceri;
		if(st != dr){
			if(get_copil(*st)->num_treceri <= 1){
				scoate_copil(*st); }
			else{
				get_copil(*st)->remove(st+1, dr); } }
		else{
			--num_aparitii; } }
	int query_1(string::iterator st, string::iterator dr){
		if(st != dr){
			if(get_copil(*st)){
				return get_copil(*st)->query_1(st+1, dr); }
			else{
				return 0; } }
		else{
			return num_aparitii; } }
	int query_2(string::iterator st, string::iterator dr, int rez=0){
		if(st != dr){
			if(get_copil(*st)){
				return get_copil(*st)->query_2(st+1, dr, rez+1); }
			else{
				return rez; } }
		else{
			return rez; } } };

int main(){
	ifstream f("trie.in");
	ofstream g("trie.out");
	nod* radacina = new nod;
	string str;
	str.reserve(20);
	for(int i = 0, a; f; ++i){
		f >> a >> str;
		if(f){
			switch(a){
			case 0:
				radacina->add(begin(str), end(str));
				break;
			case 1:
				radacina->remove(begin(str), end(str));
				break;
			case 2:
				g << radacina->query_1(begin(str), end(str)) << '\n';
				break;
			case 3:
				g << radacina->query_2(begin(str), end(str)) << '\n';
				break; } } }
	return 0; }