[Trie树] BZOJ 1819 [JSOI]Word Query电子字典

Trie树上暴力

复杂度不虚

#include<cstdio>
#include<cstdlib>
#include<cstring>
#define cl(x) memset(x,0,sizeof(x))
using namespace std;

inline char nc()
{
	static char buf[100000],*p1=buf,*p2=buf;
	if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
	return *p1++;
}

inline void read(int &x){
	char c=nc(),b=1;
	for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
	for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

inline int read(char *s){
	char c=nc(); int len=0;
	for (;!(c>='a' && c<='z');c=nc());
	for (;c>='a' && c<='z';s[++len]=c,c=nc()); s[++len]=0; return len-1;
}

int clk;

struct TRIE{
	struct node{
		int ch[26];
		int val,tim;
	}T[200005];
	int rt,cnt;
	TRIE(){
		rt=++cnt;
	}
	void add(char *s,int len){
		int p=rt;
		for (int i=1;i<=len;i++)
		{
			if (!T[p].ch[s[i]-'a']) T[p].ch[s[i]-'a']=++cnt;
			p=T[p].ch[s[i]-'a'];
		}
		T[p].val=1;
	}
	int query(char *s,int* nxt){
		int p=rt;
		for (int i=nxt[0];i;i=nxt[i])
		{
			if (!T[p].ch[s[i]-'a']) return 0;
			p=T[p].ch[s[i]-'a'];
		}
		if (!T[p].val || (T[p].val && T[p].tim==clk)) return 0;
		T[p].tim=clk; return 1;
	}
}Trie;

int n,m,len,ans;
char str[25];
int nxt[25];
int vst[10005];

int main()
{
	freopen("t.in","r",stdin);
	freopen("t.out","w",stdout);
	read(n); read(m);
	for (int i=1;i<=n;i++)
	{
		len=read(str);
		Trie.add(str,len);
	}
	for (int i=1;i<=m;i++)
	{
		clk++;
		len=read(str);
		cl(nxt);
		for (int i=0;i<len;i++)
			nxt[i]=i+1;
		nxt[len]=0;
		if (Trie.query(str,nxt))
			printf("-1\n");
		else
		{
			ans=0;
			for (int i=1;i<=len;i++)
			{
				nxt[i-1]=nxt[i];
				ans+=Trie.query(str,nxt);
				nxt[i-1]=i;
			}
			for (int i=1;i<=len;i++)
			{
				char ch=str[i];
				for (int j=0;j<26;j++)
					if (ch!='a'+j)
					{
						str[i]='a'+j;
						ans+=Trie.query(str,nxt);
					}
				str[i]=ch;
			}
			for (int j=0;j<26;j++)
			{
				str[len+1]='a'+j;
				for (int i=0;i<=len;i++)
				{
					nxt[len+1]=nxt[i]; nxt[i]=len+1; 
					ans+=Trie.query(str,nxt);
					nxt[i]=nxt[len+1];
				}
			}		
			printf("%d\n",ans);
		}
	}
	return 0;
}

    原文作者:Trie树
    原文地址: https://blog.csdn.net/u014609452/article/details/51181887
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞