Pagini recente » Cod sursa (job #1753464) | Cod sursa (job #216922) | Cod sursa (job #2704731) | Cod sursa (job #237952) | Cod sursa (job #2050112)
#include <fstream>
#include <string>
using namespace std;
struct TRIE
{
int f,nre;
TRIE *E[26];
TRIE()
{
f=nre=0;
for(int i=0;i<26;i++)
E[i]=0;
}
};
ifstream fi("trie.in");
ofstream fo("trie.out");
int tip;
string s;
TRIE *T=new TRIE;
void adauga(TRIE *nod,string s)
{
if(s.empty())
{
nod->f++;
return;
}
if(!nod->E[s[0]-'a'])
{
nod->E[s[0]-'a']=new TRIE;
nod->nre++;
}
int x=s[0]-'a';
s.erase(s.begin());
adauga(nod->E[x],s);
}
int sterge( TRIE *nod, string s )
{
int x;
if(s.empty())
nod->f --;
else
{
if(!s.empty())
{
x=s[0]-'a';
s.erase(s.begin());
}
if( sterge( nod->E[x], s) )
{
nod->E[x] = 0;
nod->nre --;
}
}
if( nod->f == 0 && nod->nre == 0 && nod != T )
{
delete nod;
return 1;
}
return 0;
}
int nraparitii(TRIE *nod,string s)
{
if(s.empty())
return nod->f;
int x=s[0]-'a';
s.erase(s.begin());
if(nod->E[x])
return nraparitii(nod->E[x],s);
return 0;
}
int nrprefixe(TRIE *nod,string s,int k)
{
int x=s[0]-'a';
s.erase(s.begin());
if(s.empty()|| !nod->E[x])
return k;
return nrprefixe(nod->E[x],s,k+1);
}
int main()
{
while(fi>>tip)
{
fi>>s;
if(tip==0)
adauga(T,s);
else if(tip==1)
sterge(T,s);
else if(tip==2)
fo<<nraparitii(T,s)<<"\n";
else
fo<<nrprefixe(T,s,0)<<"\n";
}
fi.close();
fo.close();
return 0;
}