大意:
插入n个电话号码,如果其中有一个是另一个的前缀就输出NO。
思路
改造字典树模板,当最后一个字母插入时节点已存在或插入时该节点已标记为结尾,flag=false。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <map>
using namespace std;
int ans;
struct trie
{
int tot,root,c[100050][10];
bool flag[100050];
trie()
{
memset(c[1],0,sizeof(c[1]));
flag[1]=false;
root=tot=1;
}
void clear()
{
memset(c[1],0,sizeof(c[1]));
flag[1]=false;
root=tot=1;
}
void insert(const char *str)
{
int *cur=&root;
int len=strlen(str);
for(int i=0; i<len; i++)
{
cur=&c[*cur][str[i]-'0'];
if(flag[*cur]==true) ans=1;
if(i==len-1&&*cur!=0) ans=1;
if(*cur==0)
{
*cur=++tot;
memset(c[tot],0,sizeof(c[tot]));
flag[tot]=false;
}
}
flag[tot]=true;
}
} tree;
int main()
{
int T,n;
char ord[100];
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
ans=0;
tree.clear();
while(n--)
{
scanf("%s",ord);
tree.insert(ord);
}
if(ans)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}