通俗的说,字典树就是用一棵树来存储一系列的字符串,每一个点到根节点的路径记录着一个字符串。
http://poj.org/problem?id=1056
该图为存了26个英文字母的字典树,
本题只需要把每一层26个字母改成0 1 两个分支。
<span style="font-size:18px;">#include <stdio.h>
#include <string.h>
#include <malloc.h>
typedef struct ac<span style="white-space:pre"> </span>
{
struct ac *child[3];
int v;<span style="white-space:pre"> </span>//v记录到该点为止,是否记录了一个完整的二进制数
}trie;
trie *root;
int flag=0;
void add(char *p)<span style="white-space:pre"> </span>//读入一个二进制数
{
int len=strlen(p);
int i,k;
trie *r=root;
for(i=0;i<len;i++)<span style="white-space:pre"> </span>//改二进制数每一位占一层
{
k=p[i]-'0';
if(r->child[k]!=NULL)
{
r=r->child[k];<span style="white-space:pre"> </span>
if(r->v==1)
flag=1;
}
else
{
trie *s=(trie *)malloc(sizeof(trie));
for(int j=0;j<2;j++)
s->child[j]=NULL;
r->child[k]=s;
r=s;
}
}
r->v=1;
}
void trie_clear(trie *r)<span style="white-space:pre"> </span>//内存清理
{
if(r==NULL)
free(r);
else
{
for(int i=0;i<2;i++)
trie_clear(r->child[i]);
}
}
int main()
{
char s[15];
int ti=1,i;
root=(trie *)malloc(sizeof(trie));
for(i=0;i<2;i++)
{
root->child[i]=NULL;
root->v=0;
}
while(scanf("%s",s)!=EOF)
{
if(s[0]=='9')
{
if(flag)
printf("Set %d is not immediately decodable\n",ti++);
else
printf("Set %d is immediately decodable\n",ti++);
flag=0;
trie_clear(root);
root=(trie *)malloc(sizeof(trie));
for(i=0;i<2;i++)
{
root->child[i]=NULL;
root->v=0;
}
continue;
}
add(s);
}
return 0;
}
</span>
相关题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1109