Cod sursa(job #234062)

Utilizator sima_cotizoSima Cotizo sima_cotizo Data 19 decembrie 2008 21:58:53
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <cstdio>
#include <cstring>
using namespace std;

const int nr_lit = 'z'-'a'+1;
struct trie {
	trie	*p[nr_lit];
	int		value;
	trie() { value = 0; memset(p, 0, sizeof(p)); }
} root;

void add( char* );
void del( char* );
void ask( char* );
void wtf( char* );

int main() {
	freopen( "trie.in", "r", stdin );
	freopen( "trie.out", "w", stdout );

	while ( !feof(stdin) ) {
		int op;
		char buf[32];
		scanf( "%d %s\n", &op, buf );
		switch ( op ) {
			case 0: add( buf ); break;
			case 1: del( buf ); break;
			case 2: ask( buf ); break;
			case 3: wtf( buf );
		}
	}
	return 0;
}

void add( char *s ) {
	trie *p = &root;
	int n = strlen( s );	
	for ( int i=0; i<n; p = p->p[ s[i++]-'a' ] )
		if ( p->p[ s[i]-'a' ] == NULL ) 
			p->p[ s[i]-'a' ] = new trie();
	p -> value ++;
}

void cleanup( trie *p, char *s, int i, int n ) {
	if ( i==n ) return;
	cleanup( p->p[ s[i]-'a' ], s, i+1, n );
	bool ok = true;
	for ( int l = 0; l<nr_lit; ++l )
		if ( p->p[ s[i]-'a']->p[l] != NULL )
			ok = false;
	if ( ok && p->p[ s[i]-'a']->value==0 ) {
		delete p->p[ s[i]-'a'];
        p->p[ s[i]-'a' ] = NULL;
    }
}

void del( char *s ) {
	trie *p = &root;
	int n = strlen( s ), tmp[32];
	for ( int i=0; i<n; p = p->p[ s[i++]-'a' ] ) {
		if ( p->p[ s[i]-'a' ] == NULL )
			return;
		tmp[i] = p->value;
	}
	p -> value --;

	cleanup( &root, s, 0, n );
}

void ask( char *s ) {
	trie *p = &root;
	int n = strlen( s );
	bool ok = true;
	for ( int i=0; i<n; p = p->p[ s[i++]-'a' ] )
		if ( p->p[ s[i]-'a' ] == NULL ) {
			ok = false; 
			break;
		}
	printf( "%d\n", ok ? p->value : 0 );
}

void wtf( char *s ) {
	trie *p = &root;
	int n = strlen( s ), i;
	for ( i=0; i<n; p = p->p[ s[i++]-'a' ] )
		if ( p->p[ s[i]-'a' ] == NULL )
			break;
	printf( "%d\n", i );

}