Cod sursa(job #1456871)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 2 iulie 2015 12:29:10
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

class nod{
	nod* copii[26];
public:
	int num_treceri, num_aparitii;
	nod(){
		for(auto& x : copii){
			x = nullptr; }
		num_treceri = 0;
		num_aparitii = 0; }
	~nod(){
		for(auto x : copii){
			delete x; } }
	void add_copil(char c){
		c -= 'a';
		if(!copii[c]){
			copii[c] = new nod; } }
	nod* get_copil(const char c){
		return copii[c-'a']; }
	void rm_copil(char c){
		c -= 'a';
		if(copii[c]){
			delete copii[c];
			copii[c] = nullptr; } } };

void print(nod* n, const int i = 0){
	for(char c = 'a'; c <= 'z'; ++c){
		if(n->get_copil(c)){
			for(int j = 0; j < i; ++j){
				cout << '\t'; }
			cout << c << '\n';
			print(n->get_copil(c), i+1); } } }

void add_string(nod* la, string::iterator st, string::iterator dr){
	++(la->num_treceri);
	if(st != dr){
		la->add_copil(*st);
		add_string(la->get_copil(*st), st+1, dr); }
	else{
		++(la->num_aparitii); } }

void remove_string(nod* la, string::iterator st, string::iterator dr){
	--(la->num_treceri);
	if(st != dr){
		if(la->get_copil(*st)->num_treceri == 1){
			la->rm_copil(*st); }
		else{
			remove_string(la->get_copil(*st), st+1, dr); } }
	else{
		--(la->num_aparitii); } }

int count_num_aparitii(nod* la, string::iterator st, string::iterator dr){
	if(st != dr){
		if(la->get_copil(*st) != nullptr){
			return count_num_aparitii(la->get_copil(*st), st+1, dr); }
		else{
			return 0; } }
	else{
		return la->num_aparitii; } }

int find_longest_prefix(nod* la, string::iterator st, string::iterator dr){
	if(st != dr){
		if(la->get_copil(*st) != nullptr){
			return 1 + find_longest_prefix(la->get_copil(*st), st+1, dr); }
		else{
			return 0; } }
	else{
		return 0; } }

int main(){
	ifstream f("trie.in");
	ofstream g("trie.out");
	int a;
	string str;
	nod* rad = new nod;
	while(f){
		f >> a >> str;
		if(f){
			switch(a){
			case 0:
				add_string(rad, begin(str), end(str));
				break;
			case 1:
				remove_string(rad, begin(str), end(str));
				break;
			case 2:
				g << count_num_aparitii(rad, begin(str), end(str)) << '\n';
				break;
			case 3:
				g << find_longest_prefix(rad,begin(str),end(str)) << '\n'; } } }
	return 0; }