Pagini recente » Istoria paginii utilizator/uaic_onesim_popoiu_tucar | Cod sursa (job #2142276) | Istoria paginii planificare/asociatia-infoarena | Cod sursa (job #144788) | Cod sursa (job #227317)
Cod sursa(job #227317)
Utilizator |
Paul-Dan Baltescu pauldb |
Data |
4 decembrie 2008 02:36:26 |
Problema |
Trie |
Scor |
Ascuns |
Compilator |
cpp |
Status |
done |
Runda |
|
Marime |
1.62 kb |
#include <stdio.h>
#include <string>
#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;
}