Pagini recente » Cod sursa (job #842484) | Cod sursa (job #1033809) | Cod sursa (job #706663) | Cod sursa (job #1154569) | Cod sursa (job #2728375)
//Ilie Dumitru
#include<cstdio>
#include<cstring>
struct trie
{
int nrc, nrAp;
trie* next[26];
trie() {this->nrc=this->nrAp=0; for(int i=0;i<26;++i) this->next[i]=0;}
};
trie* capat;
FILE *f=fopen("trie.in", "r"), *g=fopen("trie.out", "w");
void push(char* text, trie* &t)
{
if(*text)
{
if(t)
{
if(!t->next[*text-'a'])
t->nrc++;
push(text+1, t->next[*text-'a']);
}
else
{
t=new trie;
t->nrc=1;
push(text+1, t->next[*text-'a']);
}
}
else
{
if(t)
t->nrAp++;
else
{
t=new trie;
t->nrAp=1;
}
}
}
void pop(char* text, trie* &t)
{
if(*text)
{
pop(text+1, t->next[*text-'a']);
if(!t->next[*text-'a'])
{
--t->nrc;
if(!t->nrc)
delete t;
}
}
else
{
t->nrAp--;
if(!t->nrAp && !t->nrc)
{
delete t;
t=0;
}
}
}
int apart(char* text, trie* &t)
{
if(*text)
if(t && t->next[*text-'a'])
return apart(text+1, t->next[*text-'a']);
if(t)
return t->nrAp;
return 0;
}
int lungMax;
void prefix(char* text, trie* &t, int niv=0)
{
if(t)
{
if(*text)
{
if(niv>lungMax)
lungMax=niv;
prefix(text+1, t->next[*text-'a'], niv+1);
}
else if(niv>lungMax)
lungMax=niv;
}
}
void solve(int op, char* cuvant)
{
int l=strlen(cuvant);
if(cuvant[l-1]=='\n')
cuvant[--l]=0;
switch(op)
{
case 0:
{
push(cuvant, capat);
break;
}
case 1:
{
pop(cuvant, capat);
break;
}
case 2:
{
fprintf(g, "%i\n", apart(cuvant, capat));
break;
}
case 3:
{
lungMax=0;
prefix(cuvant, capat);
fprintf(g, "%i\n", lungMax);
break;
}
}
}
int main()
{
int op;
char cuvant[25];
fscanf(f, "%i %s", &op, cuvant);
do
{
solve(op, cuvant);
fscanf(f, "%i %s", &op, cuvant);
}while(!feof(f));
fclose(stdin);
fclose(stdout);
return 0;
}