Pagini recente » Cod sursa (job #2317151) | Cod sursa (job #358356) | Cod sursa (job #1423288) | Cod sursa (job #2498726) | Cod sursa (job #2808860)
#include <bits/stdc++.h>
using namespace std;
const int E = 26;
struct nod{
int cnt, sons;
nod *son[E];
nod()
{
cnt = sons = 0;
for (int i = 0; i < E; i++)
son[i] = 0;
}
};
nod *trie = new nod;
void update(nod *trie, char *s, int val, int n)
{
if (!n)
{
trie->cnt += val; ///am ajuns la final, facem nr aparitii
return;
}
if (trie->son[*s - 'a'] == 0) ///nu exista nicio continuare asa
{
trie->son[*s - 'a'] = new nod;
trie->sons++;
}
update(trie->son[*s - 'a'], s + 1, val, n - 1);
nod *fiu = trie->son[*s - 'a'];
if (val < 0 && (fiu->cnt) == 0 && fiu->sons == 0) //vedem daca a ajuns 0 si l stergem
{
delete(fiu);
trie->sons--;
trie->son[*s - 'a'] = 0;
}
}
int query(nod *trie, char *s, int n)
{
if (!n)
return trie->cnt;
if (trie->son[*s - 'a'] == 0)
return 0;
return query(trie->son[*s - 'a'], s + 1, n - 1);
}
int pref(nod *trie, char *s, int n, int l)
{
if (!n)
return l;
if (trie->son[*s - 'a'] == 0)
return l;
return pref(trie->son[*s-'a'], s + 1, n - 1, l + 1);
}
char s[E];
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
int op;
trie->cnt = 1;
while (cin >> op >> s)
{
int lit = strlen(s);
if (op == 0)
update(trie, s, 1, lit);
else
if (op == 1)
update(trie, s, -1, lit);
else
if (op == 2)
cout << query(trie, s, lit);
else
if (op == 3)
cout << pref(trie, s, lit, 0);
if (op > 1)
cout << '\n';
}
return 0;
}