Pagini recente » Cod sursa (job #2186441) | Cod sursa (job #1685382) | Cod sursa (job #1166859) | Cod sursa (job #2368675) | Cod sursa (job #3289775)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ( "trie.in" );
ofstream fout ( "trie.out" );
#define cin fin
#define cout fout
#define FR( a, b ) for( int a = 0; a < (int) b; a ++ )
#define FOR( a, c, b) for( int a = c; a < (int) b; a ++ )
struct noduri {
int frecv, nrcopii;
noduri* children[26];
noduri() {
frecv = nrcopii = 0;
FR( i, 26 )
children[i] = NULL;
}
};
noduri* root = new noduri;
void inserare( noduri* nod, string s, int poz ) {
if( poz == s.size() ) {
nod->frecv++;
return;
}
if( nod->children[s[poz] - 'a'] == NULL ) {
nod->children[s[poz]-'a'] = new noduri;
nod->nrcopii++;
}
inserare( nod->children[s[poz] - 'a'], s, poz + 1 );
}
int distrugere( noduri* nod, string s, int poz ) {
if( poz == s.size() ) {
if( nod->nrcopii == 0 && nod->frecv <= 1 ) {
delete nod;
return 1;
}
nod->frecv--;
return 0;
}
if( distrugere( nod->children[s[poz]-'a'], s, poz + 1 ) == 1 ) {
nod->nrcopii--;
nod->children[s[poz] - 'a'] = nullptr;
}
if( nod->nrcopii == 0 && nod->frecv == 0 && nod != root ) {
delete nod;
return 1;
}
return 0;
}
int nraparitii( noduri* nod, string s, int poz ) {
if( poz == s.size() )
return nod->frecv;
if( nod->children[s[poz]-'a'] == nullptr )
return 0;
return nraparitii( nod->children[s[poz] - 'a'], s, poz + 1);
}
int prefix( noduri* nod, string s, int poz ) {
if( poz == s.size() )
return poz;
if( nod->children[s[poz]-'a'] == nullptr )
return poz;
return prefix( nod->children[s[poz]-'a'], s, poz + 1 );
}
int main()
{
int cerinta;
string s;
while( cin >> cerinta ) {
cin >> s;
if( cerinta == 0 )
inserare( root, s, 0 );
else if ( cerinta == 1 )
distrugere( root, s, 0 );
else if ( cerinta == 2 )
cout << nraparitii(root, s, 0 ) << '\n';
else
cout << prefix( root, s, 0 ) << '\n';
}
return 0;
}