Pagini recente » Cod sursa (job #2242598) | Cod sursa (job #2279334) | Cod sursa (job #2987787) | Cod sursa (job #856476) | Cod sursa (job #2074993)
#include <cstdio>
using namespace std;
struct trie
{
int finish = 0, counter = 0;
struct trie *next[27] = {0};
};
trie *root = new trie;
void add(trie *& nod, char *s)
{
if(*s == 0)
{
nod -> finish++;
return;
}
if(nod -> next[*s - 'a'] == 0)
{
nod -> next[*s - 'a'] = new trie;
nod -> counter++;
}
add(nod -> next[*s - 'a'], s + 1);
}
int del(trie *& nod, char *s)
{
if(*s == 0)
nod -> finish--;
else
if(del(nod -> next[*s-'a'], s + 1))
{
nod -> counter--;
nod -> next[*s - 'a'] = 0;
}
if(nod -> counter == 0 && nod -> finish == 0 && nod != root)
{
delete nod;
return 1;
}
return 0;
}
int apcuv(trie *nod, char *s)
{
if(*s == 0)
return nod -> finish;
if(nod -> next[*s - 'a'])
return apcuv(nod -> next[*s - 'a'], s + 1);
return 0;
}
int prefix(trie *nod, char *s, int k)
{
if(*s == 0 || nod -> next[*s - 'a'] == 0)
return k;
return prefix(nod -> next[*s - 'a'], s + 1, k + 1);
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
int operatie;
char a[24];
while(scanf("%d %s\n", &operatie, a) == 2)
{
switch(operatie)
{
case 0: add(root,a); break;
case 1: del(root,a); break;
case 2: printf("%d\n", apcuv(root,a)); break;
case 3: printf("%d\n", prefix(root,a,0));
}
}
return 0;
}