Pagini recente » Cod sursa (job #1770927) | Cod sursa (job #1879168) | Cod sursa (job #1559396) | Cod sursa (job #494007) | Cod sursa (job #1844791)
#include <cstdio>
#include <cstring>
using namespace std;
struct trie {
trie *next[ 27 ];
bool terminal;
int cnt, nrfii;
trie () {
cnt = nrfii = 0;
memset( next, 0, sizeof( next ) );
terminal = false;
}
};
void inser ( trie * node, char * s ) {
if ( *s == 0 ) {
node -> terminal = true;
node -> cnt++;
return ;
}
if ( ! node -> next[ *s - 'a' ] ) {
node -> next[ *s - 'a' ] = new trie;
node -> nrfii++;
}
return inser( node -> next[ *s - 'a' ], s + 1 );
}
int aparitii ( trie * node, char * s ) {
if ( ! node ) return 0;
if ( *s == 0 ) return node -> cnt;
return aparitii( node -> next[ *s - 'a' ], s + 1 );
}
int prefix ( trie *node, char *s, int k ) {
if ( *s == 0 || !node -> next[ *s - 'a' ] ) return k;
return prefix( node -> next[ *s - 'a' ], s + 1, k + 1 );
}
int del ( trie * root, trie * node, char *s ) {
if ( *s == 0 ) {
node -> cnt--;
} else if ( del( root, node -> next[ *s - 'a' ], s + 1 ) ) {
node -> next[ *s - 'a' ] = 0;
node -> nrfii--;
}
if ( node -> cnt == 0 && node -> nrfii == 0 && node != root ) {
delete node;
return 1;
}
return 0;
}
int main () {
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
trie *root = new trie;
int k;
char s[ 100 ];
while ( scanf( "%d%s",&k,s ) != EOF ) {
if ( k == 0 ) inser ( root, s );
else if ( k == 1 ) del ( root, root, s );
else if ( k == 2 )printf( "%d\n", aparitii ( root, s ) );
else printf( "%d\n", prefix( root, s, 0 ) );
}
return 0;
}