Cod sursa(job #632275)

Utilizator sunt_emoSunt emo sunt_emo Data 10 noiembrie 2011 19:23:06
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <cstdlib>

struct trie {
	int data;
	int nf;
	trie** fii;
};

std::ifstream in ("trie.in");
std::ofstream out ("trie.out");
int k,i;
trie *t;

void add (trie *t,char *s,int off) {
	t->nf++;
	if (!s[off]) t->data++;
	else {
		if (t->fii==0) {
			t->fii=(trie**) malloc (26*sizeof (trie*));
			for (i=0; i<26; i++) t->fii[i]=0;
		}
		if (t->fii[s[off]-'a']==0) {
			t->fii[s[off]-'a']=(trie*) malloc (sizeof (trie));
			t->fii[s[off]-'a']->data=0;
			t->fii[s[off]-'a']->nf=0;
			t->fii[s[off]-'a']->fii=0;
		}
		add (t->fii[s[off]-'a'],s,off+1);
	}
}

void del (trie *t,char *s,int off) {
	t->nf--;
	if (!s[off]) t->data--;
	else del (t->fii[s[off]-'a'],s,off+1);
}

int nr (trie *t,char *s,int off) {
	if (t==0) return 0;
	if (!s[off]) return t->data;
	if (!t->fii) return 0;
	return nr (t->fii[s[off]-'a'],s,off+1);
}

int pr (trie *t,char *s,int off) {
	if (t==0) return off-1;
	if (!s[off]) return off;
	if (!t->nf) return off-1;
	if (t->fii) return pr (t->fii[s[off]-'a'],s,off+1);
	else return off;
}

int main () {
	char s[20];
	t=(trie*) malloc (sizeof (trie));
	t->data=0;
	t->nf=0;
	t->fii=0;
	while (!in.eof ()) {
		in>>k;
		if (!in.eof ()) {
			in>>s;
			if (k==0) add (t,s,0);
			if (k==1) del (t,s,0);
			if (k==2) out<<nr (t,s,0)<<"\n";
			if (k==3) out<<pr (t,s,0)<<"\n";
		}
	}
	return 0;
}