Cod sursa(job #987115)
#include <fstream>
#include <cstring>
using namespace std;
struct nod
{
int pref;
int exact;
nod *alf[26];
}*root;
char sir[23];
int lung;
inline void create(nod* &a)
{
a=new nod;
a->pref=0;
a->exact=0;
int i;
for(i=0;i<26;i++)
a->alf[i]=NULL;
}
inline void destroy(nod* &a)
{
delete a;
a=NULL;
}
void add(nod* &unde,int poz)
{
unde->pref++;
if(poz==(lung-1))
{
unde->exact++;
return;
}
if((unde->alf[sir[poz+1]-'a'])==NULL)
create(unde->alf[sir[poz+1]-'a']);
add(unde->alf[sir[poz+1]-'a'],poz+1);
}
void del(nod* &unde,int poz)
{
unde->pref--;
if(poz==(lung-1))
{
unde->exact--;
if(unde->pref==0)
destroy(unde);
return;
}
del(unde->alf[sir[poz+1]-'a'],poz+1);
if((unde->pref)==0)
destroy(unde);
}
int cate(nod* &unde,int poz)
{
if(poz==(lung-1))
return unde->exact;
if((unde->alf[sir[poz+1]-'a'])!=NULL)
return cate(unde->alf[sir[poz+1]-'a'],poz+1);
return 0;
}
int cmlpc(nod* &unde,int poz)
{
if(poz==(lung-1))
return lung;
if((unde->alf[sir[poz+1]-'a'])!=NULL)
return cmlpc(unde->alf[sir[poz+1]-'a'],poz+1);
return (poz+1);
}
int main()
{
ifstream fin("trie.in");
ofstream fout("trie.out");
root=NULL;
create(root);
int x;
while(fin>>x)
{
fin.get();
fin.get(sir,23);
fin.get();
lung=strlen(sir);
//cout<<"sir e "<<sir<<endl;
if(x==0)
{
if((root->alf[sir[0]-'a'])==NULL)
create(root->alf[sir[0]-'a']);
add(root->alf[sir[0]-'a'],0);
}
else if(x==1)
del(root->alf[sir[0]-'a'],0);
else if(x==2)
{
if((root->alf[sir[0]-'a'])==NULL)
fout<<"0\n";
else
fout<<cate(root->alf[sir[0]-'a'],0)<<'\n';
}
else if(x==3)
{
if((root->alf[sir[0]-'a'])==NULL)
fout<<"0\n";
else
fout<<cmlpc(root->alf[sir[0]-'a'],0)<<'\n';
}
}
fin.close();
fout.close();
return 0;
}