Cod sursa(job #1456323)

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

class trie{
	struct nod{
		array<nod*, 26> copii{ {nullptr} };
		int num_treceri = 0, num_aparitii = 0;
		~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; } };
	nod* radacina = new nod;
public:
	void add(string::iterator st, string::iterator dr){
		++(radacina->num_treceri);
		nod* n = radacina;
		for( ; st != dr; ++st){
			n->adauga_copil(*st);
			n = n->get_copil(*st);
			++(n->num_treceri); }
		++(n->num_aparitii); }
	void remove(string::iterator st, string::iterator dr){
		--(radacina->num_treceri);
		for(nod *n = radacina, *next; st != dr; ++st, n = next){
			next = n->get_copil(*st);
			if(next == nullptr){
				return; }
			if(next->num_treceri <= 0){
				n->scoate_copil(*st);
				return; } } }
	int query_num_aparitii(string::iterator st, string::iterator dr){
		nod* n = radacina;
		for( ; st != dr; ++st){
			if(!(n->get_copil(*st))){
				return 0; }
			n = n->get_copil(*st); }
		return n->num_aparitii; }
	int query_longest_prefix(string::iterator st, string::iterator dr){
		int rez = 0;
		for(nod *n = radacina; st != dr; n = n->get_copil(*st), ++st, ++rez){
			if(n->get_copil(*st) == nullptr){
				return rez; } }
		return rez; } };

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