题链接: http://poj.org/problem?id=1056
//poj1056:判断一个前缀是否是另一个串的前缀问题,这让我想到了字典树
#include<iostream>
#include<cstdlib>
using namespace std;
const int N=1000;
typedef struct node
{
int cnt;
struct node *next[2];
}*Tree,T;
Tree root;
bool flag;//标记
void insert(char *str)
{
Tree p,nowNode;
p=root;
int i,len=strlen(str);
for(i=0;i<len;i++)
{
if(p->next[str[i]-'0']!=NULL)
{
if(p->next[str[i]-'0']->cnt==1)
{flag=false;
return;
}
p=p->next[str[i]-'0'];
// p->cnt++;
}
else
{
int j;
nowNode=(Tree)malloc(sizeof(T));
for(j=0;j<2;j++)
nowNode->next[j]=NULL;
p->next[str[i]-'0']=nowNode;
p=p->next[str[i]-'0'];
if(i==len-1)p->cnt=1;//叶子结点
}
}
}
int main()
{
char str[2000];
int set=1,i;
while(gets(str))
{
flag=true;
root=(Tree)malloc(sizeof(T));//初始化root
for(i=0;i<2;i++)
root->next[i]=NULL;
if(strcmp(str,"9")!=0)insert(str);
while(gets(str))
{
if(strcmp(str,"9")==0)break;
if(flag)insert(str);
}
printf("Set %d is %simmediately decodable\n",set++,(flag ? "":"not "));
}
return 0;
}