hdu2896ac自动机模板

来源:互联网 发布:收购淘宝卖家账号 编辑:程序博客网 时间:2024/06/05 07:07

http://acm.hdu.edu.cn/showproblem.php?pid=2896

题意 给出多个病毒字符串 再给出多个文本串 记录每个文本串中带病毒串的编号和数量
模板,只要记录一下病毒的编号就可以了。
还有我用G++提交会MLE C++不会
可见的ASCI是32到127,n为95可以,

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <algorithm>using namespace std;const int maxn=500010;const int N=95;struct node{    node *fail;    node *next[N];    int num;    node()    {        fail=NULL;        num=0;        memset(next,NULL,sizeof(next));    }}*q[maxn];char str[10010];bool vis[510];int head,tail;void insert_Trie(char *str,node *root,int h){    node *p=root;    int i=0;    while(str[i])    {        int id=str[i]-' ';        if(p->next[id]==NULL) p->next[id]=new node();        p=p->next[id];i++;    }    p->num=h;}void build_ac(node *root){    root->fail=NULL;    q[head++]=root;    while(head!=tail)    {        node *temp=q[tail++];        node *p=NULL;        for(int i=0;i<N;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[head++]=temp->next[i];            }        }    }}int query(node *root){    int i=0,ans=0;    node *p=root;    while(str[i])    {        int id=str[i]-' ';        while(p->next[id]==NULL&&p!=root) p=p->fail;        p=p->next[id];        p=(p==NULL)?root:p;        node *temp=p;        while(temp!=root)        {            vis[temp->num]=1;            if(temp->num!=0)            ans++;            temp=temp->fail;        }        i++;    }    return ans;}int main(){    int n,m;    while(scanf("%d",&n)!=-1)    {        node *root=new node();        head=tail=0;        for(int i=0;i<n;i++)        {            scanf("%s",str);            insert_Trie(str,root,i+1);        }        build_ac(root);        scanf("%d",&m);        int sum=0;        for(int i=1;i<=m;i++)        {            scanf("%s",str);            memset(vis,0,sizeof(vis));            int f=query(root);            if(f)            {                sum++;                printf("web %d:",i);                for(int j=1;j<=n;j++)                {                    if(vis[j]) printf(" %d",j);                }                printf("\n");            }        }        printf("total: %d\n",sum);    }    return 0;}
0 0
原创粉丝点击