题意:
题意:给出n个串,然后给一篇文章,问这n个串有多少个在文章里面出现过。。。
trick:n个串可能有相同的,需按照不同串处理。
刚学ac自动机,没学明白,这代码也是照着别人博客写的,弱爆--#
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
using namespace std;
char str[1000000+100];
struct node
{
int count;
struct node *next[26];
struct node *fail;
void init()
{
for(int i=0;i<26;i++)
next[i]=NULL;
count=0;
fail=NULL;
}
}*root;
void insert()
{
node *p=root;
int len=strlen(str);
for(int i=0;i<len;i++)
{
int id=str[i]-'a';
if(p->next[id]==NULL)
{
p->next[id]=new node;
p->next[id]->init();
p=p->next[id];
}
else
p=p->next[id];
}
p->count++;
}
void getfail()
{
node *p=root,*temp,*son;
queue<struct node *>que;
que.push(p);
while(!que.empty())
{
temp=que.front();
que.pop();
for(int i=0;i<26;i++)
{
son=temp->next[i];
if(son!=NULL)
{
if(temp==root)
son->fail=root;
else
{
p=temp->fail;
while(p)
{
if(p->next[i])
{
son->fail=p->next[i];
break;
}
p=p->fail;
}
if(!p)
son->fail=root;
}
que.push(son);
}
}
}
}
void query()
{
int len=strlen(str);
int cnt=0;
node *p,*temp;
p=root;
for(int i=0;i<len;i++)
{
int id=str[i]-'a';
while(!p->next[id]&&p!=root) p=p->fail;
p=p->next[id];
if(!p) p=root;
temp=p;
while(temp!=root)
{
if(temp->count>=0)
{
cnt+=temp->count;
temp->count=-1;
}
else break;
temp=temp->fail;
}
}
printf("%d\n",cnt);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
root=new node;
root->init();
root->fail=NULL;
int n;
scanf("%d",&n);
getchar();
for(int i=0;i<n;i++)
{
gets(str);
insert();
}
getfail();
gets(str);
query();
}
return 0;
}