Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 11585 | Accepted: 5517 |
Description
Input
Output
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
题意:
判断二进制码是否能唯一识别,也就是一个二进制码不是另一个二进制码的前缀
题解:
最近在学字典树,搜的字典树的简单题做的,其实还可以排序做,先说字典树吧,在树的节点上做个标记,标记作用为是否是为一个二进制码的结尾,于是就有两种情况,一种为在此码是前面出现的二进制码的前缀,这时只需要判断此码的结尾字符在树上存在,还有就是前面出现的二进制码是此码的前缀,这时只要判断标记就行了,注意初始化。
排序的方法,对二进制码按字典序排序,一个二进制码的前缀肯定在其前一个位置出现,具体原因,自己想下就很容易理解了O(∩_∩)O~~
字典树代码:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; const int maxn=110000; struct node { int sign; int next[2]; } a[maxn]; int n=0; bool insert(char *s) { int len,temp; len=strlen(s); int p=0; for(int i=0; i<len; i++) { temp=s[i]-'0'; if(a[p].next[temp]!=-1) { p=a[p].next[temp]; if(i==len-1) return 1; if(a[p].sign==1) return 1; } else { a[p].next[temp]=++n; p=n; } if(i==len-1) a[p].sign=1; } return 0; } int main() { char s[15]; int count=1; while(~scanf("%s",s)) { n=0; if(s[0]=='9') break; memset(a,-1,sizeof(a)); int ans=0; if(insert(s)) { ans=1; } while(scanf("%s",s)&&s[0]!='9') { if(insert(s)) { ans=1; } } if(ans) printf("Set %d is not immediately decodable\n",count++); else printf("Set %d is immediately decodable\n",count++); } }
排序代码:
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; struct node { char s[15]; } a[11000]; bool operator < (node const& x,node const& y) { return strcmp(x.s,y.s)<0; } int main() { int n=0; int count=1; while(~scanf("%s",a[n].s)&&a[n].s[0]!='9') { n++; while(scanf("%s",a[n].s)&&a[n].s[0]!='9') { n++; } sort(a,a+n); int ans=0; for(int i=1; i<n; i++) { int len1=strlen(a[i-1].s); int len2=strlen(a[i].s); if(len1<=len2) { int j; for(j=0; j<len1; j++) if(a[i-1].s[j]!=a[i].s[j]) break; if(j==len1) ans=1; } } if(ans) printf("Set %d is not immediately decodable\n",count++); else printf("Set %d is immediately decodable\n",count++); n=0; } return 0; }
POJ 1056 IMMEDIATE DECODABILITY
原文地址:http://blog.csdn.net/caduca/article/details/43603445