Pagini recente » Cod sursa (job #5781) | Cod sursa (job #6823) | Cod sursa (job #269582) | Cod sursa (job #3231592) | Cod sursa (job #293133)
Cod sursa(job #293133)
#include<fstream.h>
#include<string.h>
#define nx 26
struct trie
{
int inf,fiu;
trie *next[nx];
trie ()
{
memset(next,0,sizeof(next));
inf=fiu=0;
}
};
void add (trie *t,char *w)
{
if (*w=='\0')
{
++t->inf;
return;
}
int pos=*w-'a';
if (!t->next[pos])
{
++t->fiu;
t->next[pos]=new trie;
}
add (t->next[pos],w+1);
}
int del (trie *T,trie *t,char *w)
{
int pos=*w-'a';
if (*w=='\0')
--t->inf;
else
if (del(T,t->next[pos],w+1))
{
t->next[pos]=0;
--t->fiu;
}
if (!t->fiu && !t->inf && t!=T)
{
delete t;
return 1;
}
return 0;
}
int app (trie *t,char *w)
{
if (*w=='\0')
return t->inf;
int pos=*w-'a';
if (t->next[pos])
return app(t->next[pos],w+1);
return 0;
}
int pref (trie *t,char *w,int k)
{
if (*w=='\0')
return k;
int pos=*w-'a';
if (!t->next[pos])
return k;
return pref(t->next[pos],w+1,k+1);
}
int main()
{
ifstream be ("trie.in");
ofstream ki ("trie.out");
int c;
trie *t=new trie;
char szo[nx];
while (be>>c && be>>szo)
{
if (c==0)
add(t,szo);
if (c==1)
del(t,t,szo);
if (c==2)
ki<<app(t,szo)<<'\n';
if (c==3)
ki<<pref(t,szo,0)<<'\n';
}
be.close();
ki.close();
return 0;
}