HDU P2222 Keywords Search

AC自动机模板题

下面是代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
string s,m;
int T,n,sz,ans;
int a[500001][27],q[500001];
int point[500001],danger[500001];
bool mark[500001];
void ins(){
    int now=1,l=s.length();
    for(int i=0;i<l;i++){
        int t=s[i]-'a'+1;
        if(!a[now][t]){
        	a[now][t]=++sz;
		}
		now=a[now][t];
    }
    danger[now]++;
}
void acmach(){
    int t=0,w=1,now;
    q[0]=1;point[1]=0;
    while(t<w){
        now=q[t++];
        for(int i=1;i<=26;i++){
            if(!a[now][i]){
            	continue;
			}
            int k=point[now];
            while(!a[k][i]){
            	k=point[k];
			}
            point[a[now][i]]=a[k][i];
            q[w++]=a[now][i];
        }
    }
}
void solve(){
    int k=1,l=m.length()-1;
    for(int i=0;i<l;i++){
        mark[k]=1;
        int t=m[i]-'a'+1;
        while(!a[k][t]){
        	k=point[k];
		}
        k=a[k][t];
        if(!mark[k]){
        	for(int j=k;j;j=point[j]){
                ans+=danger[j];
                danger[j]=0;
            }
		}
    }
    cout<<ans<<endl;
}
int main(){
    cin>>T;
    while(T--){
        sz=1;ans=0;
        cin>>n;
        for(int i=1;i<=26;i++){
        	a[0][i]=1;
		}
        while(n--){
        	cin>>s;
            ins();
        }
        acmach();
        cin>>m;
        solve();
        for(int i=1;i<=sz;i++){
            point[i]=danger[i]=mark[i]=0;
            for(int j=1;j<=26;j++){
            	a[i][j]=0;
			}
        }
    }
    return 0;
}
/*
in:
1
5
she
he
say
shr
her
yasherhs

out:
3
*/ 


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值