Pagini recente » Cod sursa (job #1447691) | Cod sursa (job #1399956) | Cod sursa (job #939515) | Cod sursa (job #1235311) | Cod sursa (job #2665491)
#include <fstream>
#include <cstring>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
const int NMAX = 21;
const int SIGMAX = (int)('z' - 'a' + 1);
int Q, Type;
char S[NMAX];
struct Node
{
int val = 0;
int active_sons = 0;
Node *Next[SIGMAX];
Node ()
{
val = active_sons = 0;
for(int i = 0; i <= (int)('z' - 'a'); ++i)
Next[i] = nullptr;
}
} *Trie = new Node;
static inline void Update (Node *tree, char *word, int upd_val, int remaining_letters)
{
if(remaining_letters == 0)
{
(tree -> val) += upd_val;
return;
}
int Now = (int)(*word - 'a');
if((tree -> Next[Now]) == nullptr)
++(tree -> active_sons), (tree -> Next[Now]) = new Node;
Update((tree -> Next[Now]), word + 1, upd_val, remaining_letters - 1);
if(upd_val == -1)
{
Node *Son = (tree -> Next[Now]);
if((Son -> val) == 0 && (Son -> active_sons) == 0)
delete(Son), --(tree -> active_sons), (tree -> Next[Now]) = nullptr;
}
return;
}
static inline int Query (Node *tree, char *word, int remaining_letters)
{
if(remaining_letters == 0)
return (tree -> val);
int Now = (int)(*word - 'a');
if((tree -> Next[Now]) == nullptr)
return 0;
return Query((tree -> Next[Now]), word + 1, remaining_letters - 1);
}
static inline int LCP (Node *tree, char *word, int curr_level, int remaining_letters)
{
if(remaining_letters == 0)
return curr_level;
int Now = (int)(*word - 'a');
if((tree -> Next[Now]) == nullptr)
return curr_level;
return LCP((tree -> Next[Now]), word + 1, curr_level + 1, remaining_letters - 1);
}
int main()
{
f.tie(nullptr);
Trie -> val = 1; /// The Empty Set;
while(f >> Type >> (S + 1))
{
if(Type == 0)
Update(Trie, S + 1, 1, (int)strlen(S + 1));
else if(Type == 1)
Update(Trie, S + 1, -1, (int)strlen(S + 1));
else if(Type == 2)
g << Query(Trie, S + 1, (int)strlen(S + 1)) << '\n';
else
g << LCP(Trie, S + 1, 0, (int)strlen(S + 1)) << '\n';
}
return 0;
}