hdu 3065 ac自動機

把長串裏面不是A到Z的全部變爲一種字符,多組輸入

#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=1e5+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 trie[maxn][27],fail[maxn],cnt[maxn];
int tot=0;
int ans[1050];
char a[1050][100],aa[maxn*20];

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

void insert(char s[],int id)
{
    int p=0;
    int len=strlen(s);
    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]=id;
}

void get_fail()
{
    queue<int>q;
    for(int i=0;i<26;i++){
        if(trie[0][i]!=0){
            fail[ trie[0][i] ]=0;
            q.push(trie[0][i]);
        }
    }
    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];
            }
        }
    }
}

void query(char s[])
{
    int len=strlen(s);
    int p=0;
    for(int i=0;i<len;i++){
        int c=s[i]-'A';
        p=trie[p][c];
        if(c<0 || c>25)p=0;
        for(int j=p;j!=0;j=fail[j]){
            if(cnt[j]!=0){
                ans[ cnt[j] ]++;
            }
        }
    }
}

int main()
{
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    int n;
    while(~scanf("%d",&n)){
        init();
        for(int i=1;i<=n;i++){
            scanf("%s",a[i]);
            insert(a[i],i);
        }
        get_fail();
        scanf("%s",aa);
        query(aa);
        for(int i=1;i<=n;i++){
            if(ans[i]>0){
                printf("%s: %d\n",a[i],ans[i]);
            }
        }
    }
    return 0;
}


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