Pagini recente » Cod sursa (job #17213) | Rating Popescu Ioana (shpif2005) | Cod sursa (job #510913) | Cod sursa (job #1123965) | Cod sursa (job #841864)
Cod sursa(job #841864)
#include <cstdio>
const int SIZE('z' - 'a' + 1);
struct trie
{
int prefix;
int words;
struct trie *node [SIZE];
};
inline void initialize (struct trie *&vertex)
{
vertex = new struct trie( );
}
inline void insert (struct trie *&vertex, const char *word)
{
if (!vertex)
initialize(vertex);
struct trie *iterator(vertex);
while (*word)
{
++iterator->prefix;
if (!iterator->node[*word - 'a'])
initialize(iterator->node[*word - 'a']);
iterator = iterator->node[*word - 'a'];
++word;
}
++iterator->prefix;
++iterator->words;
}
void remove (struct trie *&vertex, const char *word)
{
if (!*word)
{
--vertex->prefix;
--vertex->words;
if (!vertex->words)
{
delete vertex;
vertex = 0;
}
return;
}
remove(vertex->node[*word - 'a'],word + 1);
--vertex->prefix;
if (!vertex->prefix)
{
delete vertex;
vertex = 0;
}
}
inline int words (const struct trie *vertex, const char *word)
{
while (*word)
{
if (!vertex)
return 0;
vertex = vertex->node[*word - 'a'];
++word;
}
return vertex->words;
}
inline int prefix (const struct trie *vertex, const char *word)
{
if (!vertex)
return 0;
int length(0);
while (*word && vertex->node[*word - 'a'])
{
vertex = vertex->node[*word - 'a'];
++word;
++length;
}
return length;
}
int main (void)
{
std::freopen("trie.in","r",stdin);
std::freopen("trie.out","w",stdout);
struct trie *data(0);
char s [SIZE];
std::gets(s);
while (!std::feof(stdin))
{
if (*s == '0')
insert(data,s + 2);
else if (*s == '1')
remove(data,s + 2);
else if (*s == '2')
std::printf("%d\n",words(data,s + 2));
else
std::printf("%d\n",prefix(data,s + 2));
std::gets(s);
}
std::fclose(stdin);
std::fclose(stdout);
return 0;
}