Cod sursa(job #715989)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class trie
{
struct node
{
int nr_sons, nr_words;
node *sons[26];
node()
{
nr_sons = nr_words = 0;
for(int i = 0; i < 26; ++i)
sons[i] = NULL;
}
};
node *root;
public:
trie()
{
root = new node;
}
private:
void t_push(string str, node *here)
{
if(str.size() == 0)
{
here -> nr_words++;
return;
}
if(here -> sons[str[0] - 97] == NULL)
{
here -> sons[str[0] - 97] = new node;
here -> nr_sons++;
}
t_push(str.substr(1, str.size() - 1), here -> sons[str[0] - 97]);
}
bool t_pop(string str, node *here)
{
if(str.size() == 0)
here -> nr_words--;
else if(t_pop(str.substr(1, str.size() - 1), here -> sons[str[0] - 97]))
{
here -> sons[str[0] - 97] = NULL;
here -> nr_sons--;
}
/*This node is no more necessary - has 0 sons and 0 words ending in it.*/
if(here -> nr_words == 0 && here -> nr_sons == 0 && here != root)
{
delete here;
return true;
}
return false;
}
public:
void push(string str)
{
t_push(str, root);
}
void pop(string str)
{
t_pop(str, root);
}
int count(string str)
{
node *here = root;
int i = 0;
while(i < str.size())
{
if(here -> sons[str[i] - 97] == NULL)
return 0;
here = here -> sons[str[i] - 97];
++i;
}
return here -> nr_words;
}
int longest_prefix(string str)
{
int max = 0;
node *here = root;
int i = 0;
while (i < str.size())
{
if(here -> sons[str[i] - 97] == NULL)
return max;
here = here -> sons[str[i] - 97];
max++;
i++;
}
return max;
}
};
int main()
{
trie tr;
int op;
string str;
ifstream in("trie.in");
ofstream out("trie.out");
while(in >> op >> str)
{
switch(op)
{
case 0: tr.push(str); break;
case 1: tr.pop(str); break;
case 2: out << tr.count(str) << "\n"; break;
case 3: out << tr.longest_prefix(str) << "\n"; break;
}
}
in.close();
out.close();
return 0;
}