hdu 2222 ac自動機初學

求父串中出現子串的次數

#include <bits/stdc++.h>
#define eps 1e-14
#define pi acos(-1)
#define ll long long
#define RD T*(rand()*2-RAND_MAX)
#define Drand (long double)rand()/RAND_MAX
#define LINF 0x7f7f7f7f7f7f7f7f
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=5e5+50;
const long long mod=1e18;
ll MOD(ll a,ll m){return a>m?a%m+m:a;}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}

int tot=0;
int fail[maxn],trie[maxn][27],cnt[maxn];
char S1[100],S2[maxn*2];

void init()
{
    tot=0;
    memset(fail,0,sizeof fail);
    memset(trie,0,sizeof trie);
    memset(cnt,0,sizeof cnt);
}

void insert(char s[])
{
    int len=strlen(s);
    int p=0;
    for(int i=0;i<len;i++){
        int c=s[i]-'a';
        if(trie[p][c]==0)
            trie[p][c]=++tot;
        p=trie[p][c];
    }
    cnt[p]++;
}

void get_fail()
{
    queue<int>q;
    for(int i=0;i<26;i++){
        int x=trie[0][i];
        if(x!=0){
            fail[x]=0;
            q.push(x);
        }
    }
    while(!q.empty()){
        int now=q.front();
        q.pop();
        for(int i=0;i<26;i++){
            int x=trie[now][i];
            if(x!=0){
                fail[x]=trie[ fail[now] ][i];
                q.push(x);
            }
            else{
                trie[now][i]=trie[ fail[now] ][i];
            }
        }
    }
}

int query(char s[])
{
    int p=0,ans=0;
    int len=strlen(s);
    for(int i=0;i<len;i++){
        p=trie[p][ s[i]-'a' ];
        for(int j=p;j!=0 && cnt[j]!=-1;j=fail[j]){
            ans+=cnt[j];
            cnt[j]=-1;
        }
    }
    return ans;
}

int main()
{
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    int t;
    scanf("%d",&t);
    while(t--){
        init();
        int n;
        scanf("%d",&n);
        while(n--){
            scanf("%s",S1);
            insert(S1);
        }
        get_fail();
        scanf("%s",S2);
        int ans=query(S2);
        printf("%d\n",ans);
    }
    return 0;
}

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