Pagini recente » Cod sursa (job #1687041) | Cod sursa (job #2747466) | Cod sursa (job #1274741) | Cod sursa (job #1286689) | Cod sursa (job #2968798)
#include <fstream>
#include <cstring>
const int NMAX=25;
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Nod
{
int nrc, ncopii;
Nod* l[26];
Nod()
{
ncopii=0;
nrc=0;
for(int i=0; i<26; i++) l[i]=NULL;
}
};
void ins(Nod*, char*, int);
bool rem(Nod*, char*, int);
int cnt(Nod*, char*, int);
int pref_com_max(Nod*, char*, int, int);
bool elim(Nod*);
char s[NMAX];
int main()
{
int tip;
Nod* root=new Nod;
while(fin>>tip>>s)
{
if(tip==0) ins(root, s, strlen(s));
else if(tip==1) rem(root, s, strlen(s));
else if(tip==2) fout<<cnt(root, s, strlen(s))<<'\n';
else fout<<pref_com_max(root, s, strlen(s), 0)<<'\n';
}
return 0;
}
void ins(Nod* n, char* cuv, int lg)
{
if(lg==0)
{
n->nrc++;
return;
}
if(n->l[cuv[0]-'a']==NULL)
{
n->ncopii++;
n->l[cuv[0]-'a']= new Nod;
}
ins(n->l[cuv[0]-'a'], (cuv+1), lg-1);
}
bool should_rem(Nod* n)
{
return (n->nrc==0 && n->ncopii==0);
}
bool rem(Nod* n, char* cuv, int lg)
{
if(lg==0)
{
n->nrc--;
return should_rem(n);
}
else if(rem(n->l[cuv[0]-'a'], (cuv+1), lg-1))
{
delete n->l[cuv[0]-'a'];
n->l[cuv[0]-'a']=NULL;
n->ncopii--;
return should_rem(n);
}
return false;
}
int cnt(Nod* n, char* cuv, int lg)
{
if(lg==0) return(n->nrc);
if(n->l[cuv[0]-'a']!=NULL) return cnt(n->l[cuv[0]-'a'], cuv+1, lg-1);
return 0;
}
int pref_com_max(Nod* n, char* cuv, int lg, int lvl)
{
if(lg==0) return lvl;
if(n->l[cuv[0]-'a']!=NULL)
{
int comp=pref_com_max(n->l[cuv[0]-'a'], cuv+1, lg-1, lvl+1);
if(n->ncopii>=1) return max(lvl+1, comp);
return comp;
}
return 0;
}