题目链接:https://vjudge.net/problem/POJ-1056
题意:给定一个字符串集,判断是否存在一个字符串是另一个字符串的前缀。
思路:和hdoj1671一样,有两种情况:
当前长度处已经存在字符串。比如先插入10,再插入101。
最后一个字符后面还有子结点。比如先插入101,再插入10。
AC code:
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxn=1e6+5; int cas,trie[maxn][3],key[maxn],cnt,flag; char str[15]; void insert(char *s){ int len=strlen(s),u=0; for(int i=0;i<len;++i){ int t=s[i]-'0'; if(!trie[u][t]){ ++cnt; memset(trie[cnt],0,sizeof(trie[cnt])); key[cnt]=0; trie[u][t]=cnt; } u=trie[u][t]; if(key[u]){ flag=0; return; } if(i==len-1) key[u]=1; } if(trie[u][0]||trie[u][1]) flag=0; } int main(){ while(~scanf("%s",str)){ flag=1,cnt=0; memset(trie[0],0,sizeof(trie[0])); insert(str); while(scanf("%s",str),str[0]!='9') if(flag) insert(str); if(flag) printf("Set %d is immediately decodable ",++cas); else printf("Set %d is not immediately decodable ",++cas); } return 0; }