AC自動機 病毒侵襲 hdu2896

和hdu2222題相似的水題

提示:

1)連着RE了好多發,沒想明白,看了一下網上題解才知道,輸入的不一定都是字母,所以next要開100!!!!!!!

#include <stdio.h>
#include <string.h>
int tot;
char str[10005];
int t;
//int time[100];
struct trie {
    trie *fail;
    trie *next[100];
    int num;
    trie() {
        for(int i=0; i<100; i++)
            next[i]=NULL;
        fail=NULL;
        num=0;
    }
}*queue[100005];
struct xxx
{
    int virus[505];
    int vt;
}web[1005];
trie *root;
void build() {                 //建立字典樹
    int len=strlen(str);
    trie *p=root;
    for(int i=0;i<len;i++) {
        int id=str[i]-' ';
        if(p->next[id]==NULL)
            p->next[id]=new trie();
        p=p->next[id];
    }
    if(p->num==0)
        p->num=tot++;         //給每一個單詞結尾附上序號
}
void build_fail() {           //構建失敗指針
    int i;
    trie *u,*v;
    int fr,ed;
    fr=ed=0;
    root->fail=NULL;
    queue[ed++]=root;
    while(fr<ed) {
        u=queue[fr++];
        v=NULL;
        for(i=0; i<100; i++) {
            if(u->next[i]!=NULL) {
                if(u==root)
                    u->next[i]->fail=root;
                else {
                    v=u->fail;
                    while(v!=NULL) {
                        if(v->next[i]!=NULL) {
                            u->next[i]->fail=v->next[i];
                            break;
                        }
                        v=v->fail;
                    }
                    if(v==NULL)
                        u->next[i]->fail=root;
                }
                queue[ed++]=u->next[i];
            }
        }
    }
}
void search(int n) {            //查找字符串
    int i=0;
    trie *p=root;
    while(str[i]) {
        int id=str[i]-' ';
        while(p->next[id]==NULL&&p!=root)
            p=p->fail;
        p=p->next[id];
        p=(p==NULL)?root:p;
        trie *q=p;
        while(q!=root)
        {
            if(q->num!=0)
            {
                web[n].virus[q->num]=1;    //記錄病毒種類
                web[n].vt++;          //統計個數
            }
            q=q->fail;
        }
        i++;
    }
}
int main() {
    int n;
    int i;
    scanf("%d",&n);
    tot=1;
    memset(web,0,sizeof(web));
    root=new trie();
    for(i=0; i<n; i++) {
        scanf("%s",str);
        build();
    }
    build_fail();
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%s",str);
        search(i);
    }
    t=0;
    for(int i=1;i<=n;i++)
    {
        if(web[i].vt!=0)
        {
            t++;
            printf("web %d:",i);
            for(int j=0;j<505;j++)
                if(web[i].virus[j]!=0)
                    printf(" %d",j);
            printf("\n");
        }
    }
    printf("total: %d\n",t);
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章