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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章