題目鏈接如下:http://hdu.hustoj.com/showproblem.php?pid=1305
Immediate Decodability
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 2836 Accepted Submission(s): 1462
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 <iostream>
#include <cstdio>
using namespace std;
struct trie
{
int num;
trie *child[2];
trie()
{
for(int i=0;i<2;i++) child[i]=0;
num=0;
}
} *root;
int flag;
void Insert(char *x)
{
int k=0;trie *p=root;
while(x[k]!='\0')
{
if(p->child[x[k]-'0']==0)
p->child[x[k]-'0']=new trie;
p=p->child[x[k]-'0'];
if(p->num==2){
flag=1;
k++;
continue;
}
if(p->num==1){
if(x[k+1]=='\0') flag=1;
k++;
continue;
}
p->num=1;
k++;
}
p->num=2;
}
void Free(trie *p)
{
for(int i=0;i<2;i++)
if(p->child[i]) Free(p->child[i]);
delete p;
}
int main()
{
char x[10];
int t=1;
root=new trie;flag=0;
while(scanf("%s",x)!=EOF)
{
if(x[0]=='9')
{
if(flag) printf("Set %d is not immediately decodable\n",t++);
else printf("Set %d is immediately decodable\n",t++);
flag=0; Free(root);
root=new trie;
continue;
}
Insert(x);
}
return 0;
}