Pagini recente » Cod sursa (job #1348197) | Cod sursa (job #1457472) | Cod sursa (job #823538) | Cod sursa (job #1047271) | Cod sursa (job #2062837)
#include<stdio.h>
#include<string.h>
#define NUM_SYMBOLS_MAX 26
#define MAXBUF 20
struct Node
{
Node();
int no_of_ending_points;
int nr_occ;
Node* son[NUM_SYMBOLS_MAX];
};
//FUNCTII TRIE
void Add();
void Remove();
int Occ();
int LCP();
FILE*fin,*fout;
Node* root;
char buf[MAXBUF];
int len; //TOATE FUNCTIILE DE MAI SUS ACTIONEAZA PE SIRUL ASTA
int main()
{
fin=fopen("trie.in","r");
fout=fopen("trie.out","w");
root=new Node;
int op;
fscanf(fin,"%d %s",&op,buf);
while(!feof(fin))
{
len=strlen(buf);
if(op==0)
{
Add();
}
if(op==1)
{
Remove();
}
if(op==2)
{
fprintf(fout,"%d\n",Occ());
}
if(op==3)
{
fprintf(fout,"%d\n",LCP());
}
fscanf(fin,"%d %s",&op,buf);
}
}
Node::Node()
{
no_of_ending_points=0;
nr_occ=0;
for(int i=0;i<NUM_SYMBOLS_MAX;i++)
{
son[i]=NULL;
}
}
void Add()
{
Node*p=root;
for(int i=0;i<len;i++)
{
if(p->son[buf[i]-'a']==NULL)
{
p->son[buf[i]-'a']=new Node;
}
p->son[buf[i]-'a']->nr_occ++;
p=p->son[buf[i]-'a'];
}
p->no_of_ending_points++;
}
void Remove()
{
Node*p=root;
for(int i=0;i<len;i++)
{
p->son[buf[i]-'a']->nr_occ--;
Node* toDelete=p;
p=p->son[buf[i]-'a'];
if(toDelete->son[buf[i]-'a']->nr_occ==0)
{
toDelete->son[buf[i]-'a']=NULL;
}
if(toDelete->nr_occ==0 && toDelete!=root)
{
delete toDelete;
}
}
}
int Occ()
{
Node*p=root;
for(int i=0;i<len && p!=NULL;i++)
{
p=p->son[buf[i]-'a'];
}
if(p==NULL)
{
return 0;
}
return p->no_of_ending_points;
}
int LCP()
{
int ans=0;
Node*p=root;
for(int i=0;i<len && p!=NULL;i++)
{
p=p->son[buf[i]-'a'];
if(p!=NULL)
{
ans++;
}
}
return ans;
}