Pagini recente » Cod sursa (job #3180926) | Cod sursa (job #2662518) | Cod sursa (job #1716592) | Cod sursa (job #1315803) | Cod sursa (job #2437601)
#include <iostream>
#include<fstream>
#include<vector>
#include<string>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct node
{
char here;
int endings;
int occurences;
node*node_list[26];
node(char name)
{
endings=0;
here=name;
occurences=0;
for(int i=0; i<26; i++)
node_list[i]=nullptr;
}
~node()
{
for(int i=0; i<26; i++)
delete node_list[i];
}
bool contains(char to_check)
{
return node_list[to_check-'a']!=nullptr;
}
node*get_node(char name)
{
return node_list[name-'a'];
}
void add_node(char to_add)
{
node_list[to_add-'a']=new node(to_add);
}
};
node base(' ');
void add_string(const std::string&to_add)
{
node*here=&base;
char c;
for(int i=0; i<to_add.length(); i++)
{
c=to_add[i];
if(!here->contains(c))
{
here->add_node(c);
}
here=here->get_node(c);
here->occurences++;
}
here->endings++;
}
int get_ocurences(const std::string&to_check)
{
node*here=&base;
char c;
for(int i=0; i<to_check.length(); i++)
{
c=to_check[i];
if(!here->contains(c))
{
return 0;
}
here=here->get_node(c);
}
return here->endings;
}
int longest_prefix(const std::string&input)
{
node*here=&base;
char c;
for(int i=0; i<input.length(); i++)
{
c=input[i];
if(!here->contains(c))
{
return i;
}
here=here->get_node(c);
}
return input.length();
}
void erase_string(const std::string&to_check)
{
node*here=&base;
vector<node*> nodes;
for(int i=0; i<to_check.length(); i++)
{
here=here->get_node(to_check[i]);
here->occurences--;
nodes.push_back(here);
}
here->endings--;
node*last_node=&base;
for(int i=0; i<nodes.size(); i++)
{
if(nodes[i]->occurences==0)
{
last_node->node_list[nodes[i]->here-'a']=nullptr;
delete nodes[i];
break;
}
last_node=nodes[i];
}
}
void read()
{
int query;
string input;
while(in>>query>>input)
{
if(query==0)
{
add_string(input);
}
else if(query==1)
{
erase_string(input);
}
else if(query==2)
{
out<<get_ocurences(input)<<'\n';
}
else
out<<longest_prefix(input)<<'\n';
}
}
int main()
{
read();
return 0;
}