一道字典树的题,这道题在检查每个串时,不仅要判断别的串是否为自己的前缀,还要判断自己是否为其他串的前缀.
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <climits>
#include <set>
#include <cstdlib>
using namespace std;
#define maxn 10
typedef struct Node{
bool end;
Node* p[maxn];
}*T;
T NewNode(){
T k = (T)malloc(sizeof(Node));
k -> end = false;
memset(k -> p, 0, sizeof(k -> p));
return k;
}
bool Insert(string &s, T u){
int i = 0;
while(i < s.size()){
int m = s[i] - '0';
if(u -> p[m]){
u = u -> p[m];
if(u -> end || i == s.size()-1)
return false;
}
else{
u -> p[m] = NewNode();
u = u -> p[m];
}
i++;
}
u -> end = true;
return true;
}
void Destory(T u){
for(int i = 0; i < maxn; i++){
if(u -> p[i])
Destory(u -> p[i]);
}
free(u);
}
int main(){
// freopen("in.txt", "r", stdin);
int t;
cin >> t;
while(t--){
int n, flag = 0;
cin >> n;
T u = NewNode();
for(int i = 0; i < n; i++){
string s;
cin >> s;
if(!flag && !Insert(s, u))
flag = 1;
}
if(flag)
cout << "NO" << endl;
else
cout << "YES" << endl;
Destory(u);
}
return 0;
}