字典树模板

不是洛谷的题?!

第一次学字典树,先抄了个一本通上的代码。

  • 坑点:
    有输出\(NO\),没有是\(YES\)

他这里根节点编号为1,这就要初始化\(tot=1\),(想起来了线段树。。。)一般来说根节点设为0,就不用了初始化了。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 1e5+5;
const int Z = 10;
int T,n,tot,ch[N][Z];
bool book[N];
char s[20];
bool insert(char s[])
{
	int len=strlen(s);
	int u=1;
	bool flag=false;
	for(int i=0;i<len;i++)
	{
		int c=s[i]-'0';
		if(!ch[u][c]) 
		 ch[u][c]=++tot;
		else if(i==len-1)
		        flag=true;
		u=ch[u][c];
		if(book[u]) flag=true;
	}
	book[u]=true;
	return flag;
}
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		tot=1;
		memset(ch,0,sizeof(ch));
		memset(book,0,sizeof(book));
		bool ans=false;
		for(int i=1;i<=n;i++)
		{
			scanf("%s",s);
			if(insert(s)) ans=true;
		}
		if(!ans) printf("YES\n");
		else printf("NO\n");
	}
	return 0;
}
posted @ 2019-09-03 21:54  蟹蟹王  阅读(149)  评论(0编辑  收藏  举报