Pagini recente » Cod sursa (job #993432) | Cod sursa (job #1772593) | Cod sursa (job #2811331) | Cod sursa (job #252440) | Cod sursa (job #3149664)
#include <bits/stdc++.h>
using namespace std;
const int SIGMA = 30;
int t,tc;
string str;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct TrieNode {
int cnt = 0;
TrieNode * father;
TrieNode * children[SIGMA] = {nullptr};
} root;
void add(string str){
TrieNode * ptr = &root;
for(int i = 0; i < str.size(); i++){
int ch = str[i]-'a';
if(ptr->children[ch] == nullptr){
TrieNode * new_branch = new TrieNode;
new_branch->father = ptr;
ptr->children[ch] = new_branch;
ptr = new_branch;
}else{
ptr = ptr->children[ch];
}
}
ptr->cnt++;
}
bool has_children(TrieNode * nod){
for(int i = 0; i < SIGMA; i++){
if(nod->children[i] != nullptr){
return true;
}
}
return false;
}
void prune(string str){
TrieNode * ptr = &root;
for(int i = 0; i < str.size(); i++){
int ch = str[i]-'a';
ptr = ptr->children[ch];
}
ptr->cnt--;
int pos = str.size()-1;
if(ptr->cnt == 0){
while(ptr != &root && !has_children(ptr)){
TrieNode * tata = ptr->father;
ptr = tata;
delete ptr->children[str[pos]-'a'];
ptr->children[str[pos]-'a'] = nullptr;
if(ptr->cnt != 0){
break;
}
pos--;
}
}
}
int get_cnt(string str){
TrieNode * ptr = &root;
for(int i = 0; i < str.size(); i++){
int ch = str[i]-'a';
if(ptr->children[ch] != nullptr){
ptr = ptr->children[ch];
}else{
return 0;
}
}
return ptr->cnt;
}
int lp(string str){
TrieNode * ptr = &root;
int ans = 0;
for(int i = 0; i < str.size(); i++){
int ch = str[i]-'a';
if(ptr->children[ch] != nullptr){
ptr = ptr->children[ch];
ans++;
}else{
break;
}
}
return ans;
}
int main()
{
while(fin >> t >> str){
++tc;
if(t == 0){
add(str);
}else if(t == 1){
prune(str);
}else if(t == 2){
fout << get_cnt(str) << "\n";
}else if(t == 3){
fout << lp(str) << "\n";
}
}
return 0;
}