Pagini recente » Cod sursa (job #2845823) | Cod sursa (job #277138) | Cod sursa (job #1537407) | Cod sursa (job #3207258) | Cod sursa (job #710121)
Cod sursa(job #710121)
#include <cstdio>
#include <cstring>
class trie
{
class node
{
int count, prefs;
node * parent;
node * sons[26];
node()
{
count = 0;
prefs = 0;
parent = NULL;
memset(sons,NULL,sizeof(sons));
}
friend class trie;
};
int index(char c) const { return c - 'a'; }
node * root;
public:
trie() : root(new node)
{
}
void insert(const char * x)
{
node * p = root;
for(const char * c = x; *c != '\0'; ++c)
{
if(p->sons[index(*c)] != NULL)
p = p->sons[index(*c)];
else
{
node * q = p;
p = p->sons[index(*c)] = new node;
q->sons[index(*c)] = p;
p->parent = q;
}
p-> prefs ++;
}
p->count ++;
}
void remove(const char * x)
{
if(count(x) == 0)
return;
node * p = root;
const char * c = x;
for( ;*c != '\0'; ++c)
{
p = p->sons[index(*c)];
}
--c;
p->count --;
for(; c != x; --c)
{
p->prefs --;
if(p->prefs == 0)
{
node * q = p;
p->parent->sons[index(*c)] = NULL;
p = p->parent;
q->parent = NULL;
delete q;
}
else p = p->parent;
}
}
int count(const char *x) const
{
node * p = root;
for(const char * c = x; *c != '\0' && p != NULL; ++c)
{
p = p->sons[index(*c)];
}
if(p == NULL)
return 0;
else return p->count;
}
int longestPrefix(const char *x) const
{
node * p = root;
int k = 0;
for(const char * c = x; *c != '\0' && p != NULL; ++c)
{
p = p->sons[index(*c)];
if(p != NULL)
++k;
}
return k;
}
};
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
trie T;
char code;
char string[20 + 1];
for(;scanf("%[0-3]%*[^a-z]%[a-z]%*[^0-3]",&code,string) == 2;)
{
switch(code)
{
case '0':
T.insert(string);
break;
case '1':
T.remove(string);
break;
case '2':
printf("%d\n",T.count(string));
break;
case '3':
printf("%d\n",T.longestPrefix(string));
break;
default:
break;
}
}
return 0;
}