Pagini recente » Cod sursa (job #44131) | Cod sursa (job #1894825) | Cod sursa (job #2605189) | Cod sursa (job #1665167) | Cod sursa (job #2752354)
#include <fstream>
#define SIGMA 'z' - 'a' + 1
using namespace std;
ifstream cin ("trie.in");
ofstream cout ("trie.out");
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 poz) {
root->freqpref++;
if (poz == s.size()) {
root->freqcuv++;
return;
}
int lit = s[poz] - 'a';
if (root->sons[lit] == NULL)
root->sons[lit] = new Trie;
add(root->sons[lit], s, poz + 1);
}
void del(Trie* root, string s, int poz) {
root->freqpref--;
if (poz == s.size()) {
root->freqcuv--;
return;
}
int lit = s[poz] - 'a';
del(root->sons[lit], s, poz + 1);
}
int cnt(Trie* root, string s, int poz) {
if (poz == s.size())
return root->freqcuv;
int lit = s[poz] - 'a';
return cnt(root->sons[lit], s, poz + 1);
}
int pref(Trie* root, string s, int poz) {
if (poz == s.size())
return poz;
int lit = s[poz] - 'a';
if (root->sons[lit] == NULL || root->sons[lit]->freqpref == 0)
return poz;
return pref(root-> sons[lit], s, poz + 1);
}
int main() {
int op;
string s;
Trie* 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 if (op == 3)
cout << pref(root, s, 0) << "\n";
}
return 0;
}