模板——AC自动机

#include<bits/stdc++.h>
using namespace std;
struct nob{
	int fail,son[27],ed;
}a[1000000];
int cnt=0;
void build (string s){
	int now=0;
	for (int i=0; i<s.length(); i++){
		if (a[now].son[s[i]-'a']==0)
			a[now].son[s[i]-'a']=++cnt;
		now=a[now].son[s[i]-'a'];
	}
	a[now].ed++;
}
void fail(){
	queueque;
	for (int i=0; i<26; i++){
		if (a[0].son[i]!=0){
			a[a[0].son[i]].fail=0;
			que.push(a[0].son[i]);
		}
	}
	while (que.size()){
		int pos=que.front();
		que.pop();
		for (int i=0; i<26; i++){
			if (a[pos].son[i]!=0){
				a[a[pos].son[i]].fail=a[a[pos].fail].son[i];
				que.push(a[pos].son[i]);
			}
			else a[pos].son[i]=a[a[pos].fail].son[i];
		}
	}
}
int answer(string s){
	int now=0,ans=0;
	for (int i=0; i<s.length(); i++){
		now=a[now].son[s[i]-'a'];
		for (int t=now; t&&a[t].ed!=-1; t=a[t].fail){
			ans+=a[t].ed;
			a[t].ed=-1;
		}
	}
	return ans;
}
int main(){
	int n;
	string s;
	cin>>n;
	for (int i=1; i<=n; i++){
		cin>>s;
		build(s);
	}
	a[0].fail=0;
	fail();
	cin>>s;
	cout<<answer(s)<<endl;
	return 0;
}
posted @ 2017-09-29 14:54  |斗蜂|  阅读(162)  评论(0编辑  收藏  举报