Pagini recente » Cod sursa (job #73867) | Cod sursa (job #1104880) | Cod sursa (job #309065) | Cod sursa (job #573006) | Cod sursa (job #2447066)
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
const int SIZEOF_ALPHABET=26;
ifstream cin ("trie.in");
ofstream cout ("trie.out");
struct Node
{
int for_how_many_is_leaf;
int for_how_many_passes;
Node* point_to[SIZEOF_ALPHABET];
Node()
{
for_how_many_is_leaf = 0;
for_how_many_passes = 0;
memset(point_to, NULL, sizeof(point_to));
}
};
Node* root = new Node();
namespace Node_actions
{
void insert(string &s)
{
auto current_node = root;
for(auto current_character: s)
{
int where_to=current_character-'a';
if(current_node->point_to[where_to] == nullptr)
current_node->point_to[where_to] = new Node();
current_node->for_how_many_passes += 1;
current_node = current_node->point_to[where_to];
}
current_node->for_how_many_passes += 1;
current_node->for_how_many_is_leaf += 1;
}
void remove(Node *¤t_node, string &s, int current_index)
{
current_node->for_how_many_passes -= 1;
if (current_index == s.size()) {
current_node->for_how_many_is_leaf -= 1;
if (current_node->for_how_many_passes == 0)
delete current_node, current_node = nullptr;
return;
}
int where_to = s[current_index] - 'a';
remove(current_node -> point_to[where_to], s, current_index + 1);
if (current_node->for_how_many_passes == 0 and current_node != root)
delete current_node, current_node = nullptr;
}
int number_of_words(string &s)
{
auto current_node = root;
for(auto current_character: s)
{
int where_to = current_character-'a';
if(current_node->point_to[where_to] == nullptr)
return 0;
current_node = current_node->point_to[where_to];
}
return current_node->for_how_many_is_leaf;
}
int longest_common_prefix(string &s)
{
auto current_node = root;
int answer=0;
for(auto current_character: s)
{
int where_to = current_character - 'a';
if(current_node->point_to[where_to] == nullptr)
return answer;
current_node = current_node->point_to[where_to];
++answer;
}
return answer;
}
}
int main()
{
int type;
string s;
while(cin>>type>>s)
{
switch(type)
{
case 0: Node_actions :: insert(s);
break;
case 1: Node_actions :: remove(root, s, 0);
break;
case 2: cout<<Node_actions :: number_of_words(s)<<'\n';
break;
case 3: cout<<Node_actions :: longest_common_prefix(s)<<'\n';
}
}
return 0;
}