hdu2896 AC自動機

來源:互聯網
上載者:User
#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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.