Pagini recente » Cod sursa (job #2031632) | Cod sursa (job #1821558) | Cod sursa (job #2466256) | Cod sursa (job #610833) | Cod sursa (job #1948474)
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 100;
class Nod{
public:
int nr;
Nod* vecini[27];
Nod()
{
nr = 0;
for(int i = 0; i < 27; i++)
{
vecini[i] = NULL;
}
}
};
int operatie;
char cuvant[N];
int lungimeCuvant;
Nod* root;
void insertNode(Nod*& x, int y)
{
if(x->vecini[cuvant[y]] == NULL)
{
x->vecini[cuvant[y]] = new Nod();
}
if(y == lungimeCuvant - 1)
{
x->vecini[cuvant[y]]->nr++;
}
else
{
insertNode(x->vecini[cuvant[y]], y + 1);
}
}
void deleteNode(Nod*& x, int y)
{
if(y == lungimeCuvant - 1)
{
if(x->vecini[cuvant[y]] == NULL)
{
return;
}
x->vecini[cuvant[y]]->nr--;
//if(x->vecini[cuvant[y]]->nr == 0)
//{
// delete x->vecini[cuvant[y]];
// x->vecini[cuvant[y]] = NULL;
//}
}
else
{
deleteNode(x->vecini[cuvant[y]], y + 1);
}
}
int numberOfAparitions(Nod*& x, int y)
{
if(x->vecini[cuvant[y]] == NULL)
{
return 0;
}
else
{
if(y == lungimeCuvant - 1)
{
return x->vecini[cuvant[y]]->nr;
}
else
{
return numberOfAparitions(x->vecini[cuvant[y]], y + 1);
}
}
}
int lungimePrefix(Nod*& x, int y)
{
if(y == lungimeCuvant)
{
return y;
}
if(x->vecini[cuvant[y]] == NULL)
{
return y;
}
else
{
return lungimePrefix(x->vecini[cuvant[y]], y + 1);
}
}
void citire()
{
scanf("%d %s\n", &operatie, &cuvant);
lungimeCuvant = strlen(cuvant);
for(int i = 0; i < lungimeCuvant; i++)
{
cuvant[i] -= 'a';
}
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
root = new Nod();
while(!feof(stdin))
{
citire();
if(operatie == 0)
{
insertNode(root, 0);
}
else if(operatie == 1)
{
deleteNode(root, 0);
}
else if(operatie == 2)
{
printf("%d\n", numberOfAparitions(root, 0));
}
else if(operatie == 3)
{
printf("%d\n", lungimePrefix(root, 0));
}
}
return 0;
}