题目:http://poj.org/problem?id=1056
题意:判断一组字符串中是否有两个串A和串B,且A是B的前缀,通过将串依次插入Trie即可判断当前串是否是前面串的前缀,和前面串是否有当前串的前缀。
#include <cstdio>
#define MAX_N 200005
int N, NEX;
struct Node{
Node* ch[2];
bool isLeaf(){
return !ch[0] && !ch[1];
}
} nodes[MAX_N], *root;
Node* newNode(){
nodes[NEX].ch[0] = nodes[NEX].ch[1] = NULL;
return nodes + NEX++;
}
bool insert(Node* p, const char* s)
{
bool newed = false;
for(; *s; ++s){
Node*& q = p->ch[*s - '0'];
if(!q){
q = newNode();
newed = true;
}
else if(!newed && q != root && q->isLeaf()) return true;
p = q;
}
return !newed;
}
int main()
{
int kase = 0;
char s[12];
bool foundPrefix;
while(gets(s)){
++kase;
NEX = 0;
root = newNode();
foundPrefix = false;
for(; s[0] != '9' && !foundPrefix; gets(s)) foundPrefix = insert(root, s);
while(s[0] != '9') gets(s);
if(foundPrefix) printf("Set %d is not immediately decodable\n", kase);
else printf("Set %d is immediately decodable\n", kase);
}
return 0;
}