http://acm.hdu.edu.cn/showproblem.php?pid=1305
题目大意:给你一系列字符串,以9位分割线,判断在某个集合里的字符串有没有作为其他字符串的前缀出现。
解题思路:典型的字典树的题,只需要在构造字典树的时候判断这个节点是否可以构成字符串,且为叶子结点。这里出现前缀有两种情况,一是这个字符串还没有插入完,但已经遇到被标记的字符,二是,这个字符串已经插入完,但它还有后继节点。
code:
#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
struct Trie
{
int flag;
struct Trie *next[2];
Trie(){
flag = 0;
for(int i=0;i<2;i++)
next[i] = NULL;
}
};
int ans ;
Trie *root,*p,*temp;
bool insert(char str[])
{
p = root;
for(int i=0;i<strlen(str);i++)
{
if(p->next[str[i]-'0']!=NULL){
p = p->next[str[i] -'0'];
if(p->flag == 1||i == strlen(str)-1){
///p->flag == 1还没有插入完,已经遇到被标记的节点,i == strlen(str)-1表示已经插入完毕,但此节点还有后继节点,此时标记一下变量,直接结束
ans = 0;
break;
}
}
else{
temp = new Trie;
p->next[str[i] - '0'] = temp;
p = temp;
}
}
p->flag = 1;
}
void del(Trie *root)
{
for(int i=0;i<2;i++)
{
if(root->next[i]!=NULL)
del(root->next[i]);
}
delete(root);
}
int main()
{
int c = 0;ans = 1;
char str[15];root = new Trie;
while(~scanf("%s",str))
{
if(str[0]=='9')
{
if(ans) printf("Set %d is immediately decodable\n",++c);
else printf("Set %d is not immediately decodable\n",++c);
del(root);root = new Trie;
ans = 1;
continue;
}
if(!ans)continue;
insert(str);
}
return 0;
}