Pagini recente » Cod sursa (job #1322624) | Cod sursa (job #83140) | Cod sursa (job #1403543) | Cod sursa (job #570775) | Cod sursa (job #1579943)
#include <bits/stdc++.h>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct Trie
{
int cnt,nrs;
Trie *sons[30];
Trie()
{
cnt=nrs=0;
for(int i=0;i<30;i++)
sons[i]=NULL;
}
};
Trie *root= new Trie();
void ins(Trie *nod, char *s)
{
if(!*s)
{
nod->cnt++;
return;
}
int alfa=*s-'a';
if(nod->sons[alfa]==NULL)
{
nod->sons[alfa]=new Trie();
nod->nrs++;
}
ins(nod->sons[alfa],s+1);
}
int lung(Trie *nod, char *s)
{
if(!*s)
{
return 0;
}
int alfa=*s-'a';
if(nod->sons[alfa]==NULL)
return 0;
return lung(nod->sons[alfa],s+1)+1;
}
int freq(Trie *nod, char *s)
{
if(!*s)
{
return nod->cnt;
}
int alfa=*s-'a';
if(nod->sons[alfa]==NULL)
return 0;
return freq(nod->sons[alfa],s+1);
}
bool sterg(Trie *nod, char *s)
{
int alfa=*s-'a';
if(!*s)
{
nod->cnt--;
}
else
{
if(sterg(nod->sons[alfa],s+1))
{
nod->nrs--;
nod->sons[alfa]=NULL;
}
}
if(nod->nrs==0&&nod->cnt==0&&nod!=root)
{
delete nod;
return 1;
}
return 0;
}
int main()
{
int op;
char s[30];
while(in>>op>>s)
{
if(op==0)
{
ins(root,s);
}
if(op==1)
{
sterg(root,s);
}
if(op==2)
{
out<<freq(root,s)<<'\n';
}
if(op==3)
{
out<<lung(root,s)<<'\n';
}
}
return 0;
}