Pagini recente » Cod sursa (job #3278539) | Cod sursa (job #2938033) | Cod sursa (job #1581842) | Cod sursa (job #983836) | Cod sursa (job #3281280)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int x;
string str;
struct Trie {
int cnt = 0,lvs = 0;
Trie *next[26] = {};
void insert(const 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 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 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 string &str, int pos = 0) {
if (pos == int(str.size()))
return pos;
if (!next[str[pos] - 'a'])
return pos;
return next[str[pos] - 'a']->lcp(str, pos+1);
}
};
Trie root;
int main() {
while (fin >> x >> str){
if (x == 0)
root.insert(str);
else if (x == 1)
root.erase(str);
else if (x == 2)
fout << root.count(str) << "\n";
else
fout << root.lcp(str) << "\n";
}
}