Pagini recente » Cod sursa (job #3040823) | Cod sursa (job #3042187) | Cod sursa (job #160256) | Cod sursa (job #2943990) | Cod sursa (job #1355125)
#include <fstream>
#include <cstring>
using namespace std;
ifstream is ("trie.in");
ofstream os ("trie.out");
struct Node{
int NrAp, NrS;
Node *Son[27];
Node()
{
NrAp = NrS = 0;
memset(Son, 0, sizeof(Son));
}
};
Node *Root = new Node;
int OP;
char w[22];
void Add(char *w, Node *X);
bool Erase(char *w, Node *X);
int Count(char *w, Node *X);
int Prefix(char *w, Node *X, int k);
int main()
{
while (is >> OP >> w)
{
if (OP == 0)
Add(w, Root);
if (OP == 1)
Erase(w, Root);
if (OP == 2)
os << Count(w, Root) << '\n';
if (OP == 3)
os << Prefix(w, Root, 0) << '\n';
}
}
void Add(char *w, Node *X)
{
if (*w == 0)
{
X->NrAp++;
return;
}
if (X->Son[*w - 'a'] == 0)
{
X->Son[*w - 'a'] = new Node;
X->NrS++;
}
Add(w+1, X->Son[*w - 'a']);
}
bool Erase(char *w, Node *X)
{
if (*w == 0)
X->NrAp--;
else
if (Erase(w+1, X->Son[*w - 'a']) == 1)
{
X->NrS--;
X->Son[*w - 'a'] = 0;
}
if (X != Root && X->NrS == 0 && X->NrAp == 0)
{
delete X;
return 1;
}
return 0;
};
int Count(char *w, Node *X)
{
if (*w == 0)
return X->NrAp;
if (X->Son[*w - 'a'])
return Count(w+1, X->Son[*w - 'a']);
return 0;
};
int Prefix(char *w, Node *X, int k)
{
if (*w == 0)
return k;
if (X->Son[*w - 'a'])
return Prefix(w+1, X->Son[*w - 'a'], k+1);
return k;
};