您的位置:首页 > 其它

hdu2896 AC自动机

2013-01-13 13:28 232 查看
#include<iostream>
#include<cstdio>
#include<queue>
#include<string.h>
#include<algorithm>
#define kind 94
using namespace std;
struct node
{
int pox;
struct node *fail;
struct node *next[kind];
node()
{
pox=0;
for(int i=0; i<kind; i++)
next[i]=NULL;
}
};
char st[210],st1[10010];
int ans[10],s=0,flag=0;
int cmp(int a,int b)
{
return a<b;
}
void buildTree(char *word,struct node *root,int pox)
{
int len=strlen(word);
int index;
struct node *temp=root;
for(int i=0; i<len; i++)
{
index=word[i]-32;
if(temp->next[index]==NULL)
temp->next[index]=new node();
temp=temp->next[index];
}
temp->pox=pox;
}
void BFS(struct node *root)
{
queue<struct node*>q;
struct node *temp,*p;
root->fail=NULL;
q.push(root);
while(!q.empty())
{
temp=q.front();
q.pop();
for(int i=0; i<kind; i++)
{
if(temp->next[i]!=NULL)
{
if(temp==root)temp->next[i]->fail=root;
else
{
p=temp->fail;
while(p!=NULL)
{

if(p->next[i]!=NULL)
{
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL)
temp->next[i]->fail=root;
}
q.push(temp->next[i]);
}
}
}

}
void find(struct node *root)
{
int cnt=0,index;
int len=strlen(st1);
struct node *p=root;
for(int i=0; i<len; i++)
{
index=st1[i]-32;
while(p->next[index]==NULL&&p!=root)
p=p->fail;
p=(p->next[index]==NULL?root:p->next[index]);
struct node *temp=p;
while(temp!=root)
{
if(temp->pox!=0)
{

flag=1;
ans[s]=temp->pox;
s++;
break;
}
temp=temp->fail;
//  printf("sdfsdf\n");
}
}
}
int main()
{
int N,M;
scanf("%d",&N);
struct node *root=new node();
for(int i=1; i<=N; i++)
{
scanf("%s",st);
buildTree(st,root,i);
}
BFS(root);
scanf("%d",&M);
int t;
int sum=0;
for(int i=1; i<=M; i++)
{
flag=0;
scanf("%s",st1);
find(root);
if(flag)
{
sum++;
printf("web %d:",i);
sort(ans,ans+s,cmp);
for(int i=0;i<s;i++)
printf(" %d",ans[i]);
printf("\n");
}

s=0;
memset(ans,0,sizeof(ans));
}
printf("total: %d\n",sum);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: