Pagini recente » Cod sursa (job #1369785) | Cod sursa (job #2620233) | Cod sursa (job #2724456) | Cod sursa (job #2175118) | Cod sursa (job #800840)
Cod sursa(job #800840)
#include <stdio.h>
#define SIGMA 26
#define Nmax 22
using namespace std;
struct Trie
{
int cnt,sons;
Trie *son[SIGMA];
Trie()
{
cnt = sons = 0;
for(int i=0;i<SIGMA;++i)
son[i] = 0;
}
}*nod;
void create_node(Trie *&x)
{
x = new Trie();
}
void insert(Trie *&x, char *s)
{
if(*s == 0)
{
++x->cnt;
return;
}
int code = s[0] - 'a';
if(x->son[ code ] == 0)
{
create_node(x->son[code]);
++x->sons;
}
insert(x->son[code], s+1);
}
void remove(Trie *&x, char *s)
{
if(*s == 0)
{
--x->cnt;
return;
}
int code = s[0] - 'a';
if(x->son[code] == 0)
return;
remove(x->son[code], s+1);
if(x->son[code]->cnt == 0 && x->son[code]->sons == 0)//daca fiul nodului x nu are alti fii si nu este un final de cuv il stergem
{
delete x->son[code];
x->son[code] = 0;
--x->sons;
}
}
int count(Trie *x, char *s)
{
if(*s == 0)
{
return x->cnt;
}
int code = s[0] - 'a';
if(x->son[code] == 0)
{
return 0;
}
return count(x->son[code],s+1);
}
int maxim(int a,int b)
{
if(a>=b)
return a;
return b;
}
int pref(Trie *x, char *s,int l)
{
if(x == 0)
return 0;
if(*s == 0)
{
return l;
}
int code = s[0] - 'a';
if(x->sons || x->cnt)//daca acest nod are mai mult de 2 fii sau pana aici s-a format un cuv atunci l(adancimea) ramane valabila
return maxim(l, pref(x->son[code], s+1, l+1));
}
void show_node(Trie *x)
{
printf("%d ",x->cnt);
for(int i=0;i<SIGMA;++i)
if(x->son[i])
printf("%c %d %d\n",char(i+'a'), x->son[i]->cnt, x->son[i]->sons);
printf("\n");
}
int main()
{
create_node(nod);
FILE*f = fopen("trie.in","r");
FILE*g = fopen("trie.out","w");
int op,la=0;
char buf[Nmax];
while(!feof(f))
{
fscanf(f,"%d %s",&op,buf);
if(feof(f))
continue;
switch(op)
{
case 0:
//printf("%s\n",buf);
insert(nod, buf);
break;
case 1:
remove(nod,buf);
break;
case 2:
fprintf(g,"%d\n",count(nod,buf));
break;
case 3:
fprintf(g,"%d\n",pref(nod,buf,0));
break;
}
}
//show_node(nod->son['m' - 'a']);
fclose(f);
fclose(g);
return 0;
}