【HDU 2222】Keywords Search AC自动机模板题

参考iwtwiioi的模板写出来的。上午gty讲的并没有听懂,只好自己慢慢对着模板理解。

在HDU上为什么相同的程序提交有时T有时A!!!

奉上sth神犇的模板(不是这道题):

  

然后是我的ACcode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define for1(i,a,n) for(int i=(a);i<=(n);++i)
#define for2(i,a,n) for(int i=(a);i<(n);++i)
#define for3(i,a,n) for(int i=(a);i>=(n);--i)
#define for4(i,a,n) for(int i=(a);i>(n);--i)
#define CC(i,a) memset(i,a,sizeof(i));
using namespace std;
char a[10010],s[1000010];
int ch[500010][30],fail[500010],w[500010],ans,cnt;
inline void ins(char *b){
    int u=0,v,len=strlen(b);
    for2(i,0,len){
        v=b[i]-'a';
        if (!ch[u][v])ch[u][v]=cnt++;
        u=ch[u][v];
    }w[u]++;
}
inline void bfs(){
    queue<int>q;
    q.push(0);
    int u,p;
    while (!q.empty()){
        u=q.front();q.pop();
        for2(i,0,26) if (ch[u][i]){
            q.push(ch[u][i]);
            if (!u) continue;
            p=fail[u];
            while (p&&!ch[p][i])p=fail[p];
            fail[ch[u][i]]=ch[p][i];
        }
    }
}
inline void ac(char *b){
    int u=0,v,len=strlen(b),t;
    for2(i,0,len){
        v=b[i]-'a';
        while (u&&!ch[u][v])u=fail[u];
        u=ch[u][v];
        t=u;
        while (t){
            ans+=w[t];
            w[t]=0;
            t=fail[t];
        }
    }
}
inline void init(){CC(fail,0);CC(ch,0);CC(w,0);ans=0;cnt=1;}
int main(){
    int T;scanf("%d",&T);
    while (T--){
        init(); int n;
        scanf("%d",&n);
        for1(i,1,n){
            scanf("%s",a);
            ins(a);
        }bfs();
        scanf("%s",s);
        ac(s);
        printf("%d\n",ans);
    }return 0;
}

  

posted @   abclzr  阅读(179)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· MQ 如何保证数据一致性?
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
点击右上角即可分享
微信分享提示