Pagini recente » Cod sursa (job #1188733) | Cod sursa (job #1503598) | Cod sursa (job #2161258) | Cod sursa (job #109788) | Cod sursa (job #2632174)
#include <bits/stdc++.h>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
int x;
class nod{
public:
int nrfii,occ;
nod *p[30];
nod()
{
occ=nrfii=0;
for(int i=0;i<30;i++) p[i]=NULL;
//memset(p,0,sizeof(p));
}
};
void Add(nod* root,string word,int k)
{
if(k==word.size())
{
root->occ++;
return;
}
int idx=word[k]-'a';
if( root->p[idx] == NULL )
{
root->nrfii++;
nod* vertex=new nod;
root->p[idx]=vertex;
}
Add(root->p[idx],word,k+1);
}
nod* T;
bool Erase(nod* root,string word,int k)
{
if(k==word.size())
{
root->occ--;
if(root!=T && !root->occ && !root->nrfii)
{
delete root;
return 1;
}
else return 0;
}
int idx=word[k]-'a';
if( Erase( root->p[idx] , word, k+1) )
{
root->nrfii--;
root->p[idx]=0;
if( root!=T && !root->nrfii )
{
delete root;
return 1;
}
else return 0;
}
else return 0;
}
int Prefix(nod* root,string word,int k)
{
if(k==word.size()) return 0;
int idx=word[k]-'a';
if( root->p[idx] ) return 1+Prefix(root->p[idx],word,k+1);
else return 0;
}
int Occurances(nod* root,string word,int k)
{
if(k==word.size()) return root->occ;
int idx=word[k]-'a';
if( root->p[idx] ) return Occurances(root->p[idx],word,k+1);
else return 0;
}
int main()
{
nod* root=new nod;
T=root;
string S;
while(f>>x>>S)
{
if(x==0) Add(root,S,0);
else
if(x==1) Erase(root,S,0);
else
if(x==2) g<<Occurances(root,S,0)<<'\n';
else
g<<Prefix(root,S,0)<<'\n';
}
return 0;
}