Pagini recente » Cod sursa (job #2327888) | Cod sursa (job #569919) | Cod sursa (job #2838223) | Cod sursa (job #2640901) | Cod sursa (job #2483547)
#include <fstream>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
struct trie {
trie *next[26];
int paths;
int ends;
trie() {
{
next[0] = NULL;
next[1] = NULL;
next[2] = NULL;
next[3] = NULL;
next[4] = NULL;
next[5] = NULL;
next[6] = NULL;
next[7] = NULL;
next[8] = NULL;
next[9] = NULL;
next[10] = NULL;
next[11] = NULL;
next[12] = NULL;
next[13] = NULL;
next[14] = NULL;
next[15] = NULL;
next[16] = NULL;
next[17] = NULL;
next[18] = NULL;
next[19] = NULL;
next[20] = NULL;
next[21] = NULL;
next[22] = NULL;
next[23] = NULL;
next[24] = NULL;
next[25] = NULL;
}
paths = 1;
ends = 0;
}
};
void add(trie *node, string &str){
size_t x = 0;
while(x < str.size()){
if(node->next[str[x] - 'a'] == NULL)
node->next[str[x] - 'a'] = new trie();
else
node->next[str[x] - 'a']->paths++;
node = node->next[str[x] - 'a'];
x++;
}
node->ends++;
}
void rem(trie *node, string &str){
size_t x = 0;
while(x < str.size()){
if(node->next[str[x] - 'a'] == NULL){
size_t y = 0;
while(y < x){
node = node->next[str[x] - 'a'];
node->paths++;
y++;
}
return;
}
node = node->next[str[x] - 'a'];
node->paths--;
x++;
}
node->ends--;
}
int trace_full(trie *node, string &str){
size_t x = 0;
while(x < str.size()){
if(node->next[str[x] - 'a'] == NULL)
return 0;
node = node->next[str[x] - 'a'];
x++;
}
return node->ends;
}
int trace_shared(trie *node, string &str){
trie *node_ = node;
size_t x = 0;
int len = 0;
while(x < str.size()){
if(node->next[str[x] - 'a'] == NULL)
return len;
if(node->next[str[x] - 'a']->paths < 1)
return len + (node->next[str[x] - 'a']->paths > 0);
node = node->next[str[x] - 'a'];
len++;
x++;
}
x = 0;
len = 0;
node = node_;
while(x < str.size()){
if(node->next[str[x] - 'a']->paths < 2)
return len;
node = node->next[str[x] - 'a'];
x++;
len++;
}
return len;
}
int main() {
trie *root = new trie;
int req;
string in;
while(cin>>req){
cin>>in;
if(req == 0)
add(root, in);
else if(req == 1)
rem(root, in);
else if(req == 2)
cout<<trace_full(root, in)<<'\n';
else
cout<<trace_shared(root, in)<<'\n';
}
return 0;
}