您的位置:首页 > 其它

HDU2222 Keywords Search(AC自动机模版题)

2015-10-10 17:38 316 查看
邝斌大神的模版mark一下

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
using namespace std;
struct Trie
{
int next[500010][26],fail[500010],end[500010];
int root,l;
int newnode()
{
for(int i=0; i<26; i++)
next[l][i]=-1;
end[l++]=0;
return l-1;
}
void init()
{
l=0;
root=newnode();
}
void insert(char buf[])
{
int len=strlen(buf);
int now=root;
for(int i=0; i<len; i++)
{
if(next[now][buf[i]-'a']==-1) next[now][buf[i]-'a']=newnode();
now=next[now][buf[i]-'a'];
}
end[now]++;
}
void build()
{
queue<int>q;
fail[root]=root;
for(int i=0; i<26; 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<26; 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]);
}
}
}
}
int query(char buf[])
{
int len=strlen(buf);
int now=root;
int res=0;
for(int i=0;i<len;i++)
{
now=next[now][buf[i]-'a'];
int temp=now;
while(temp!=root)
{
res+=end[temp];
end[temp]=0;
temp=fail[temp];
}
}
return res;
}
};
char buf[1000010];
Trie ac;
int main()
{
//freopen("in.txt","r",stdin);
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
ac.init();
for(int i=0; i<n; i++)
{
scanf("%s",buf);
ac.insert(buf);
}
ac.build();
scanf("%s",buf);
printf("%d\n",ac.query(buf));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: