Pagini recente » Cod sursa (job #1061073) | Cod sursa (job #996757) | Cod sursa (job #269951) | Cod sursa (job #3137251) | Cod sursa (job #3297419)
#include <fstream>
const int SIGMA = 26;
struct Trie {
Trie *c[SIGMA];
int cnt = 0;
int all = 0;
};
void insert( Trie* &root, const std::string &str, int idx ) {
if( !root ) root = new Trie();
root->all++;
if( idx == (int)str.size() ){
root->cnt++;
return;
}
insert( root->c[str[idx]], str, idx + 1 );
}
void erase( Trie* &root, const std::string &str, int idx ) {
root->all--;
if( idx == (int)str.size() ){
root->cnt--;
return;
}
erase( root->c[str[idx]], str, idx + 1 );
}
int count( Trie* root, const std::string &str, int idx ) {
if( !root ) return 0;
if( idx == (int)str.size() )
return root->cnt;
return count( root->c[str[idx]], str, idx + 1 );
}
int maxpref( Trie *root, const std::string &str, int idx ) {
if( !root || !root->all ) return -1;
if( idx == (int)str.size() ) return 0;
return 1 + maxpref( root->c[str[idx]], str, idx + 1 );
}
int main() {
std::ifstream fin( "trie.in" );
std::ofstream fout( "trie.out" );
Trie *root = new Trie();
int task;
while( fin >> task ){
std::string str;
fin >> str;
for( auto &ch : str ) ch -= 'a';
if( task == 0 ) insert( root, str, 0 );
if( task == 1 ) erase( root, str, 0 );
if( task == 2 ) fout << count( root, str, 0 ) << '\n';
if( task == 3 ) fout << maxpref( root, str, 0 ) << '\n';
}
return 0;
}