Immediate Decodability
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3444 Accepted Submission(s): 1791
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)
Set 2 is not immediately decodable
題目大意:給你一些二進制組成的密碼,詢問是否可以解碼,規定如果這些密碼裏存在某些二進制密碼是另外一些二進制密碼的前綴,則不可以解碼,如果不是則代表可以解碼,以數字9代表當前一組數據輸入結束。
解題思路:沒得到一組密碼,就將該密碼插入到字典樹裏面去,因爲這裏只有0和1,所以密碼樹只有兩個子樹1和0,當存在情況爲當前密碼存儲的位置被標記過時,則說明該位置存在密碼,即存在前綴情況,結束。
ac代碼:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdlib>
using namespace std;
const int M=100005;
struct node
{
int cnt;
node *child[2];
node()
{
cnt=0;
for(int i=0; i<2; i++)
child[i]=NULL;
}
};
char a[15];
int flag;
node *root,*cur,*newnode;
void insert(char *a)
{
cur=root;
int len=strlen(a);
for(int i=0; i<len ; i++)
{
int index=a[i]-'0';
if(cur->child[index]!=NULL)
{
cur=cur->child[index];
if(cur->cnt==1 || i==len-1)
{
flag=0;//標記
break;
}
}
else
{
newnode=new node;
cur->child[index]=newnode;
cur=newnode;
}
}
cur->cnt=1;
}
void del(node *head)
{
for(int i=0; i<2; i++)
if(head->child[i]!=NULL)
del(head->child[i]);
delete(head);
}
int main()
{
int g=1;
while(scanf("%s",a)!=EOF)
{
flag=1;//標記默認爲1
root=new node;
insert(a);
while(scanf("%s",a)!=EOF)
{
if(strcmp(a,"9")==0)break;
{
if(!flag)
continue;
insert(a);
}
}
if(flag)printf("Set %d is immediately decodable\n",g++);
else
printf("Set %d is not immediately decodable\n",g++);
del(root);
}
return 0;
}
題目鏈接:點擊打開鏈接http://acm.hdu.edu.cn/showproblem.php?pid=1305
有關字典樹的有關知識請看我的字典樹專題博客:點擊打開鏈接http://blog.csdn.net/wang_heng199/article/details/76448804