Pagini recente » Cod sursa (job #757189) | Cod sursa (job #164799) | Cod sursa (job #1109020) | Cod sursa (job #2068001) | Cod sursa (job #2752355)
#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;
Trie* root = new Trie();
while (1) {
string s;
if (cin >> op) {
cin >> 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";
}
else
return 0;
}
return 0;
}