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

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值