题意:给你一串电话号看是否有号码为其他号码的前缀。
分析:判断前缀我们只需要看前面字符串是否是已经出现字符串的前缀或者是后面的字符串的前缀。
(1)已经出现字符串的前缀我们。用flag代表是否出现以该节点结尾的单词;
(2)用sum代表以该节点结尾为前缀的单词数还有多少个,中间加判断条件即可。
#include<iostream>
#include<cstdio>
#include<map>
#include<string.h>
#include<cstring>
using namespace std;
const int maxn = 100010;
string a, b;
int trie[maxn][12], tot;
int m, rt, t, flag[maxn], ans, sum[maxn];
void insertit(int rt, string str)
{
int len = str.size();
for(int i = 0; i < len; i++)
{
int x = str[i] - '0';
if(trie[rt][x] == 0) trie[rt][x] = ++tot;
rt = trie[rt][x];
if(flag[rt]) ans = 1;
sum[rt]++;
}
if(sum[rt] > 1) ans = 1;
flag[rt]++;
}
int main()
{
scanf("%d", &t);
while(t--)
{
rt = 1; tot = 1;
scanf("%d", &m);
ans = 0;
while(m--)
{
cin >> a;
insertit(rt, a);
}
if(ans) puts("NO");
else puts("YES");
memset(flag, 0 ,sizeof(flag));
memset(trie, 0, sizeof(trie));
memset(sum, 0, sizeof(sum));
}
return 0;
}