Cod sursa(job #905640)

Utilizator drobertDumitru Robert drobert Data 5 martie 2013 23:42:05
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <stdio.h>
#include <cstring>
char Word[32];
struct Trie {
	int Cont,Nr;
	Trie *For[26];
	Trie() {
		Cont=Nr=0;
		memset( For,0,sizeof(For) );
	}
};
Trie *Start=new Trie;

void Ins( Trie *Nod,char *s ) {
	if ( *s=='\n' ) { Nod->Cont++; return; }
	if ( Nod->For[*s-'a']==0 ) {
		Nod->For[*s-'a']=new Trie;
		Nod->Nr++;
	}
	Ins( Nod->For[*s-'a'],s+1);
}
int Del( Trie *Nod,char *s ) {
	if ( *s=='\n' ) Nod->Cont--;
	else if ( Del( Nod->For[*s-'a'],s+1 ) ) {
		Nod->For[*s-'a']=0;
		Nod->Nr--;
	}
	if ( Nod->Nr==0 && Nod->Cont==0 && Nod!=Start ) {
		delete Nod; return 1;
	}
	return 0;
}
int Apa( Trie *Nod,char *s ) {
	if ( *s=='\n' ) return Nod->Cont;
	if ( Nod->For[*s-'a'] )
		return Apa( Nod->For[*s-'a'],s+1 );
	return 0;
}
int Pre( Trie *Nod,char *s,int Lg ) {
	if ( *s=='\n' || Nod->For[*s-'a']==0 ) return Lg;
	return Pre( Nod->For[*s-'a'],s+1,Lg+1 );
}
int main ()
{
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	fgets( Word,32,stdin );
	while ( !feof(stdin) ) {
		switch ( Word[0] ) {
			case '0': { Ins(Start,Word+2); break; }
			case '1': { Del(Start,Word+2); break; }
			case '2': { printf("%d\n", Apa(Start,Word+2) ); break; }
			case '3': { printf("%d\n", Pre(Start,Word+2,0) ); break; }
		}
		fgets( Word,32,stdin );
	}
	return 0;
}