Examples: Assume an alphabet that has symbols {A, B, C, D}
The following code is immediately decodable:
A:01 B:10 C:0010 D:0000
but this one is not:
A:01 B:10 C:010 D:0000 (Note that A is a prefix of C)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 3333
typedef struct node
{
int c;
int flag;
}BT;
BT tr[N];
int f=0;
void ct(int i) //建树,可以成为01树噢,左孩子为0,右孩子为1
{
tr[i<<1].c='0';
tr[i<<1].flag=0;
tr[i<<1|1].c='1';
tr[i<<1|1].flag=0;
if(i*2+1<1024)
{
ct(i<<1);
ct(i<<1|1);
}
}
void pan(char *s,int i,int k)//大概思路是将输入的编码放进树里,路上如果遇见了已标记的,说明有前缀
{
if(f)
return;
if(tr[k<<1].c==s[i])
{
if(tr[k<<1].flag==1)
{ f=1;return; }
if(s[i+1]=='\0')
{tr[k<<1].flag=1;return ;}
pan(s,i+1,k<<1);
}
else
{
if(tr[k<<1|1].flag==1)
{f=1;return;}
if(s[i+1]=='\0')
{tr[k<<1|1].flag=1;return ;}
pan(s,i+1,k<<1|1);
}
}
int main()
{
freopen("in.txt","r",stdin);
int t=1;
char s[13];
ct(1);//建树
while(scanf("%s",s)!=EOF)
{
if(strcmp(s,"9")==0)
{
if(!f)
printf("Set %d is immediately decodable\n",t++);
else
printf("Set %d is not immediately decodable\n",t++);
f=0;
ct(1);//建树
continue;
}
pan(s,0,1);将编码放进树中,并在结尾标记!
}
return 0;
}
------江财小子