天天看點

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