题目链接
题目分析:字典树的裸题,把每个字符串读入后,插入字典树,在从头到尾便利一遍每个字符串,如果在遍历过程中遇到某个节点是另一个字符串的结尾,(注意做个标记排除自身),则输出“NO”。
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e4 + 5;
int T, n, tot, trie[15 * N][15], len[N], mark[N];
char s[N][15];
bool book[N];
void insert(char* s, int n, int num) {
int p = 1;
for (int i = 1; i <= n; i++) {
if (!trie[p][s[i] - '0']) trie[p][s[i] - '0'] = ++tot;
p = trie[p][s[i] - '0'];
}
book[p] = true;
mark[num] = p;
}
bool search(char* s, int n, int num) {
int p = 1;
for (int i = 1; i <= n; i++) {
p = trie[p][s[i] - '0'];
if (mark[num] != p && book[p]) return true;
}
return false;
}
int main() {
cin >> T;
while (T--) {
memset(trie, 0, sizeof(trie));
memset(book, 0, sizeof(book));
tot = 1;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> s[i] + 1;
len[i] = strlen(s[i] + 1);
insert(s[i], len[i], i);
}
bool flag = true;
for (int i = 1; i <= n; i++) {
if (search(s[i], len[i], i)) {
flag = false;
break;
}
}
if (flag) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}