构造Trie,在插入的过程中,判断是否有之前插入的单词是当前单词的前缀,在插入完成时,判断当前单词是否是之前某个单词的前缀:
#include <cstdio>
#include <cstring>
struct Node{
bool EOW;//end of word
Node* children[10];
} arr[100000];
int index;
Node* newNode()
{
memset(arr + index, 0, sizeof(Node));
return &arr[index++];
}
bool insertTrie(Node* p, const char* s)
{
bool already = true;
for(; *s; ++s){
Node*& q = p->children[*s - '0'];
if(!q){
q = newNode();
already = false;
}
else if(q->EOW) return false;//a previous word is prefix of this word
if(!s[1]) q->EOW = true;
p = q;
}
return !already;//if already, then this word is prefix of a previous word
}
int main()
{
int test, n;
bool ok;
char s[11];
Node root, *pTrie = &root;
scanf("%d", &test);
while(test--){
//initialize
index = 0;
ok = true;
memset(pTrie, 0, sizeof(Node));
//input and build trie
scanf("%d", &n);
while(getchar() != '\n') ;
for(; n && ok; --n) ok = insertTrie(pTrie, gets(s));
while(n--) gets(s);
//print result
if(ok) puts("YES");
else puts("NO");
}
return 0;
}