HDU1305 Immediate Decodability (字典树
Immediate Decodability
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)
InputWrite a program that accepts as input a series of groups of records from input. Each record in a group contains a collection of zeroes and ones representing a binary code for a different symbol. Each group is followed by a single separator record containing a single 9; the separator records are not part of the group. Each group is independent of other groups; the codes in one group are not related to codes in any other group (that is, each group is to be processed independently).
OutputFor each group, your program should determine whether the codes in that group are immediately decodable, and should print a single output line giving the group number and stating whether the group is, or is not, immediately decodable.
Sample Input
01 10 0010 0000 9 01 10 010 0000 9
Sample Output
Set 1 is immediately decodable Set 2 is not immediately decodable
orz一道字典树的题,以9为每组数据的间隔,给你那么多个字符串,判断是否存在一个字符串是其他某个字符串的前缀。
写法是按照给出的串构造一棵树,如果构造这条字符串的时候碰见了某个串的结尾,或者是构造完了以后接下来还有字符,就说明存在,标记一下就好了
记住每次都要清空标记。
两份ac代码,一个是别人博客学来的,一个是学长给的ppt里扒下来的字典树~第二份被没有赋{0}卡了半天orz,感谢mwjj救憨憨lj
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 struct node{ 5 int a[10]; 6 int isleaf; 7 int haveson; 8 }trie[1000]; 9 int len,cnt,f; 10 char s[100]; 11 12 void insert(int now,int x){ 13 if(x==len){ 14 if(trie[now].isleaf==1||trie[now].haveson==1)f = 1; 15 trie[now].isleaf=1;return ; 16 } 17 if(trie[now].isleaf==1){ 18 f = 1;return ; 19 } 20 trie[now].haveson=1; 21 int num = s[x]-'0'; 22 if(trie[now].a[num]==0)trie[now].a[num]=++cnt; 23 insert(trie[now].a[num],x+1); 24 } 25 int main(){ 26 int t=0,cas=0; 27 while(scanf("%s",s)!=EOF){ 28 if(s[0]=='9'){ 29 cas++; 30 if(t) printf("Set %d is not immediately decodable\n",cas); 31 else printf("Set %d is immediately decodable\n",cas); 32 memset(trie,0,sizeof(trie)); 33 t = cnt = 0; 34 } 35 f = 0;len=strlen(s);insert(0,0); 36 if(f==1)t = 1; 37 } 38 return 0; 39 }
1 #include<bits/stdc++.h> 2 const int mod=100003; 3 const int N = 1e5+2; 4 int a[N],n,k,tot=0; 5 bool flag=0; 6 using namespace std; 7 struct node{ 8 bool r=0; 9 node *next[30]={0}; 10 }; 11 node root; 12 bool ans = 0;char s[1500]; 13 void build_trie(){ 14 int l = strlen(s); 15 node *p=&root; 16 for(int i = 0;i < l;++i){ 17 if(p->r==1)flag=1; 18 if(p->next[s[i]-'0']==NULL){ 19 p->next[s[i]-'0'] = new node; 20 } 21 p=p->next[s[i]-'0']; 22 } 23 if(p->r > 0)flag=1;p->r=1; 24 if(p->next[0]!=NULL||p->next[1]!=NULL)flag=1; 25 } 26 27 int main() 28 { 29 while(scanf("%s",s)!=EOF){ 30 if(s[0]=='9'){ 31 if(ans)printf("Set %d is not immediately decodable\n",++tot); 32 else printf("Set %d is immediately decodable\n",++tot); 33 flag=ans=false; 34 for(int i=0;i<26;i++)root.next[i]=nullptr; 35 } 36 build_trie(); 37 if(flag)ans=true; 38 } 39 return 0; 40 }