Pagini recente » Cod sursa (job #2248538) | Cod sursa (job #122003) | Cod sursa (job #1172569) | Cod sursa (job #629972) | Cod sursa (job #2904376)
#include <fstream>
#include <unordered_map>
using namespace std;
ifstream cin ( "trie.in" );
ofstream cout ( "trie.out") ;
struct Trie {
unordered_map<char, Trie*> nodes;
int isFinal;
int words_now;
Trie* getNode ( char ch ) {
auto it = nodes.find(ch);
if ( it != nodes.end() ) {
return it->second;
}
return NULL;
}
Trie* addNode ( char ch ) {
nodes[ch] = new Trie();
return nodes[ch];
}
};
Trie root;
void addString ( const string& s ) {
int i;
Trie* aux;
aux = &root;
for ( i = 0; i < s.size(); ++i ) {
if ((*aux).getNode(s[i]) == NULL) {
aux = (*aux).addNode(s[i]);
(*aux).words_now++;
}
else {
aux = (*aux).getNode(s[i]);
(*aux).words_now++;
}
}
(*aux).isFinal++;
}
int String_Occurences ( const string& s ) {
int i;
Trie* aux;
aux = &root;
for ( i = 0; i < s.size(); ++i ) {
if ((*aux).getNode(s[i]) == NULL) {
return 0;
}
else {
aux = (*aux).getNode(s[i]);
}
}
return (*aux).isFinal;
}
int Max_Prefix ( const string& s ) {
int i, cnt;
Trie* aux;
aux = &root;
cnt = 0;
for ( i = 0; i < s.size(); ++i ) {
if ((*aux).getNode(s[i]) == NULL) {
return cnt;
}
else {
aux = (*aux).getNode(s[i]);
cnt += ( (*aux).words_now > 0 );
}
}
}
void Delete_String ( const string& s ) {
int i;
Trie* aux;
aux = &root;
for ( i = 0; i < s.size(); ++i ) {
aux = (*aux).getNode(s[i]);
(*aux).words_now--;
}
(*aux).isFinal--;
}
void Evaluate( int op, const string& s ) {
if ( op == 0 ) {
addString( s );
}
else if ( op == 1 ) {
Delete_String( s );
}
else if ( op == 2 ) {
cout << String_Occurences( s ) << "\n";
}
else if ( op == 3 ) {
cout << Max_Prefix( s ) << "\n";
}
}
int main() {
int op;
string s;
while ( cin >> op ) {
cin >> s;
Evaluate( op, s );
}
return 0;
}