hdu2896 AC自动机

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
struct node
{
    int flag;
    node *next[100];
    node *fail;
    node():flag(0)
    {
        memset(next,0,sizeof(next));
        fail=0;
    }
};
node *root;
void insert(char *str,int s)
{
    int i;
    int l=strlen(str);
    node *p=root;
    for(i=0;i<l;i++)
    {
        int k=str[i]-32;
        if(p->next[k]==0)
            p->next[k]=new node;
        p=p->next[k];
    }
    p->flag=s;

}
void build_fail()
{
    queue<node *> q;
    node *p=root;
    p->fail=0;
    q.push(p);
    while(!q.empty())
    {
        node* p=q.front();
        q.pop();
        int i;
        for(i=0;i<100;i++)
        {
            if(p->next[i]!=0)
            {
                node *temp=p->fail;
                while(temp)
                {
                    if(temp->next[i]!=0)
                    {
                        p->next[i]->fail=temp->next[i];
                        break;
                    }
                    temp=temp->fail;
                }
                if(temp==0)
                    p->next[i]->fail=root;
                q.push(p->next[i]);
            }
        }
    }
}
int a[5];
int cas=0;
int ac_find(char *str)
{
    int i,l=strlen(str);
    node *p=root;
    for(i=0;i<l;i++)
    {
        int k=str[i]-32;
        while(p->next[k]==0&&p!=root)
            p=p->fail;
        p=p->next[k]==0?root:p->next[k];
        node *temp=p;
        while(temp!=root)
        {
            if(temp->flag!=0)
                a[cas++]=temp->flag;
            //temp->flag=-1;
            temp=temp->fail;
        }
    }
    if(cas==0)
        return 0;
    else
        return 1;

}
char str[10005];
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int i;
        root= new node;
        getchar();
        for(i=1;i<=n;i++)
        {
            gets(str);
            insert(str,i);
        }
        int m;
        scanf("%d",&m);
        int s=0;
        getchar();
        build_fail();
        for(i=1;i<=m;i++)
        {
            cas=0;
            gets(str);
            if(ac_find(str))
            {
                sort(a,a+cas);
                int j;
                printf("web %d:",i);
                for(j=0;j<cas;j++)
                    printf(" %d",a[j]);
                printf("\n");
                s++;
            }

        }
        printf("total: %d\n",s);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值