AC自動機(初學模板)

Keywords Search

In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.

Wiskey also wants to bring this feature to his image retrieval system.

Every image have a long description, when users type some keywords
to find the image, the system will match the keywords with description
of image and show the image which the most keywords be matched.

To simplify the problem, giving you a description of image, and
some keywords, you should tell me how many keywords will be match.

    Input
    First line will contain one integer means how many cases will follow by. 

Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)

Each keyword will only contains characters ‘a’-‘z’, and the length will be not longer than 50.

The last line is the description, and the length will be not longer than 1000000.

    Output
    Print how many keywords are contained in the description.

題意:有一組文本串,一個模式串,求模式串中包含多少種文本串。

AC自動機(由字典樹和fail[]指針構成)

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>

#define lowbits(x) x&(-x)
#define ml root<<1
#define mr root<<1|1
#define maxn 500055
#define N 1000005
using namespace std;
int mp[maxn][26],p[maxn],fail[maxn];
int cnt=1;
void build_trie(char str[])    //構建字典樹;
{
    int root=0,len,i,pos;
    len=strlen(str);
    for(i=0;i<len;++i){
        pos=str[i]-'a';
        if(!mp[root][pos]) mp[root][pos]=++cnt;
        root=mp[root][pos];
    }
    p[root]++;
}
void get_fail()  //得到fail[]指針,bfs搜索,匹配最長子鏈;
{
    fail[0]=0;
    queue<int> q;
    for(int i=0;i<26;++i){     //將字典樹中的第一層元素壓入隊列,並將其fail[]指針指向根節點;
        if(mp[0][i]){
            fail[mp[0][i]]=0;
            q.push(mp[0][i]);
        }
    }
    while(!q.empty()){        //寬搜;
        int now=q.front();
        q.pop();
        for(int i=0;i<26;++i){
            if(mp[now][i]){
                fail[mp[now][i]]=mp[fail[now]][i];  //將fail[]指針指向上一層的與之相匹配的節點;
                q.push(mp[now][i]);
            }
            else{
                mp[now][i]=mp[fail[now]][i];  //若元素結束了,將該元素的節點設置爲上一元素的位置;
            }
        }
    }
}
int query(char str[])    //查找,主要是設置不同的數組來實現功能;
{
    int root=0,len,pos,i,ans=0;
    len=strlen(str);
    for(i=0;i<len;++i){
        pos=str[i]-'a';
        root=mp[root][pos];
        for(int j=root;j&&~p[j];j=fail[j]){
            ans+=p[j];
            p[j]=-1;
        }
    }
    return ans;
}
int main()
{
    int t,n,i;
    char str[N];
    scanf("%d",&t);
    while(t--){
        memset(mp,0,sizeof(mp));
        memset(p,0,sizeof(p));
        scanf("%d",&n);
        cnt=1;
        for(i=0;i<n;++i){
            scanf("%s",str);
            build_trie(str);
        }
        get_fail();
        scanf("%s",str);
        printf("%d\n",query(str));
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章