HDU 2896 病毒侵袭(AC自动机)
题目链接:hdu2896
题意:
给你一组模板,然后在给你多个文本,要你去匹配文本,看看每个文本中都出现了哪些模板然后输出即可.
分析:
本题的模板不会重复,题目中已说明.
不过本题的字符是所有ASCII码可见字符,所以sigma_size=128.
结构体中的val对每个模板的结束结点进行标记,记录他是属于哪个模板的
查找的时候找到之后就存在一个数组中,同时将该病毒标记为已经检查过了.
AC代码:
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int maxnode=100000+100;
const int sigma_size=130;
int ans;
int n,m;
int a[20];
bool vis[1000];//病毒
struct AC_Automata
{
int ch[maxnode][sigma_size];
int val[maxnode];//用于保存当前单词输入了几遍,当用find扫描文本的时候,只要遇到该单词就+val[i]且让vis[i]=false,使得下次遇到该模板不会重复计算
int f[maxnode];
int last[maxnode];
int sz;
void init()
{
sz=1;
memset(ch[0],0,sizeof(ch[0]));
last[0]=f[0]=val[0]=0;
}
void insert(char *s,int num)
{
int n=strlen(s),u=0;
for(int i=0;i<n;i++)
{
int id=s[i];
if(ch[u][id]==0)
{
ch[u][id]=sz;
memset(ch[sz],0,sizeof(ch[sz]));
val[sz++]=0;
}
u=ch[u][id];
}
val[u]=num;//标记为第几个病毒
}
void print(int i)
{
if(val[i])
{
if(!vis[val[i]])
{
a[ans++]=val[i];
vis[val[i]]=true;
}
print(last[i]);
}
}
void find(char *s)
{
int n=strlen(s),j=0;
for(int i=0;i<n;i++)
{
int id=s[i];
while(j && ch[j][id]==0) j=f[j];
j=ch[j][id];
if(val[j]) print(j);
else if(last[j]) print(last[j]);
}
}
void getFail()
{
queue<int> q;
f[0]=0;
for(int i=0;i<sigma_size;i++)
{
int u=ch[0][i];
if(u)
{
last[u]=f[u]=0;
q.push(u);
}
}
while(!q.empty())
{
int r=q.front();q.pop();
for(int i=0;i<sigma_size;i++)
{
int u=ch[r][i];
if(!u) continue;
q.push(u);
int v=f[r];
while(v && ch[v][i]==0) v=f[v];
f[u]=ch[v][i];
last[u] = val[f[u]]?f[u]:last[f[u]];
}
}
}
};
AC_Automata ac;
char word[250],text[10100];
int main()
{
while(~scanf("%d",&n)&&n)
{
ac.init();
for(int i=1;i<=n;i++)
{
scanf("%s",word);
ac.insert(word,i);
}
ac.getFail();
int tot=0;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
scanf("%s",text);
ans=0;
memset(vis,false,sizeof vis);
ac.find(text);
if(ans>0)
{
sort(a,a+ans);
printf("web %d:",i);
tot++;
for(int j=0;j<ans;j++)
printf(" %d",a[j]);
printf("\n");
}
}
printf("total: %d\n",tot);
}
return 0;
}