Pagini recente » Cod sursa (job #487418) | Cod sursa (job #2751220) | Cod sursa (job #892080) | Cod sursa (job #1954103) | Cod sursa (job #2277587)
#include <cstdio>
#include <cstring>
#include <cctype>
#define FILE_IN "trie.in"
#define FILE_OUT "trie.out"
struct trie
{
char length, children;
trie *next[32];
trie()
{
memset(next, 0, sizeof(next));
length = children = 0;
}
} *start;
void trie_insert(trie*, char*);
bool trie_delete(trie*, char*);
int trie_count(trie*, char*);
int trie_prefix(trie*, char*, int);
int main()
{
freopen(FILE_IN, "r", stdin);
freopen(FILE_OUT, "w", stdout);
start = new trie;
char str[32];
while(fgets(str, 32, stdin))
{
switch(str[0])
{
case '0': trie_insert(start, str+2); break;
case '1': trie_delete(start, str+2); break;
case '2': printf("%i\n", trie_count(start, str+2)); break;
case '3': printf("%i\n", trie_prefix(start, str+2, 0)); break;
default: return 0;
}
}
return 0;
}
int trie_prefix(trie *nod, char *str, int pos)
{
if(!isalpha(*str) || !nod->next[*str - 'a'])
return pos;
return trie_prefix(nod->next[*str - 'a'], str+1, pos+1);
}
int trie_count(trie *nod, char *str)
{
if(!isalpha(*str))
return nod->length;
if(nod->next[*str - 'a'])
return trie_count(nod->next[*str - 'a'], str+1);
return 0;
}
bool trie_delete(trie *nod, char *str)
{
if(!isalpha(*str))
nod->length--;
else if(trie_delete(nod->next[*str - 'a'], str+1))
{
nod->children--;
nod->next[*str - 'a'] = 0;
}
if(nod->children == 0 && nod->length == 0 && nod != start)
{
delete nod;
return true;
}
return false;
}
void trie_insert(trie *nod, char *str)
{
if(!isalpha(*str))
{
nod->length++;
return;
}
if(!nod->next[*str - 'a'])
{
nod->next[*str - 'a'] = new trie;
nod->children++;
}
trie_insert(nod->next[*str - 'a'], str+1);
}