Pagini recente » Cod sursa (job #2449581) | Cod sursa (job #1383420) | Cod sursa (job #2629901) | Cod sursa (job #909956) | Cod sursa (job #2496581)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Node
{
int cnt, nrSons;
Node *sons[26];
Node()
{
cnt = 0;
nrSons = 0;
for (int i = 0; i < 26; i++)
sons[i] = NULL;
}
};
Node *Root = new Node;
int tip;
char s[25];
void Add(Node *T, char *s)
{
if (s[0] == '\0')
{
T->cnt++;
return;
}
else if (T->sons[s[0] - 'a'] == NULL)
{
T->nrSons++;
T->sons[s[0] - 'a'] = new Node;
}
Add(T->sons[s[0] - 'a'], s + 1);
}
int Remove(Node *T, char *s)
{
if (s[0] == '\0')
T->cnt--;
else if (Remove(T->sons[s[0] - 'a'], s + 1))
{
T->sons[s[0] - 'a'] = NULL;
T->nrSons--;
}
if (T->cnt == 0 && T->nrSons == 0 && T != Root)
{
delete T;
return 1;
}
return 0;
}
int Count(Node *T, char *s)
{
if (s[0] == '\0')
return T->cnt;
else if (T->sons[s[0] - 'a'] == NULL)
return 0;
else
return Count(T->sons[s[0] - 'a'], s + 1);
}
int MaxPre(Node *T, char *s)
{
if (s[0] == '\0')
return 1;
if (T->sons[s[0] - 'a'])
return 1 + MaxPre(T->sons[s[0] - 'a'], s + 1);
else
return 0;
}
int main()
{
while (fin >> tip >> s)
{
if (tip == 0)
Add(Root, s);
else if (tip == 1)
Remove(Root, s);
else if (tip == 2)
fout << Count(Root, s) << "\n";
else
fout << MaxPre(Root, s) << "\n";
}
return 0;
}