Pagini recente » Cod sursa (job #2561698) | Cod sursa (job #1044984) | Cod sursa (job #3153325) | Cod sursa (job #1188755) | Cod sursa (job #2433064)
#include <iostream>
#include<fstream>
#include<string>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
int get_offset(char to_get)
{
return to_get-'a';
}
class node
{
public:
const char node_character;
node* child_nodes[26];
int how_many_here;
int prefix_of;
bool does_contain(char node)
{
return child_nodes [get_offset(node)]!=nullptr;
}
void add_node(char newnode)
{
if(child_nodes[get_offset(newnode)]==nullptr)
{
node* newp=new node(newnode);
child_nodes[get_offset(newnode)]=newp;
}
}
node(char nd):node_character(nd)
{
how_many_here=0;
prefix_of=0;
for(int i=0; i<26; i++)
child_nodes[i]=nullptr;
}
~node()
{
for(int i=0; i<26; i++)
delete child_nodes[i];
}
};
class trie
{
public:
node base_node;
trie():base_node(' ')
{
}
void add_string(const string to_add)
{
node* current_node=&base_node;
for(int i=0; i<to_add.length(); i++)
{
if(!current_node->does_contain(to_add[i]))
{
current_node->add_node(to_add[i]);
}
current_node->prefix_of++;
current_node=current_node->child_nodes[get_offset(to_add[i])];
}
current_node->how_many_here++;
}
void erase_string(const std::string to_delete)
{
node* current_node=&base_node;
for(int i=0; i<to_delete.length(); i++)
{
current_node->prefix_of--;
current_node=current_node->child_nodes[get_offset(to_delete[i])];
}
current_node->how_many_here--;
}
node* get_root(const string prefix)
{
node* current_node=&base_node;
for(int i=0; i<prefix.length(); i++)
{
if(!current_node->does_contain(prefix[i]))
{
return nullptr;
}
current_node=current_node->child_nodes[get_offset(prefix[i])];
}
return current_node;
}
int get_longest_common_prefix_of_string(const string prefix)
{
node* current_node=&base_node;
int maxx=0;
for(int i=0; i<prefix.length(); i++)
{
if(current_node->does_contain(prefix[i]))
{
current_node=current_node->child_nodes[get_offset(prefix[i])];
if(current_node->prefix_of==0)
{
return i+1;
}
}
else
return i;
}
return 0;
}
};
int main()
{
trie test_trie;
int f;
string input;
while(in>>f>>input)
{
switch(f)
{
case 0:
{
test_trie.add_string(input);
}
break;
case 1:
{
test_trie.get_root(input)->how_many_here--;
}
break;
case 2:
{
node*to_get=test_trie.get_root(input);
if(to_get)
out<<to_get->how_many_here<<endl;
else
out<<0<<endl;
}
break;
case 3:
out<<test_trie.get_longest_common_prefix_of_string(input)<<endl;
break;
}
}
return 0;
}