Pagini recente » Cod sursa (job #2198092) | Cod sursa (job #2376784) | Cod sursa (job #2315656) | Cod sursa (job #2416201) | Cod sursa (job #3359563)
#include <bits/stdc++.h>
using namespace std;
const int cmax = 27;
struct trie {
struct node {
int cnt = 0, cnts = 0;
node* sub[cmax]{};
~node() {
for(auto i : sub) if(i) delete i;
}
};
node *r = new node;
int find(string &s) {
node *n = r;
for(int i = 0; i < s.size(); i ++) {
int ch = s[i] - 'a';
if(!n->sub[ch] || !n->sub[ch]->cnt) return 0;
n = n->sub[ch];
}
return n->cnts;
}
int find2(string &s) {
node *n = r;
for(int i = 0; i < s.size(); i ++) {
int ch = s[i] - 'a';
if(!n->sub[ch] || !n->sub[ch]->cnt) return i;
n = n->sub[ch];
}
return s.size();
}
void insert(string &s) {
node *n = r; n->cnt ++;
for(int i = 0; i < s.size(); i ++) {
int ch = s[i] - 'a';
if(!n->sub[ch] || !n->sub[ch]->cnt) n->sub[ch] = new node;
n = n->sub[ch];
n->cnt ++;
}
n->cnts ++;
}
void remove(string &s) {
node *n = r;
for(int i = 0; i < s.size() && n->cnt; i ++) {
int ch = s[i] - 'a';
if(!n->sub[ch] || !n->sub[ch]->cnt) assert(false);
n = n->sub[ch];
n->cnt --;
}
n->cnts --;
}
};
int main() {
ifstream cin("trie.in");
ofstream cout("trie.out");
cin.tie(0)->sync_with_stdio(0);
trie str;
int t;
string s;
while(cin >> t >> s) {
if(t == 0) {
str.insert(s);
} else if(t == 1) {
str.remove(s);
} else if(t == 2) {
cout << str.find(s) << '\n';
} else {
cout << str.find2(s) << '\n';
}
}
}