题目描述
给定 n 个长度不超过 10 的数字串,问其中是否存在两个数字串 S,T,使得 S 是 T 的前缀,多组数据。
输入格式
第一行一个整数 T,表示数据组数。
对于每组数据,第一行一个数 n,接下来 n 行输入 n 个数字串。
输出格式
对于每组数据,若存在两个数字串 S,T,使得 S 是 T 的前缀,则输出 NO ,否则输出 YES 。
请注意此处结果与输出的对应关系!
样例输入
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
样例输出
NO YES
#include<bits/stdc++.h>
using namespace std;
int ch[100005][10], n, tot;
bool flag[100005], ans;
void Insert(string s) {
int u = 1,p=s.size();
for (int i = 0; i < p; i++) {
int c = s[i] - '0';
if (!ch[u][c]) {
ch[u][c] = ++tot;
}
u = ch[u][c];
if (flag[u]) ans = false;
}
flag[u] = true;
for (int i = 0; i < 10; i++) {
if (ch[u][i]) ans = false;
}
}
int main() {
int m;
cin >> m;
while (m--) {
cin >> n;
tot = 1;
memset(ch, 0, sizeof(ch));
memset(flag, 0, sizeof(flag));
ans = true;
string str;
for (int i = 0; i < n; ++i) {
cin >> str;
Insert(str);
}
if (ans) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}