Pagini recente » Cod sursa (job #780551) | Cod sursa (job #251965) | Cod sursa (job #2474003) | Cod sursa (job #537301) | Cod sursa (job #2905707)
#include <stdio.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize ("unroll-loops")
#define DELTA 1e-9
#define MAX 300
#define SIGMA 26
struct Trie {
int freq;
int words;
Trie* children[ SIGMA ];
Trie() {
freq = 0;
words = 0;
for( int i = 0; i < SIGMA; i++ )
children[ i ] = nullptr;
}
};
void insert( Trie* root, char* S ) {
if( *S == '\0' ) {
root->freq++;
root->words++;
} else {
if( root->children[ *S - 'a' ] == nullptr )
root->children[ *S - 'a' ] = new Trie();
root->children[ *S - 'a' ]->freq++;
insert(root->children[ *S - 'a' ], S + 1 );
}
}
void erese( Trie* root, char* S ) {
if( *S == '\0' ) {
root->freq--;
root->words--;
} else {
if( root->children[ *S - 'a' ] == nullptr )
root->children[ *S - 'a' ] = new Trie();
root->children[ *S - 'a' ]->freq--;
erese( root->children[ *S - 'a' ], S + 1 );
}
}
int no( Trie* root, char* S ) {
if( *S == '\0' )
return root->words;
else {
if( root->children[ *S - 'a' ] == nullptr || root->children[ *S - 'a' ]->freq == 0 )
return 0;
return no( root->children[ *S - 'a' ], S + 1 );
}
}
int val;
int rez( Trie* root, char* S ) {
if( *S == '\0' )
return val;
else {
if( root->children[ *S - 'a' ] == nullptr || root->children[ *S - 'a' ]->freq == 0 )
return val;
++val;
return rez( root->children[ *S - 'a' ], S + 1 );
}
}
int main()
{
Trie root;
int cerinta;
char s[ 23 ];
FILE *fin = fopen( "trie.in", "r" );
FILE *fout = fopen( "trie.out", "w" );
while( ~fscanf( fin, "%d %s\n", &cerinta, s ) ) {
if( cerinta == 0 )
insert( &root, s );
else if( cerinta == 1 )
erese( &root, s );
else if( cerinta == 2 )
fprintf( fout, "%d\n", no( &root, s ) );
else {
val = 0;
fprintf( fout, "%d\n", rez( &root, s ) );
}
}
fclose( fin );
fclose( fout );
return 0;
}