Pagini recente » Cod sursa (job #5519) | Cod sursa (job #2543760) | Cod sursa (job #87697) | Cod sursa (job #1205463) | Cod sursa (job #1678328)
#include <fstream>
#include <cstring>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
int n;
class TrieNode {
int cnt, subtree_words;
TrieNode *Edg[26];
public:
TrieNode(int _cnt = 0, int _subtree_words = 0) {
cnt = _cnt;
subtree_words = _subtree_words;
memset(Edg, 0, sizeof Edg);
}
void TrieInsert(const string &str, const int &pos = 0) {
if(str[pos] == 0) {
++cnt;
++subtree_words;
return;
}
if(Edg[str[pos] - 'a'] == nullptr) { ///Word not in trie
Edg[str[pos] - 'a'] = new TrieNode;
}
Edg[str[pos] - 'a']->TrieInsert(str, pos + 1);
++subtree_words;
}
void TrieRemove(const string &str, const int &pos = 0) {
if(str[pos] == 0) {
--cnt;
--subtree_words;
return;
}
Edg[str[pos] - 'a']->TrieRemove(str, pos + 1);
--subtree_words;
}
int TrieAppr(const string &str, const int &pos = 0) {
if(str[pos] == 0) { ///Word found
return cnt;
}
if(Edg[str[pos] - 'a'] == nullptr) { ///Word not in Trie
return 0;
}
return Edg[str[pos] - 'a']->TrieAppr(str, pos + 1);
}
int TriePrefix(const string &str, const int &pos = 0) {
if(str[pos] == 0) {
return pos;
}
if(subtree_words == 0) {
return pos - 1;
}
if(Edg[str[pos] - 'a'] == nullptr) {
return pos;
}
return Edg[str[pos] - 'a']->TriePrefix(str, pos + 1);
}
};
TrieNode *Rt = new TrieNode;
int main() {
int type;
string str;
while(cin >> type >> str) {
if(type == 0) {
Rt->TrieInsert(str);
}
else if(type == 1) {
Rt->TrieRemove(str);
}
else if(type == 2) {
cout << Rt->TrieAppr(str) << '\n';
}
else {
cout << Rt->TriePrefix(str) << '\n';
}
}
return 0;
}