Pagini recente » Cod sursa (job #2345883) | Cod sursa (job #3237756) | Cod sursa (job #256904) | Cod sursa (job #1459071) | Cod sursa (job #1375975)
#include <cstring>
#include <fstream>
#include <algorithm>
using namespace std;
struct Trie
{
int ishere, endhere;
Trie *nxt[26];
Trie()
{
ishere = endhere = 0;
memset(nxt, 0, sizeof(nxt));
}
};
Trie *R = new Trie();
void add(Trie *T, char *now)
{
++T->ishere;
if (*now == 0)
{
++T->endhere;
return;
}
if (T->nxt[*now - 'a'] == 0)
T->nxt[*now - 'a'] = new Trie();
add(T->nxt[*now - 'a'], now + 1);
}
void rem(Trie *T, char *now)
{
--T->ishere;
if (*now == 0)
{
--T->endhere;
return;
}
rem(T->nxt[*now - 'a'], now + 1);
}
int freq(Trie *T, char *now)
{
if (*now == 0)
return T->endhere;
if (T->nxt[*now - 'a'] == 0)
return 0;
return freq(T->nxt[*now - 'a'], now + 1);
}
int pref(Trie *T, char *now)
{
if (T->ishere == 0)
return 0;
if (*now == 0)
return 1;
if (T->nxt[*now - 'a'] == 0)
return 1;
return 1 + pref(T->nxt[*now - 'a'], now + 1);
}
int main()
{
ifstream fin("trie.in");
ofstream fout("trie.out");
int type;
while (fin >> type)
{
char aux[24];
fin >> aux;
if (type == 0)
add(R, aux);
else if (type == 1)
rem(R, aux);
else if (type == 2)
fout << freq(R, aux) << '\n';
else if (type == 3)
fout << max(0, pref(R, aux) - 1) << '\n';
}
fin.close();
fout.close();
}