Pagini recente » Cod sursa (job #2878825) | Cod sursa (job #2368505) | Cod sursa (job #3256164) | Cod sursa (job #2051989) | Cod sursa (job #2886713)
#include <bits/stdc++.h>
using namespace std;
struct nod
{
int cnt, sons;
nod *son[26];
nod()
{
cnt = sons = 0;
for (int i = 0; i < 26; i++)
son[i] = 0;
}
};
void update(nod *trie, char *s, int val, int lit)
{
if (!lit)
{
trie->cnt += val;
return;
}
if (trie->son[*s - 'a'] == 0)
{
trie->sons++;
trie->son[*s - 'a'] = new nod;
}
update((trie->son[*s - 'a']), s + 1, val, lit - 1);
if (val < 0)
{
nod *fiu = trie->son[*s - 'a'];
if (fiu->cnt == 0 && fiu->sons == 0)
{
delete(fiu);
trie->sons--;
trie->son[*s - 'a'] = 0;
}
}
}
int query(nod *trie, char *s, int lit)
{
if (lit == 0)
return trie->cnt;
if (trie->son[*s - 'a'] == 0)
return 0;
query(trie->son[*s - 'a'], s + 1, lit - 1);
}
int prefix(nod *trie, char *s, int lvl, int lit)
{
if (!lit)
return lvl;
if (trie->son[*s - 'a'] == 0)
return lvl;
return prefix(trie->son[*s - 'a'], s + 1, lvl + 1, lit - 1);
}
nod *trie = new nod;
char s[50];
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 << prefix(trie, s, 0, lit);
if (op > 1)
cout << '\n';
}
return 0;
}