题解 SP4033 【PHONELST - Phone List】
蒟蒻新学Trie树,本题为Trie树板子题.`
边建立Trie树的时候边判断答案,
- 若当前串插入后没有任何新建节点,则该串肯定是之前插入的某个串的前缀,
- 若在插入的时候,有某个经过的节点带有某串结尾的标记,则之前插入的某个串是当前串的前缀.
(详细见注释)
#include<bits/stdc++.h>
using namespace std;
#define RN register int
const int N=1e5+5;
const int Z=10;
int T,n,tot;
int ch[N][Z];//表示该节点的字符指针指向的节点,若为0,则无子节点
bool bo[N];
char s[20];
inline bool insert(char *s)//插入串,并判断.
{
int len=strlen(s);
int u=1;
bool flag=false;
for(RN i=0;i<len;i++)
{
int c=s[i]-'0';
if(!ch[u][c])//如果当前这个节点u没有指向c的指针,则建立一个
ch[u][c]=++tot;
else if(i==len-1)//如果搜完了,没有插入任何的新节点,则说明该串出现过,第1种情况
flag=true;
u=ch[u][c];
if(bo[u])//如果经过某个有标记的节点,属于第2种情况
flag=true;
}
bo[u]=true;
return flag;
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
tot=1;//新建一个Trie树,其根节点为1
memset(ch,0,sizeof(ch));
memset(bo,false,sizeof(bo));//每次都要初始化
bool ans=false;
for(RN i=1;i<=n;i++)
{
scanf("%s",s);
if(insert(s))
ans=true;
}
if(!ans)//注意不要写反
puts("YES");
else
puts("NO");
}
return 0;
}