这道题是字典树入门题目,今天下午刚学字典树,理解了原理,然后看看代码就会发现简单了!
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef struct trie
{
int v;
trie *next[2];
}trie;
trie *root;
void creattrie(char *str)
{
int i,j;
trie *p=root,*q;
int len=strlen(str);
for(i=0; i<len; i++)
{
int id=str[i]-'0';
if(p->next[id]==NULL)
{
q=(trie *)malloc(sizeof(trie));
q->v=1;
for(j=0; j<2; j++)
{
q->next[j]=NULL;
}
p->next[id]=q;
p=p->next[id];
}
else
{
p->next[id]->v++;
p=p->next[id];
}
}
}
int findtrie(char *str)
{
int len,i;
len=strlen(str);
trie *p=root;
for(i=0; i<len; i++)
{
int id=str[i]-'0';
p=p->next[id];
if(p==NULL)
return 0;
}
return p->v;
}
int main()
{
char str[10][20];
int tcase=0;
int i;
while(scanf("%s",str[0])!=EOF)
{
root=(trie *)malloc(sizeof(trie));
for(i=0; i<2; i++)
root->next[i]=NULL;
int k=1;
creattrie(str[0]);
while(scanf("%s",str[k])!=EOF&&str[k][0]!='9')
{
creattrie(str[k++]);
}
for(i=0; i<k; i++)
{
int flag;
flag=findtrie(str[i]);
if(flag>1)//一开始这里错了,就是flag一定要大于1,因为它本身就是一个!
{
printf("Set %d is not immediately decodable\n",++tcase);
break;
}
}
if(i>=k)
{
printf("Set %d is immediately decodable\n",++tcase);
}
}
return 0;
}