Pagini recente » Cod sursa (job #603984) | Cod sursa (job #2849138) | Cod sursa (job #686461) | Cod sursa (job #1956804) | Cod sursa (job #3330244)
#include <bits/stdc++.h>
using namespace std;
#define int long long
struct Node {
int cntEnd;
int cntPass;
array<Node*,26> nxt;
Node(){ cntEnd=0; cntPass=0; nxt.fill(nullptr); }
};
struct Trie {
Node* root;
Trie(){ root=new Node(); }
void add(const string &w){
Node* cur=root;
cur->cntPass++;
for(char ch:w){
int idx=ch-'a';
if(!cur->nxt[idx]) cur->nxt[idx]=new Node();
cur=cur->nxt[idx];
cur->cntPass++;
}
cur->cntEnd++;
}
void del(const string &w){
Node* cur=root;
cur->cntPass--;
for(char ch:w){
int idx=ch-'a';
cur=cur->nxt[idx];
cur->cntPass--;
}
cur->cntEnd--;
}
int count(const string &w){
Node* cur=root;
for(char ch:w){
int idx=ch-'a';
if(!cur->nxt[idx]) return 0;
cur=cur->nxt[idx];
}
return cur->cntEnd;
}
int longestPrefix(const string &w){
Node* cur=root;
int ans=0;
for(char ch:w){
int idx=ch-'a';
if(!cur->nxt[idx]) break;
cur=cur->nxt[idx];
if(cur->cntPass>0) ans++;
else break;
}
return ans;
}
};
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
Trie T;
string op,w;
while(cin>>op){
if(op=="0"){ cin>>w; T.add(w); }
else if(op=="1"){ cin>>w; T.del(w); }
else if(op=="2"){ cin>>w; cout<<T.count(w)<<"\n"; }
else if(op=="3"){ cin>>w; cout<<T.longestPrefix(w)<<"\n"; }
}
return 0;
}