hdu3065 病毒侵袭持续中--AC自动机

来源:互联网 发布:移民澳大利亚知乎 编辑:程序博客网 时间:2024/05/17 06:25

wa了好多次,一直改,一直没发现错!

最后重新写了下A-Z的这个条件,才过了

现在还是不明白为什么之前的错了



#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;char str[2000004],a[1005][55];int r[1005];int head,tail;struct node{    node *fail;    node *next[26];    int countx,Id;    node ()    {        fail=NULL;        countx=0;        Id=0;        for(int i=0;i<26;i++)            next[i]=NULL;    }}*q[30005];node *root;void Insert(char *str,int tt){    int temp, len;    node *p = root;    len = strlen(str);    for(int i = 0; i < len; ++i)    {        temp = str[i] - 'A';        if(p->next[temp] == NULL)            p->next[temp] = new node();        p = p->next[temp];    }    p->countx++;    p->Id=tt;}void build(){    q[tail++] = root;    while(head != tail)    {        node *p = q[head++];        node *temp = NULL;        for(int i = 0; i <26; ++i)        {            if(p->next[i] != NULL)            {                if(p == root)                    p->next[i]->fail = root;                else                {                    temp = p->fail;                    while(temp != NULL)                    {                        if(temp->next[i] != NULL)                        {                            p->next[i]->fail = temp->next[i];                            break;                        }                        temp = temp->fail;                    }                    if(temp == NULL)                        p->next[i]->fail = root;                }                q[tail++] = p->next[i];            }        }    }}void query(){    int id,len;    node *p=root;    len=strlen(str);    for(int i=0;i<len;i++)    {        if(str[i]<'A'||str[i]>'Z') {p=root;continue;}        id=str[i]-'A';        while(p->next[id]==NULL&&p!=root)            p=p->fail;        p=p->next[id];        if(p==NULL) p=root;        node *temp=p;        while(temp!=root)        {            if(temp->countx==1) r[temp->Id]++;            temp=temp->fail;        }    }}int main(){    //freopen("in.txt","r",stdin);    int i,j,n;    while(scanf("%d",&n)!=EOF)    {        head=tail=0;        memset(r,0,sizeof(r));        root=new node();        for(i=1;i<=n;i++)        {            scanf("%s",a[i]);            Insert(a[i],i);        }        build();        getchar();        gets(str);        query();        for(i=1;i<=n;i++)        {            if(r[i]>0)            {                printf("%s: %d\n",a[i],r[i]);            }        }    }    return 0;}


0 0
原创粉丝点击