Pagini recente » Cod sursa (job #3170657) | Cod sursa (job #1055266) | Cod sursa (job #3286813) | Cod sursa (job #1054854) | Cod sursa (job #638600)
Cod sursa(job #638600)
#include <stdio.h>
#include <assert.h>
#include <string>
#include <cstring>
#define sigma 26
#define maxl 25
struct node
{
int x, y;
node *f[sigma];
node ()
{
x = y = 0;
memset(f, 0, sizeof(f));
}
};
node *R;
int l;
char cuv[maxl];
void addTrie(char cuv[])
{
int i, next;
node *stare = R;
for (i=0; i<l; i++)
{
next = cuv[i] - 'a';
if (stare -> f[next] == NULL) stare -> f[next] = new node;
stare = stare -> f[next];
stare -> y++;
}
stare -> x++;
}
void eraseTrie(char cuv[])
{
int i, next;
node *stare = R, *aux;
for (i=0; i<l; i++)
{
next = cuv[i] - 'a';
assert(stare -> f[next] != NULL);
aux = stare;
stare = stare -> f[next];
stare -> y--;
if (aux -> y == 0) delete aux;
else if (stare -> y == 0) aux -> f[next] = NULL;
}
stare -> x--;
assert(stare -> x >= 0);
if (stare -> y == 0) delete stare;
}
int countWords(char cuv[])
{
int i, next;
node *stare = R;
for (i=0; i<l; i++)
{
next = cuv[i] - 'a';
if (stare -> f[next] == NULL) return 0;
stare = stare -> f[next];
}
return stare -> x;
}
int longestPrefix(char cuv[])
{
int i, next;
node *stare = R;
for (i=0; i<l; i++)
{
next = cuv[i] - 'a';
if (stare -> f[next] == NULL) break;
stare = stare -> f[next];
}
return i;
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
int tip;
R = new node;
R -> y = 1;
while (!feof(stdin))
{
scanf("%d %s ", &tip, cuv);
assert(0<=tip && tip<=3);
l = strlen(cuv);
assert(1<=l && l<=20);
if (tip == 0) addTrie(cuv);
if (tip == 1) eraseTrie(cuv);
if (tip == 2) printf("%d\n", countWords(cuv));
if (tip == 3) printf("%d\n", longestPrefix(cuv));
}
return 0;
}