Pagini recente » Monitorul de evaluare | Cod sursa (job #2578687) | Cod sursa (job #1200264) | Cod sursa (job #1520631) | Cod sursa (job #1539126)
#include <fstream>
#include <algorithm>
#include <cstring>
using namespace std;
ifstream in( "trie.in" );
ofstream out( "trie.out" );
const int NMAX = 100000;
const int SIGMA = 26;
struct Trie {
int cnt, nrf;
Trie *fiu[SIGMA];
Trie() {
cnt = nrf = 0;
for( int i = 0; i < SIGMA; ++i ) {
fiu[i] = NULL;
}
}
};
Trie *Trie_Root = new Trie;
int Ans_prefix = 0;
/// #Trie
int CH( char ch ) {
return ( (int)(ch - 'a') );
}
void Insert( Trie *nod, char *s ) {
if( *s == '\0' ) {
nod->cnt++;
return ;
}
if( nod->fiu[ CH(*s) ] == NULL ) {
nod->fiu[ CH(*s) ] = new Trie;
nod->nrf++;
}
Insert( nod->fiu[ CH(*s) ] , s+1 );
}
int Delete( Trie *nod, char *s ) {
if( *s == '\0' ) {
nod->cnt--;
}
else if( Delete( nod->fiu[ CH(*s) ], s+1 ) ) {
nod->fiu[ CH(*s) ] = NULL;
nod->nrf--;
}
if( nod->cnt == 0 && nod->nrf == 0 && nod != Trie_Root ) {
delete nod;
return 1;
}
return 0;
}
int Query( Trie *nod, char *s ) {
if( *s == '\0' ) {
return nod->cnt;
}
if( nod->fiu[ CH(*s) ] ) {
return ( Query( nod->fiu[ CH(*s) ] , s+1 ) );
}
return 0;
}
int Prefix( Trie *nod, char *s, int lg ) {
if( *s == '\0' || nod->fiu[ CH(*s) ] == NULL ) {
return lg;
}
return Prefix( nod->fiu[ CH(*s) ] , s+1, lg+1 );
}
int main() {
/// Trie_Root -> cnt = 1;
char str[30];
memset( str, 0, sizeof(str) );
int op = 0;
while( in >> op ) {
memset( str, 0, sizeof( str ) );
in >> str;
if( op == 0 ) { /// ADAUGARE
Insert( Trie_Root, str );
}
else if( op == 1 ) { /// STERGERE
Delete( Trie_Root, str );
}
else if( op == 2 ) { /// DE CATE ORI
out << Query( Trie_Root, str ) << '\n';
}
else if( op == 3 ) { /// CEL MAI LUNG PREFIX
out << Prefix( Trie_Root, str, 0 ) << '\n';
}
}
return 0;
}