Pagini recente » Cod sursa (job #15765) | Cod sursa (job #3032736) | Cod sursa (job #2558238) | Cod sursa (job #798294) | Cod sursa (job #1948663)
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int N = 100;
class Nod{
public:
int nr;
Nod* vecini[230];
Nod()
{
nr = 0;
for(int i = 0; i < 230; 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);
}
}
bool isLeaf(Nod* x)
{
for(int i = 0; i < 230; i++)
{
if(x->vecini[i] != NULL)
{
return false;
}
}
return true;
}
void deleteNode(Nod*& x, int y)
{
if(y == lungimeCuvant - 1)
{
x->vecini[cuvant[y]]->nr--;
//if(isLeaf(x->vecini[cuvant[y]]) == true)
//{
// delete x->vecini[cuvant[y]];
// x->vecini[cuvant[y]] = NULL;
//}
}
else
{
deleteNode(x->vecini[cuvant[y]], y + 1);
if(isLeaf(x->vecini[cuvant[y]]) == true && x->vecini[cuvant[y]]->nr == 0)
{
delete x->vecini[cuvant[y]];
x->vecini[cuvant[y]] = NULL;
}
}
}
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()
{
char tmp[100];
tmp[0] = tmp[1] = 0;
fgets(tmp, 100, stdin);
if(tmp[1] == 0)
{
operatie = -1;
return;
}
char *p = strtok(tmp, ", \n");
sscanf(p, "%d", &operatie);
p = strtok(NULL, ", \n");
strcpy(cuvant, p);
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(cuvant[0] == 0)
{
return 0;
}
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;
}