1 5 she he say shr her yasherhs
3
#include<stdio.h>
#include<string>
#include<string.h>
#include<iostream>
using namespace std;
char str[1001000],key[100];
int head,tail;
struct node
{
	node *fail;
	node *next[26];
	int cnt;
	node()
	{
		fail=NULL;
		cnt=0;
		for(int i=0;i<26;i++)
			next[i]=NULL;
	}
}*q[500050];
node *root;
void insert(char *s)
{
	int temp,len,i;
	node *p=root;
	len=strlen(s);
	for(i=0;i<len;i++)
	{
		temp=s[i]-'a';
		if(p->next[temp]==NULL)
			p->next[temp]=new node();
		p=p->next[temp];
	}
	p->cnt++;	
}
void build_ac()
{
	q[tail++]=root;
	while(head!=tail)
	{
		node *p=q[head++];
		node *temp=NULL;
		for(int i=0;i<26;i++)
		{
			if(p->next[i]!=NULL)
			{
				if(p==root)
					p->next[i]->fail=root;
				else
				{
					temp=p->fail;
					while(temp!=NULL)
					{
						if(temp->next[i]!=NULL)
						{
							p->next[i]->fail=temp->next[i];
							break;
						}
						temp=temp->fail;
					}
					if(temp==NULL)
					{
						p->next[i]->fail=root;
					}
				}
				q[tail++]=p->next[i];
			}
		}
	}
}
int query()
{
	int ans=0;
	int len=strlen(str);
	node *p=root,*temp;
	for(int i=0;i<len;i++)
	{
		int x=str[i]-'a';
		while(p->next[x]==NULL&&p!=root)
			p=p->fail;
		p=p->next[x];
		if(p==NULL)
		{
			p=root;
		}
		temp=p;
		while(temp!=root&&temp->cnt!=-1)
		{
			ans+=temp->cnt;
			temp->cnt=-1;
			temp=temp->fail;
		}
	}
	return ans;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n,i;
		scanf("%d",&n);
		head=tail=0;
		root=new node();
		for(i=0;i<n;i++)
		{
			scanf("%s",key);
			insert(key);
		}
		build_ac();
		scanf("%s",str);
		printf("%d\n",query());
	}
}HDOJ 题目2222 Keywords Search(AC自动机)
原文:http://blog.csdn.net/yu_ch_sh/article/details/44045271