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

你可能感兴趣的:(hdu2896 AC自动机)