Pagini recente » Cod sursa (job #976833) | Cod sursa (job #2340575) | Cod sursa (job #107542) | Cod sursa (job #425129) | Cod sursa (job #226148)
Cod sursa(job #226148)
Utilizator |
Lucian Boca amadaeus |
Data |
1 decembrie 2008 03:25:41 |
Problema |
Trie |
Scor |
Ascuns |
Compilator |
cpp |
Status |
done |
Runda |
|
Marime |
1.44 kb |
#include <cstdio>
#include <cstring>
using namespace std;
struct Trie {
int cnt, nrfii;
Trie *fiu[ 26 ];
Trie() {
cnt = nrfii = 0;
memset( fiu, 0, sizeof( fiu ) );
}
};
Trie *T = new Trie;
void ins( Trie *nod, char *s ) {
if( *s == '\n' ) {
nod->cnt ++; return;
}
int ch = *s - 'a';
if( nod->fiu[ ch ] == 0 ) {
nod->fiu[ ch ] = new Trie;
nod->nrfii ++;
}
ins( nod->fiu[ ch ], s+1 );
}
int del( Trie *nod, char *s ) {
if( *s == '\n' )
nod->cnt --;
else if( del( nod->fiu[ *s - 'a' ], s+1 ) ) {
nod->fiu[ *s - 'a' ] = 0;
nod->nrfii --;
}
if( nod->cnt == 0 && nod->nrfii == 0 && nod != T ) {
delete nod; return 1;
}
return 0;
}
int que( Trie *nod, char *s ) {
if( *s == '\n' )
return nod->cnt;
if( nod->fiu[ *s -'a' ] )
return que( nod->fiu[ *s - 'a' ], s+1 );
return 0;
}
int pre( Trie *nod, char *s, int k ) {
if( *s == '\n' || nod->fiu[ *s - 'a' ] == 0 )
return k;
return pre( nod->fiu[ *s - 'a' ], s+1, k+1 );
}
int main() {
char line[ 32 ];
freopen( "trie.in", "r", stdin );
freopen( "trie.out", "w", stdout );
fgets( line, 32, stdin );
while( !feof( stdin ) ) {
switch( line[0] ) {
case '0': ins( T, line+2 ); break;
case '1': del( T, line+2 ); break;
case '2': printf( "%d\n", que( T, line+2 ) ); break;
case '3': printf( "%d\n", pre( T, line+2, 0 ) ); break;
}
fgets( line, 32, stdin );
}
return 0;
}