Pagini recente » Cod sursa (job #1570030) | Cod sursa (job #3186559) | Cod sursa (job #380539) | Cod sursa (job #2067725) | Cod sursa (job #1845327)
#include <cstdio>
#include <cstring>
using namespace std;
struct Trie {
Trie * next[ 27 ];
int terminal;
int cnt, nr_fi;
Trie () {
memset( next, 0, sizeof( next ) );
cnt = nr_fi = terminal = 0;
}
};
void Insert ( Trie * node, char * s );
int QueryAparitii ( Trie * node, char * s );
int Delete ( Trie * node, Trie * root, char * s );
int QueryPrefix ( Trie * node, char * s, int nivel );
int main () {
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
int k;
char s[ 100 ];
Trie * root = new Trie;
while ( scanf( "%d%s",&k,s ) != EOF ) {
if ( k == 0) {
Insert( root, s );
} else if ( k == 1 ) {
Delete( root, root, s );
} else if ( k == 2 ) {
printf( "%d\n",QueryAparitii( root, s ) );
} else {
printf( "%d\n",QueryPrefix( root, s, 0 ) );
}
}
return 0;
}
void Insert ( Trie * node, char * s ) {
if ( *s == 0 ) {
node -> terminal = 1;
node -> cnt++;
return ;
}
if ( !node -> next[ * s - 'a' ] ) {
node -> next[ * s - 'a' ] = new Trie;
node -> nr_fi++;
}
Insert( node -> next[ *s - 'a' ], s + 1 );
}
int QueryAparitii ( Trie * node, char * s ) {
if ( !node ) return 0;
if ( *s == 0 ) return node -> cnt;
return QueryAparitii( node -> next[ *s - 'a' ], s + 1 );
}
int Delete ( Trie * node, Trie * root, char * s ) {
if ( *s == 0 ) {
node -> cnt--;
} else if ( Delete( node -> next[ *s - 'a' ] , root, s + 1 ) ) {
node -> next[ *s - 'a' ] = 0;
node -> nr_fi--;
}
if ( node -> cnt == 0 && node -> nr_fi == 0 && node != root ) {
delete node;
return 1;
}
return 0;
}
int QueryPrefix ( Trie * node, char * s, int nivel ) {
if ( *s == 0 || !node -> next[ *s - 'a' ] ) return nivel;
return QueryPrefix( node -> next[ *s - 'a' ], s + 1, nivel + 1 );
}