字典树:问是否在给出的二进制中能找到前缀码。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int x;
node *next[22];
node()
{
x=0;
for(int i=0;i<2;i++)
next[i]=NULL;
}
};
node root;
bool update(char *s)
{
int k1=0,k2=1;
int l=strlen(s);
int id=0;
node *p=&root;
for(int i=0;i<l;i++)
{
if(p->x==1)
k2=0;
id=s[i]-'0';
if(p->next[id]==NULL)
{
k1=1;
node *q=new node;
p->next[id]=q;
}
p=p->next[id];
}
p->x=1;
return k1&&k2;
}
int freedom(node *p)
{
int i=0;
for(i=0;i<2;i++)
if(p->next[i]!=NULL)
freedom(p->next[i]);
if(p==&root)
{
for(int j=0;j<2;j++)
p->next[j]=NULL;
p->x=0;
}
else
{
delete(p);
}
return 0;
}
int main(void)
{
int i,j,k=1,kk=1,t=1;
char s[20];
while(scanf("%s",s)!=EOF)
{
if(s[0]=='9')
{
if(kk==1)
printf("Set %d is immediately decodable\n",t++);
else
printf("Set %d is not immediately decodable\n",t++);
k=1;
kk=1;
freedom(&root);
}
else
{
k=update(s);
if(k==0)
kk=0;
}
}
return 0;
}