Pagini recente » Cod sursa (job #2262651) | Cod sursa (job #391319) | Cod sursa (job #2455735) | Cod sursa (job #3252880) | Cod sursa (job #2422390)
#include <iostream>
#include <fstream>
#define ch (c[ind] - 'a')
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
char c[26];
int in;
struct nod
{
int pre=0;
int app=0;
nod* v[26]={NULL};
};
inline void push( nod* root,int ind)
{
if(root->v[ch]==NULL)
root->v[ch]= new nod;
root->v[ch]->pre++;
if(c[ind+1]!='\0')
push(root->v[ch],ind+1);
else
root->v[ch]->app++;
// std::cout<<c<<" "<<(char)(ch+'a')<<" "<<root->v[ch]->pre<<" "<<root->v[ch]->app<<"\n";
}
inline void erase(nod* root, int ind)
{
root->v[ch]->pre--;
if(c[ind+1]=='\0')
root->v[ch]->app--;
else
erase(root->v[ch],ind+1);
if(root->v[ch]->pre==0)
{
delete root->v[ch];
root->v[ch]=NULL;
}
//std::cout<<c<<" "<<(char)(ch+'a')<<" "<<root->v[ch]->pre<<" "<<root->v[ch]->app<<"\n";
}
inline int find(nod *root, int ind)
{
if(c[ind+1]=='\0' && root->v[ch]!=NULL)
return root->v[ch]->app;
else if(root->v[ch]!=NULL)
return find(root->v[ch],ind+1);
else
return 0;
}
inline int larg(nod *root, int ind, int countt)
{
if(c[ind+1]=='\0'&& root->v[ch]!=NULL && root->v[ch]->pre!=0)
return countt+1;
else if(root->v[ch]!=NULL && root->v[ch]->pre!=0)
return larg(root->v[ch],ind+1,countt+1);
else
return countt;
}
int main()
{
nod * root = new nod;
fin>>in;
while(fin.getline(c,35))
{
//push
if(in==0)
push(root,1);
//erase one
else if(in==1)
erase(root,1);
//count appearances
else if(in==2)
fout<<find(root,1)<<"\n";
//biggest prefix
else
fout<<larg(root,1,0)<<"\n";
fin>>in;
}
}