Pagini recente » Cod sursa (job #1745667) | Cod sursa (job #2614575) | Cod sursa (job #414318) | Cod sursa (job #2438971) | Cod sursa (job #237736)
Cod sursa(job #237736)
#include <cstdio>
#include <iostream>
const int maxa = 26;
FILE *in = fopen("trie.in","r"), *out = fopen("trie.out","w");
struct node
{
int answ, nrs;
node *next[maxa];
node()
{
answ = nrs = 0;
memset(next, 0, sizeof(next));
}
};
void insert(node *&t, char *word)
{
if ( *word == '\0' )
{
++t->answ;
return;
}
int val = *word - 'a';
if ( t->next[val] == 0 )
{
t->next[val] = new node;
++t->nrs;
}
insert(t->next[val], word+1);
}
int del(node *main, node *&t, char *word)
{
int val = *word - 'a';
if ( *word == '\0' )
--t->answ;
else if ( del(main, t->next[val], word+1) )
{
t->next[val] = 0;
--t->nrs;
}
if ( t->nrs == 0 && t->answ == 0 && t != main )
{
delete t;
return 1;
}
return 0;
}
int apar(node *&t, char *word)
{
if ( *word == '\0' )
return t->answ;
int val = *word -'a';
if ( t->next[val] )
return apar(t->next[val], word+1);
return 0;
}
int pref(node *&t, char *word)
{
if ( !t || *word == '\0' )
return 0;
int val = *word - 'a';
return 1 + pref(t->next[val], word+1);
}
int main()
{
int code;
char word[maxa];
node *trie = new node;
while ( fscanf(in, "%d %s", &code, word) == 2 )
{
if ( code == 0 )
insert(trie, word);
else if ( code == 1 )
del(trie, trie, word);
else if ( code == 2 )
fprintf(out, "%d\n", apar(trie, word));
else
fprintf(out, "%d\n", pref(trie, word) - 1);
}
return 0;
}