Cod sursa(job #2183424)

Utilizator flibiaVisanu Cristian flibia Data 23 martie 2018 09:59:53
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>

using namespace std;

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

struct nod{
	int nr_son, nr_cuv;
	nod *son[27];
	nod(){
		nr_son = nr_cuv = 0;
		memset(son, 0, sizeof son);
	}
};

nod *root = new nod();
int cod, sz;
string s;

void baga(nod *x, int p){
	if(p == sz){
		x -> nr_cuv++;
		return;
	}
	if(x -> son[s[p] - 'a'] == NULL){
		x -> son[s[p] - 'a'] = new nod();
		x -> nr_son++;
	}
	baga(x -> son[s[p] - 'a'], p + 1);
}

bool scoate(nod *x, int p){
	if(p == sz){
		x -> nr_cuv--;
		if(x -> nr_cuv == 0 && x -> nr_son == 0 && x != root){
			delete x;
			return 1;
		}
		return 0;
	}
	if(scoate(x -> son[s[p] - 'a'], p + 1)){
		x -> nr_son--;
		x -> son[s[p] - 'a'] = NULL;
		if(x -> nr_cuv == 0 && x -> nr_son == 0 && x != root){
			delete x;
			return 1;
		}
	}
	return 0;
}

int aparitii(nod *x, int p){
	if(p == sz)
		return x -> nr_cuv;
	if(x -> son[s[p] - 'a'] == NULL)
		return 0;
	return aparitii(x -> son[s[p] - 'a'], p + 1);
}

int prefix(nod *x, int p){
	if(p == sz)
		return 1;
	if(x -> son[s[p] - 'a'] == 0)
		return 0;
	return 1 + prefix(x -> son[s[p] - 'a'], p + 1);
}

int main(){
	while(in >> cod >> s){
		sz = s.size();
		if(cod == 0){
			baga(root, 0);
			continue;
		}
		if(cod == 1){
			scoate(root, 0);
			continue;
		}
		if(cod == 2){
			out << aparitii(root, 0) << '\n';
			continue;
		}
		if(cod == 3){
			out << prefix(root, 0) << '\n';
			continue;
		}
	}
	return 0;
}