您的位置:首页 > 其它

hdu2896病毒侵袭(ac自动机,求模式串出现的个数)

2015-09-01 15:02 295 查看
题目连接:点击打开链接

题目描述:给定一些字符串和一些文本,找出每个文本中出现的所有字符串?

解题思路:很裸的一道ac自动机题目

代码:

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
priority_queue<int,vector<int>,greater<int> >pq;
struct Trie
{
int next[210*500][128],fail[210*500],ends[210*500];
int root,L,id;
int newnode()
{
for(int i=0; i<128; i++)
next[L][i]=-1;
ends[L++]=0;
return L-1;
}
void init()
{
L=0;
id=0;
root=newnode();
}
void insert_Node(char buf[])
{
int len=strlen(buf);
int now=root;
for(int i=0; i<len; i++)
{
if(next[now][buf[i]]==-1)
next[now][buf[i]]=newnode();
now=next[now][buf[i]];
}
ends[now]=++id;
}
void build()
{
queue<int> q;
fail[root]=root;
for(int i=0; i<128; i++)
if(next[root][i]==-1)
next[root][i]=root;
else
{
fail[next[root][i]]=root;
q.push(next[root][i]);
}
while(!q.empty())
{
int now=q.front();
q.pop();
for(int i=0; i<128; i++)
{
if(next[now][i]==-1)
next[now][i]=next[fail[now]][i];
else
{
fail[next[now][i]]=next[fail[now]][i];
q.push(next[now][i]);
}
}
}
}
void query(char buf[])
{
int len=strlen(buf);
int now=root;
for(int i=0; i<len; ++i)
{
now=next[now][buf[i]];
int temp=now;
while(temp!=root)
{
if(ends[temp]!=0)
pq.push(ends[temp]);
temp=fail[temp];
}
}
}
} tr; ///作为全局变量即可
char st[210];
char text[10010];
int n,m;
int main()
{
while(scanf("%d",&n)==1)
{
tr.init();
for(int i=0; i<n; ++i)
{
scanf("%s",st);
tr.insert_Node(st);
}
tr.build();
scanf("%d",&m);
int sum=0;
for(int i=1; i<=m; i++)
{
scanf("%s",text);
tr.query(text);
int len=pq.size();
int flag = -1;//标记重复出现的
int topp;
if(len>0)
{
sum++;
printf("web %d:",i);
while(!pq.empty())
{
topp = pq.top();
if(topp != flag)
printf(" %d",pq.top());
flag = topp;;
pq.pop();
}
printf("\n");
}
}
printf("total: %d\n",sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: