Pagini recente » Cod sursa (job #413257) | Cod sursa (job #3002050) | Cod sursa (job #860955) | Cod sursa (job #700193) | Cod sursa (job #748137)
Cod sursa(job #748137)
#include<fstream>
//#include<iostream.h>
//#include<conio.h>
#include<string.h>
using namespace std;
struct nod
{int nr_ap,sters;
nod * cuv[27];
nod()
{for(int i=26; i--;)
cuv[i]=0;
nr_ap=0;
sters=0;
}
};
nod * r, * p;
void adauga(char s[21])
{int i,x;
for(i=0;i<strlen(s);i++)
{x=s[i]-'a';
if(p->cuv[x]==NULL)
{p->cuv[x]=new nod;
p=p->cuv[x];
p->nr_ap=0;
}
else
p=p->cuv[x];
}
p->nr_ap++;
p->sters=1;
}
void sterge(char s[21])
{int i,x;
for(i=0;i<strlen(s);i++)
{x=s[i]-'a';
if(p->cuv[x]!=NULL)
p=p->cuv[x];
}
p->nr_ap--;
p->sters=-1;
}
int nr_aparitii(char s[21])
{int i,x;
for(i=0;i<strlen(s);i++)
{x=s[i]-'a';
if(p->cuv[x]!=NULL)
p=p->cuv[x];
else return 0;
}
return p->nr_ap;
}
int prefix(char s[21])
{int i,x,y,gasit=1,nr=0;
nod * w;
w=new nod;
for(i=0;i<strlen(s) && gasit==1;i++)
{x=s[i]-'a';
if(i==(strlen(s)-1) && p->cuv[x]->nr_ap==1)
return nr;
if(p->cuv[x]!=NULL && p->cuv[x]->sters!=-1)
{p=p->cuv[x];
nr++;
}
else gasit=0;
}
return nr;
}
int main()
{int i,x;
char s[21];
r=new nod;
p=new nod;
p=r;
ifstream f("trie.in");
ofstream g("trie.out");
while(f>>x>>s)
{if(x==0) {p=r;adauga(s);}
else
if(x==1) {p=r;sterge(s);}
else
if(x==2) {p=r;g<<nr_aparitii(s)<<"\n";}
else {p=r;g<<prefix(s)<<"\n";}
}
f.close();
g.close();
//getch();
return 0;
}