Pagini recente » Cod sursa (job #478321) | Cod sursa (job #2271678) | Cod sursa (job #1622135) | Cod sursa (job #488028) | Cod sursa (job #2198932)
#include <bits/stdc++.h>
using namespace std;
struct Trie{
int nrsons, words;
Trie *sons[27]={};
Trie (){
nrsons=0;
words=0;
}
};
Trie *T= new Trie;
void ins(Trie *nod, char *s)
{
if (!s[0])
{
nod->words++;
return;
}
int index=s[0]-'a'+1;
if (nod->sons[index]==0)
{
nod->sons[index]=new Trie;
nod->nrsons++;
}
ins(nod->sons[index], s+1);
}
bool del(Trie *nod, char*s)
{
if (!s[0])
nod->words--;
else
{
int index=s[0]-'a'+1;
if (del(nod->sons[index], s+1))
{
nod->sons[index]=0;
nod->nrsons--;
}
}
if (nod->words==0&&nod->nrsons==0&&nod!=T)
{
delete nod;
return 1;
}
return 0;
}
int cnt(Trie *nod, char *s)
{
if (!s[0])
return nod->words;
else
{
int index=s[0]-'a'+1;
if (!nod->sons[index])
return 0;
return cnt(nod->sons[index], s+1);
}
}
int lcpref(Trie *nod, char*s, int niv)
{
if (!s[0])
return niv;
else
{
int index=s[0]-'a'+1;
if (!nod->sons[index])
return niv;
return lcpref(nod->sons[index], s+1, niv+1);
}
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
ios_base::sync_with_stdio(0); cin.tie(0);
int op;
char cuv[21];
while (cin>>op>>cuv)
{
switch (op)
{
case 0: ins(T, cuv);
break;
case 1: del(T, cuv);
break;
case 2: cout<<cnt(T, cuv)<<'\n';
break;
case 3: cout<<lcpref(T, cuv, 0)<<'\n';
break;
}
}
return 0;
}