您的位置:首页 > 其它

HDU 2222 Keywords Search

2015-02-04 15:39 253 查看
ac自动机模板题。

#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<iomanip>
#include<map>
#include<algorithm>
#include<queue>
#include<set>
#define inf 10000000
#define pi acos(-1.0)
#define eps 1e-8
#define seed 131
using namespace std;
typedef pair<int,int> pii;
typedef unsigned long long ULL;
typedef long long LL;
const int maxn=100005;
char buf[1000005];
int n;
const int maxnode=500010;
const int sigma_size=26;
struct Trie{
    int root;
    int ch[maxnode][sigma_size];
    int val[maxnode];
    int fail[maxnode];
    int sz;
    Trie(){
        sz=1;root=0;
        memset(ch[0],0,sizeof(ch[0]));
    }
    void init()
    {
        sz=1;root=0;
        memset(ch[0],0,sizeof(ch[0]));
    }
    int idx(char c){
        return c-'a';
    }
    void insert(char* s)
    {
        int u=0,len=strlen(s);
        for(int i=0;i<len;i++)
        {
            int c=idx(s[i]);
            if(!ch[u][c]){
                memset(ch[sz],0,sizeof(ch[sz]));
                val[sz]=0;
                ch[u][c]=sz++;
            }
            u=ch[u][c];
        }
        val[u]++;
    }
    void build()
    {
        queue<int>que;
        fail[root]=root;
        for(int i=0;i<sigma_size;i++){
            if(ch[root][i]==0)
                ch[root][i]=root;
            else
            {
                fail[ch[root][i]]=root;
                que.push(ch[root][i]);
            }
        }
        while(!que.empty())
        {
            int now=que.front();
            que.pop();
            for(int i=0;i<sigma_size;i++)
            {
                if(ch[now][i]==0)
                    ch[now][i]=ch[fail[now]][i];
                else
                {
                    fail[ch[now][i]]=ch[fail[now]][i];
                    que.push(ch[now][i]);
                }
            }
        }
    }
    int query(char buf[])
    {
        int len=strlen(buf);
        int now=root;
        int ans=0;
        for(int i=0;i<len;i++)
        {
            now=ch[now][buf[i]-'a'];
            int temp=now;
            while(temp!=root)
            {
                ans+=val[temp];
                val[temp]=0;
                temp=fail[temp];
            }
        }
        return ans;
    }
};
Trie ac;
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        ac.init();
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%s",buf);
            ac.insert(buf);
        }
        ac.build();
        scanf("%s",buf);
        printf("%d\n",ac.query(buf));
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: