Pagini recente » Cod sursa (job #1962672) | Cod sursa (job #2861868) | Cod sursa (job #1769816) | Cod sursa (job #2725366) | Cod sursa (job #3209186)
#include <fstream>
#include <iostream>
#include <string>
#define ll long long
#define ull unsigned long long
#define pii std::pair<int, int>
#define IO (std::string) "trie"
std::ifstream cin(IO + ".in");
std::ofstream cout(IO + ".out");
#define NMAX 100
class Trie {
int cnt = 0;
int lvs = 0;
Trie *next[26] = {};
public:
void insert(const std::string& str, int pos = 0) {
lvs++;
if (pos == int(str.size()))
cnt++;
else {
if (!next[str[pos] - 'a'])
next[str[pos] - 'a'] = new Trie;
next[str[pos] - 'a']->insert(str, pos + 1);
}
}
void erase(const std::string& str, int pos = 0) {
lvs--;
if (pos == int(str.size()))
cnt--;
else {
next[str[pos] - 'a']->erase(str, pos + 1);
if (!next[str[pos] - 'a']->lvs) {
delete next[str[pos] - 'a'];
next[str[pos] - 'a'] = nullptr;
}
}
}
int count(const std::string& str, int pos = 0) {
if (pos == int(str.size()))
return cnt;
if (!next[str[pos] - 'a'])
return 0;
return next[str[pos] - 'a']->count(str, pos + 1);
}
int lcp(const std::string& str, int pos = 0) {
if (pos == int(str.size()))
return 0;
if (!next[str[pos] - 'a'])
return 0;
return 1 + next[str[pos] - 'a']->lcp(str, pos + 1);
}
};
int main() {
Trie tr;
int op;
std::string s;
while (cin >> op >> s) {
if (op == 0)
tr.insert(s, 0);
if (op == 1)
tr.erase(s, 0);
if (op == 2)
cout << tr.count(s, 0) << '\n';
if (op == 3)
cout << tr.lcp(s, 0) << '\n';
}
return 0;
}