Cod sursa(job #279903)
#include<stdio.h>
#include<string.h>
FILE *in=fopen("trie.in","rt");
FILE *out=fopen("trie.out","wt");
typedef struct Trie
{
struct Trie *next[26];
int count,childs;
}Trie;
Trie *trie;
Trie* mkTrie()
{
Trie *t = new Trie;
memset(t->next,0,sizeof(t->next));
t->childs=t->count=0;
return t;
}
int normChar(char c)
{
return c-'a';
}
void insertWord(Trie *where,char *w)
{
if(w==NULL)
{
++where->count;
return;
}
if(where->next[normChar(*w)])
insertWord(where->next[normChar(*w)],w+1);
else
{
++where->childs;
where->next[normChar(*w)]=mkTrie();
insertWord(where->next[normChar(*w)],w+1);
}
}
int removeWord(Trie *where,char *w)
{
if(w==NULL)
--where->count;
else if(removeWord(where->next[normChar(*w)],w+1))
{
where->next[normChar(*w)]=0;
--where->childs;
}
if(!where->count && !where->childs && (where!= trie))
{
delete where;
return 1;
}
return 0;
}
int countOccs(Trie *where,char *w)
{
for(;*w;++w)
if(where->next[normChar(*w)])
where = where->next[normChar(*w)];
else
return 0;
return where->count;
}
int longestPrefix(Trie *where,char *w)
{
int len = 0;
for(;*w&&where->next[normChar(*w)];++w)
{
++len;
where = where->next[normChar(*w)];
}
return len;
}
void printPath(Trie *where,char *w)
{
for(;*w&&where;++w)
printf("(%d %d)-%c->",where->count,where->childs,*w);
printf("(%d %d)\n",where->count,where->childs);
}
int main()
{
int op;
char w[32];
trie = mkTrie();
while(fscanf(in,"%d %s",&op,w)!=EOF)
switch(op)
{
case 0: insertWord(trie,w);break;
case 1: removeWord(trie,w);break;
case 2: fprintf(out,"%d\n",countOccs(trie,w));break;
case 3: fprintf(out,"%d\n",longestPrefix(trie,w));break;
}
fclose(in);
fclose(out);
return 0;
}