Pagini recente » Cod sursa (job #13290) | Cod sursa (job #2690818) | Cod sursa (job #2519651) | Cod sursa (job #2564773) | Cod sursa (job #2788437)
#include <fstream>
#include <map>
#include <vector>
#define SIGMA 26
using namespace std;
ifstream cin ("trie.in");
ofstream cout ("trie.out");
struct strnode {
int finish_word, finish_prefix;
};
int nnode;
map <char, int> mpnext[2000001];
strnode vnode[2000001];
struct Trie {
int freqpref, freqcuv;
Trie* sons[SIGMA + 1];
Trie() {
freqpref = freqcuv = 0;
for (int i = 0; i < SIGMA; ++i)
sons[i] = NULL;
}
};
void add(Trie* root, string s, int pos) {
root->freqpref++;
if (pos == s.size()) {
root->freqcuv++;
return;
}
int lit = s[pos] - 'a';
if (root->sons[lit] == NULL)
root->sons[lit] = new Trie;
add(root->sons[lit], s, pos + 1);
}
void del(Trie* root, string s, int pos) {
root-> freqpref--;
if (pos == s.size()) {
root->freqcuv--;
return;
}
int lit = s[pos] - 'a';
del(root-> sons[lit], s, pos + 1);
}
int cnt(Trie* root, string s, int pos) {
if (pos == s.size())
return root->freqcuv;
int lit = s[pos] - 'a';
if (root->sons[lit] == NULL || root->sons[lit]->freqpref == 0)
return 0;
return cnt(root -> sons[lit], s, pos + 1);
}
int pref(Trie* root, string s, int pos) {
if (pos == s.size())
return pos;
int lit = s[pos] - 'a';
if (root->sons[lit] == NULL || root->sons[lit]->freqpref == 0)
return pos;
return pref(root-> sons[lit], s, pos + 1);
}
int main() {
Trie* root;
int op;
string s;
root = new Trie;
while (cin >> op >> s) {
if (op == 0)
add(root, s, 0);
else if (op == 1)
del(root, s, 0);
else if (op == 2)
cout << cnt(root, s, 0) << "\n";
else
cout << pref(root, s, 0) << "\n";
s = "";
}
return 0;
}