hihoCoder-1036 (AC自动机模板题)

题目大意:判断模式串中是否出现模板。

代码如下:

# include<iostream>
# include<cstdio>
# include<queue>
# include<cstring>
# include<algorithm>
using namespace std;

const int N=1000000;

int cnt;
int ch[N+5][26];
int f[N+5],val[N+5];

void init()
{
	cnt=0;
	memset(ch,0,sizeof(ch));
	memset(val,0,sizeof(val));
}

int idx(char x)
{
	return x-'a';
}

void insert(char *p)
{
	int n=strlen(p);
	int root=0;
	for(int i=0;i<n;++i){
		int c=idx(p[i]);
		if(!ch[root][c]) ch[root][c]=++cnt;
		root=ch[root][c];
	}
	val[root]=1;
}

void getFail()
{
	queue<int>q;
	f[0]=0;
	for(int i=0;i<26;++i) if(ch[0][i]){
		f[ch[0][i]]=0;
		q.push(ch[0][i]);
	}
	while(!q.empty()){
		int u=q.front();
		q.pop();
		if(val[f[u]]) val[u]=1;
		for(int i=0;i<26;++i){
			if(ch[u][i]){
				q.push(ch[u][i]);
				f[ch[u][i]]=ch[f[u]][i];
			}else{
				ch[u][i]=ch[f[u]][i];
			}
		}
	}
}

char p[N+5];

bool match(char *p)
{
	int n=strlen(p);
	int u=0;
	for(int i=0;i<n;++i){
		int c=idx(p[i]);
		u=ch[u][c];
		if(val[u]) return true;
	}
	return false;
}

int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		init();
		for(int i=0;i<n;++i){
			scanf("%s",p);
			insert(p);
		}
		getFail();
		scanf("%s",p);
		if(match(p)) printf("YES
");
		else printf("NO
");
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/20143605--pcx/p/5947836.html