Cod sursa(job #2195945)

Utilizator flibiaVisanu Cristian flibia Data 17 aprilie 2018 20:53:58
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

using namespace std;

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

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

nod *root;
string s;
int sz, cod; 

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

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

int aparitii(nod *x, int p){
	if(p == sz)
		return x -> nrcuv;
	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 0;
	if(x -> son[s[p] - 'a'] == NULL)
		return 0;
	return 1 + prefix(x -> son[s[p] - 'a'], p + 1);
}

int main(){
	root = new nod();
	while(in >> cod){
		in >> 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;
}