Pagini recente » Cod sursa (job #1098435) | Cod sursa (job #1660405) | Cod sursa (job #1309850) | Cod sursa (job #219110) | Cod sursa (job #3252004)
/*
__
/\ \
_ __ ___ ___\ \ \/'\ ___ __ ___ ___ __
/\`'__\/ __`\ /'___\ \ , < / __`\ /'__`\ /' _ `\ /' _ `\ /'__`\
\ \ \//\ \L\ \/\ \__/\ \ \\`\ /\ \L\ \/\ \L\.\_/\ \/\ \/\ \/\ \/\ \L\.\_
\ \_\\ \____/\ \____\\ \_\ \_\ \____/\ \__/.\_\ \_\ \_\ \_\ \_\ \__/.\_\
\/_/ \/___/ \/____/ \/_/\/_/\/___/ \/__/\/_/\/_/\/_/\/_/\/_/\/__/\/_/
*/
#include <bits/stdc++.h>
using namespace std;
#define ft first
#define sd second
#define endl '\n'
using i64 = int64_t;
struct node {
int cnt, kidz;
node* v[27];
node() {
cnt = 0;
kidz = 0;
for (int i = 0; i < 27; i++) {
v[i] = NULL;
}
}
};
node* root = new node();
void add(node* crt, string& s, int idx) {
if (idx == (int)s.size()) {
crt->cnt++;
return;
}
if (crt->v[s[idx] - 'a'] == NULL) {
crt->v[s[idx] - 'a'] = new node();
crt->kidz++;
}
add(crt->v[s[idx] - 'a'], s, idx + 1);
}
bool del(node* crt, string& s, int idx) {
if (idx == (int)s.size()) {
if (crt->cnt <= 1 && crt->kidz == 0) {
delete crt;
return true;
}
crt->cnt--;
return false;
}
bool d = del(crt->v[s[idx] - 'a'], s, idx + 1);
if (d) {
crt->kidz -= d;
crt->v[s[idx] - 'a'] = NULL;
}
if (crt == root) {
return false;
}
if (crt->kidz == 0 && crt->cnt == 0) {
delete crt;
return true;
}
return false;
}
int query_ap(node* crt, string& s, int idx) {
if (idx == (int)s.size()) {
return crt->cnt;
}
if (crt->v[s[idx] - 'a'] == NULL) {
return 0;
}
return query_ap(crt->v[s[idx] - 'a'], s, idx + 1);
}
int query_pre(node* crt, string& s, int idx) {
if (idx == (int)s.size()) {
return 0;
}
if (crt->v[s[idx] - 'a'] == NULL) {
return 0;
}
return 1 + query_pre(crt->v[s[idx] - 'a'], s, idx + 1);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
// #ifdef LOCAL
// ifstream cin{"input.txt"};
// ofstream cout{"output.txt"};
// #endif
ifstream cin{"trie.in"};
ofstream cout{"trie.out"};
int x;
string s;
while (cin >> x) {
cin >> s;
if (x == 0) {
add(root, s, 0);
} else if (x == 1) {
del(root, s, 0);
} else if (x == 2) {
cout << query_ap(root, s, 0) << endl;
} else if (x == 3) {
cout << query_pre(root, s, 0) << endl;
}
}
return 0;
}