Pagini recente » Cod sursa (job #534587) | Cod sursa (job #117459) | Cod sursa (job #844156) | Cod sursa (job #464705) | Cod sursa (job #711171)
Cod sursa(job #711171)
#include <iostream>
#include <fstream>
using namespace std;
class trie
{
struct node
{
int n_sons, n_words;
node *sons[26];
node()
{
n_sons = n_words = 0;
for(int i = 0; i < 26; ++i)
sons[i] = NULL;
}
};
node *root;
public:
trie()
{
root = new node;
}
void true_push(char *str, node *here)
{
if(*str == NULL)
{
here->n_words++;
return;
}
if(here->sons[*str-97] == NULL)
{
here->sons[*str-97] = new node;
here->n_sons++;
}
true_push(str + 1, here->sons[*str-97]);
}
void push(char *str)
{
true_push(str, root);
}
bool true_pop(char *str, node *here)
{
if(*str == NULL)
here->n_words--;
else if(true_pop(str+1, here->sons[*str-97]))
{
here->sons[*str-97] = NULL;
here->n_sons--;
}
if(here->n_words == 0 && here->n_sons == 0 && here!=NULL)
{
delete here;
return true;
}
return false;
}
void pop(char *str)
{
true_pop(str, root);
}
int count(char *str)
{
node *here = root;
while(*str)
{
if(here->sons[*str - 97] == NULL)
return 0;
here = here -> sons[*str - 97];
++str;
}
return here -> n_words;
}
int max_pref(char *str)
{
int max = 0;
node *here = root;
while(*str)
{
if(here -> sons[*str - 97] == NULL)
return max;
here = here -> sons[*str - 97];
++max;
++str;
}
return max;
}
};
trie tr;
int main()
{
int n;
char str[21];
ifstream in("trie.in");
ofstream out("trie.out");
while(in >> n >> str)
{
switch(n)
{
case 0: tr.push(str); break;
case 1: tr.pop(str); break;
case 2: out << tr.count(str) << "\n"; break;
case 3: out << tr.max_pref(str) << "\n"; break;
}
}
in.close();
out.close();
return 0;
}