Pagini recente » Cod sursa (job #1066861) | Cod sursa (job #3321942) | Cod sursa (job #1061064) | Cod sursa (job #2720220) | Cod sursa (job #3337821)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
string s;
int t;
struct trie
{
int children,words;
trie *child[30];
trie() {
words=children=0;
memset(child,0,sizeof(child));
}
}*nod,*rad;
void add(trie *nod,int poz)
{
if(poz>=s.size())
{
nod->words++;
return;
}
if(nod->child[s[poz]-'a']==0)
{
nod->child[s[poz]-'a']=new trie;
nod->children++;
}
add(nod->child[s[poz]-'a'],poz+1);
}
bool delete_conditions(trie *nod)
{
return (nod!=rad&&nod->children==0&&nod->words==0);
}
bool eliminate(trie* nod, int poz)
{
if(!nod) return false;
if(poz==s.size())
{
if(nod->words>0)
nod->words--;
}
else
{
if (nod->child[s[poz]-'a']&&eliminate(nod->child[s[poz]-'a'],poz+1))
{
delete nod->child[s[poz]-'a'];
nod->child[s[poz]-'a']=NULL;
nod->children--;
}
}
return (nod!= rad && nod->children == 0 && nod->words == 0);
}
int number(trie *nod,int poz)
{
if(poz==s.size())
{return nod->words;}
if(nod->child[s[poz]-'a']==0)
{
return 0;
}
return number(nod->child[s[poz]-'a'],poz+1);
}
int prefix(trie *nod,int poz)
{
if(nod==NULL)
return poz;
if(poz==s.size())
return poz;
if(nod->child[s[poz]-'a']==0)
return poz;
return prefix(nod->child[s[poz]-'a'],poz+1);
}
int main()
{
nod=new trie;
rad=nod;
while(fin>>t>>s)
{
if(t==0)
add(nod,0);
if(t==1)
eliminate(nod,0);
if(t==2)
fout<<number(nod,0)<<'\n';
if(t==3)
fout<<prefix(nod,0)<<'\n';
}
return 0;
}