Pagini recente » Cod sursa (job #841359) | Cod sursa (job #729320) | Cod sursa (job #247301) | Cod sursa (job #2644887) | Cod sursa (job #3295276)
#include "bits/stdc++.h"
const int SIGMA = 26;
const int FIRST_LETTER = 'a';
struct Trie{
Trie* children[SIGMA];
bool isWord;
int cnt;
int subcnt;
};
Trie* root;
Trie* newTrie(){
Trie* answer = new Trie();
answer -> isWord = false;
answer -> cnt = 0;
answer -> subcnt = 0;
for(int i = 0; i < SIGMA; i++){
answer -> children[i] = NULL;
}
return answer;
}
void Insert(Trie* root, char *S){
root -> subcnt++;
if(S[0] == '\0'){
root -> isWord = true;
root -> cnt++;
}else{
if(root -> children[S[0] - FIRST_LETTER] == NULL){
root -> children[S[0] - FIRST_LETTER] = newTrie();
}
Insert(root -> children[S[0] - FIRST_LETTER], S + 1);
}
}
void Erase(Trie* root, char* S){
root -> subcnt--;
if(S[0] == '\0'){
root -> isWord = false;
root -> cnt--;
}else{
if(root -> children[S[0] - FIRST_LETTER] != NULL){
Erase(root -> children[S[0] - FIRST_LETTER], S + 1);
}
}
}
int Find(Trie* root, char* S){
if(S[0] == '\0'){
return root -> cnt;
}else{
if(root -> children[S[0] - FIRST_LETTER] == NULL){
return false;
}else{
return Find(root -> children[S[0] - FIRST_LETTER], S + 1);
}
}
}
int LCP(Trie *root, char* S){
if(S[0] == '\0'){
return 0;
}
if(root -> children[S[0] - FIRST_LETTER] == NULL or root -> children[S[0] - FIRST_LETTER] -> subcnt == 0){
return 0;
}
return 1 + LCP(root -> children[S[0] - FIRST_LETTER], S + 1);
}
void testcase(){
Trie* root = newTrie();
int q;
char s[21];
while(std :: cin >> q >> s){
if(q == 0){
Insert(root, s);
}
if(q == 1){
Erase(root, s);
}
if(q == 2){
std :: cout << Find(root, s) << '\n';
}
if(q == 3){
std :: cout << LCP(root, s) << '\n';
}
}
}
signed main(){
std :: ios_base :: sync_with_stdio(false);
std :: cin.tie(0);
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
testcase();
return 0;
}