Pagini recente » Cod sursa (job #724696) | Cod sursa (job #2325930) | Cod sursa (job #2723268) | Cod sursa (job #454681) | Cod sursa (job #2433099)
#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++;
current_node->prefix_of++;
}
void erase_string(const std::string to_delete)
{
node* current_node=&base_node;
current_node->prefix_of--;
for(int i=0; i<to_delete.length(); i++)
{
current_node=current_node->child_nodes[get_offset(to_delete[i])];
current_node->prefix_of--;
}
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])];
}
else
return i;
if(current_node->prefix_of==0)
{
return i;
}
}
return prefix.length();
}
};
int main()
{
trie test_trie;
int f;
string input;
int a,b;
while(in>>f>>input)
{
switch(f)
{
case 0:
{
test_trie.add_string(input);
}
break;
case 1:
{
test_trie.erase_string(input);
}
break;
case 2:
{
a++;
node*to_get=test_trie.get_root(input);
if(to_get!=nullptr)
out<<to_get->how_many_here<<endl;
else
out<<0<<endl;
}
break;
case 3:
b++;
out<<test_trie.get_longest_common_prefix_of_string(input)<<endl;
break;
}
}
cout<<a<<" "<<b<<endl;
return 0;
}