Pagini recente » Cod sursa (job #2214069) | Cod sursa (job #2872047) | Cod sursa (job #473114) | Monitorul de evaluare | Cod sursa (job #2691009)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
class Trie {
private:
struct Node {
int cnt = 0;
int lvs = 0;
int next[26] = {};
};
vector<Node> trie{1};
bool leaf(int node) {
for (int chr = 0; chr < 26; chr++)
if (trie[node].next[chr])
return false;
return true;
}
public:
void insert(int node, const string& str, int pos) {
if (pos == (int) str.size()) {
trie[node].cnt++;
return;
}
if (!trie[node].next[str[pos] - 'a']) {
trie[node].next[str[pos] - 'a'] = trie.size();
trie.emplace_back();
}
insert(trie[node].next[str[pos] - 'a'], str, pos + 1);
trie[node].lvs++;
}
bool erase(int node, const string& str, int pos) {
if (pos == (int) str.size()) {
if (trie[node].cnt > 1 || !leaf(node)) {
trie[node].cnt--;
return false;
}
return true;
}
if (!trie[node].next[str[pos] - 'a'])
return false;
if (!erase(trie[node].next[str[pos] - 'a'], str, pos + 1))
return false;
trie[node].next[str[pos] - 'a'] = 0;
return --trie[node].lvs == 0;
}
int count(int node, const string& str, int pos) {
if (pos == (int) str.size())
return trie[node].cnt;
if (!trie[node].next[str[pos] - 'a'])
return 0;
return count(trie[node].next[str[pos] - 'a'], str, pos + 1);
}
int lcp(int node, const string& str, int pos) {
if (pos == (int) str.size())
return 0;
if (!trie[node].next[str[pos] - 'a'])
return 0;
return 1 + lcp(trie[node].next[str[pos] - 'a'], str, pos + 1);
}
};
int main() {
Trie trie;
int type; string str;
while (fin >> type >> str)
if (!type)
trie.insert(0, str, 0);
else if (type == 1)
trie.erase(0, str, 0);
else if (type == 2)
fout << trie.count(0, str, 0) << '\n';
else
fout << trie.lcp(0, str, 0) << '\n';
return 0;
}