Pagini recente » Cod sursa (job #294480) | Cod sursa (job #494952) | Cod sursa (job #1691733) | Cod sursa (job #2811872) | Cod sursa (job #2486633)
#include <fstream>
#include <cstring>
using namespace std;
ifstream in ( "trie.in" );
ofstream out ( "trie.out" );
struct nod {
int info;
nod *urm[26], *prec[26];
/*nod() {
info = 0;
memset ( urm, 0, sizeof ( urm ) );
memset ( prec, 0, sizeof ( prec ) );
}*/
};
nod* prim;
void adaug ( nod* &first, string s ) {
if ( first == NULL ) {
first = new nod;
first->info = 0;
for ( int i = 0; i < 26; i++ )
first->prec[i] = first->urm[i] = NULL;
}
nod *aux = first;
for ( int i = 0; i < s.size(); i++ ) {
if ( aux->urm[s[i] - 'a'] == NULL ) {
nod *aux2 = new nod;
aux->urm[s[i] - 'a'] = aux2;
if ( i != 0 )
aux2->prec[s[i - 1] - 'a'] = aux;
aux = aux2;
for ( int j = i + 1; j < s.size(); j++ ) {
aux2 = new nod;
aux2->info = 0;
for ( int k = 0; k < 26; k++ )
aux2->urm[k] = aux2->prec[k] = NULL;
aux->urm[s[j] - 'a'] = aux2;
aux2->prec[s[j - 1] - 'a'] = aux;
aux = aux2;
}
break;
} else
aux = aux->urm[s[i] - 'a'];
}
aux->info++;
}
void scoate ( nod* &first, string s ) {
nod *aux = first;
for ( int i = 0; i < s.size(); i++ )
aux = aux->urm[s[i] - 'a'];
if ( aux->info >= 2 )
aux->info--;
else {
aux->info--;
nod *aux2;
for ( int i = s.size() - 1; i >= 0 && !aux->info; i-- ) {
if ( i != 0 )
aux2 = aux->prec[s[i - 1] - 'a'];
else
aux2 = first;
aux2->urm[s[i] - 'a'] = NULL;
delete ( aux );
aux = aux2;
}
}
}
void afiseaza ( nod* &first, string s ) {
nod *aux = first;
for ( int i = 0; i < s.size(); i++ )
aux = aux->urm[s[i] - 'a'];
out << aux->info << '\n';
}
void prefix ( nod* &first, string s ) {
nod *aux = first;
int max1 = 0, cnt = 0;
for ( int i = 0; i < s.size() && aux != NULL; i++ ) {
aux = aux->urm[s[i] - 'a'];
cnt++;
if ( aux != NULL && aux->info )
max1 = cnt;
}
out << max1 << '\n';
}
string s, s0;
int main() {
int t;
in >> t >> ws >> s;
//prim = new nod();
while ( s != s0 ) {
if ( t == 0 )
adaug ( prim, s );
else if ( t == 1 )
scoate ( prim, s );
else if ( t == 2 )
afiseaza ( prim, s );
else
prefix ( prim, s );
s0 = s;
in >> t >> ws >> s;
}
return 0;
}