Pagini recente » Monitorul de evaluare | Cod sursa (job #1435708) | Cod sursa (job #1804664) | Cod sursa (job #1220137) | Cod sursa (job #2137332)
#include <bits/stdc++.h>
using namespace std;
struct Trie{
int nrsons, words;
Trie *sons[26]={};
Trie (){
nrsons=0;
words=0;
}
};
Trie *T= new Trie;
void ins(Trie *nod, char *s)
{
if (!s[0])
{
nod->words++;
return;
}
if (nod->sons[s[0]-'a']==0)
{
nod->sons[s[0]-'a']=new Trie;
nod->nrsons++;
}
ins(nod->sons[s[0]-'a'], s+1);
}
bool del(Trie *nod, char*s)
{
if (!s[0])
nod->words--;
else
{
if (del(nod->sons[s[0]-'a'], s+1))
{
nod->sons[s[0]-'a']=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
{
if (!nod->sons[s[0]-'a'])
return 0;
return cnt(nod->sons[s[0]-'a'], s+1);
}
}
int lcpref(Trie *nod, char*s, int niv)
{
if (!s[0])
return niv;
else
{
if (!nod->sons[s[0]-'a'])
return niv;
return lcpref(nod->sons[s[0]-'a'], s+1, niv+1);
}
}
int main()
{
ifstream cin("trie.in");
ofstream cout ("trie.out");
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;
}