Cod sursa(job #632577)

Utilizator sunt_emoSunt emo sunt_emo Data 11 noiembrie 2011 18:01:57
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <cstdlib>

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

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

void add (trie *t,char *s,int off) {
	if (!s[off]) {
		t->data++;
		return;
	}
	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']->fii=0;
	}
	add (t->fii[s[off]-'a'],s,off+1);
}

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

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->fii) return off;
	return pr (t->fii[s[off]-'a'],s,off+1);
}

int main () {
	char s[20];
	t=(trie*) malloc (sizeof (trie));
	t->data=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;
}