您的位置:首页 > 其它

hdu2222 AC自动机入门 指针型模板

2013-07-03 20:22 323 查看
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#include <algorithm>
#include <ctime>
#include <vector>
#include <string>
#include <stack>
#include <queue>
using namespace std;
#define maxnode 10000*100
#define sigma_size 26
struct Node
{
Node *fail;
Node *nxt[sigma_size];
int count;
Node()
{
fail=NULL;
memset(nxt,NULL,sizeof(nxt));
count=0;
}
}*q[maxnode];

void insert(Node *root,char *str)
{
Node *p=root;
for(int i=0;str[i]!='\0';++i)
{
if(p->nxt[str[i]-'a']==NULL)
p->nxt[str[i]-'a']=new Node();
p=p->nxt[str[i]-'a'];
}
p->count++;
}
void getfail(Node *root)
{
Node *u,*t,*p;
root->fail=NULL;
int head=0,tail=0;
q[tail++]=root;
while(head<tail)
{
u=q[head++];
for(int i=0;i<sigma_size;++i)
if(u->nxt[i]!=NULL)
{
if(u==root)
u->nxt[i]->fail=root;
else
{
p=u->fail;
while(p!=NULL)
{
if(p->nxt[i]!=NULL)
{
u->nxt[i]->fail=p->nxt[i];
break;
}
p=p->fail;
}
if(p==NULL)
u->nxt[i]->fail=root;
}
q[tail++]=u->nxt[i];
}
}
}
int query(Node *root,char *str)
{
int res=0;
Node *p=root,*temp;
for(int i=0;str[i]!='\0';++i)
{
Node *pre=p;
while(p->nxt[str[i]-'a']==NULL && p!=root)
p=p->fail;
p=p->nxt[str[i]-'a'];
if(p==NULL)
p=root;
//if(p!=root)
//p=p->nxt[str[i]-'a'];
temp=p;
while(temp!=NULL && temp->count!=-1)
{
res+=temp->count;
temp->count=-1;
temp=temp->fail;
}
}
return res;
}
char str[100];
char T[1000500];
int main ()
{
int ncase,n;
scanf("%d",&ncase);
while(ncase--)
{
scanf("%d",&n);
Node *root=new Node();
for(int i=0;i<n;++i)
{
scanf("%s",str);
insert(root,str);
}
getfail(root);
scanf("%s",T);
int ans=query(root,T);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: