【模板】AC自动机

题目链接:【模板】AC 自动机(简单版) - 洛谷 

代码:

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int N=1000005;
int ch[N][26],fail[N],tot,en[N];

inline void build(const string&s){ //普通的trie树build函数
    int len=s.size(), x, u=0;
    for(int i=0; i<len; i++){
        x=s[i]-'a';
        if(!ch[u][x]) ch[u][x] = ++tot; //如果没有这个点,就建立
        u=ch[u][x];
    }
    en[u]++; //记录出现次数
}
inline void get_fail(){ //ac自动机的精髓,求解fail数组
    queue<int> q;
    for(int i=0; i<26; i++) //特别处理第一层
        if(ch[0][i]) q.push(ch[0][i]); //第一层结点加入队列
    //注意:所有第一层结点的fail值都没有处理过,也就是默认他们的fail值都是0,回到root点
    while(q.size()){ //bfs求fail指针
        int u=q.front(); q.pop(); //父结点
        for(int i=0; i<26; i++){
            if(ch[u][i]){ //有这个子结点
                fail[ch[u][i]] = ch[fail[u]][i]; //核心步骤,fail = fa->fail->child
                q.push(ch[u][i]);
            } else {ch[u][i] = ch[fail[u]][i];} //特殊处理,建立虚拟子结点,实际上相当于失配
        }
    }
}
int solve(const string&s){
	int u=0, res=0;
	for(char c:s){ //遍历文本串的所有字符
		u = ch[u][c-'a'];
		for(int t=u; t && en[t]!=-1; t=fail[t]){ //不断假设当前失配,遍历到所有匹配情况
            //en[t]==-1代表这条线已经遍历过,遍历过那不再重复计算贡献了
			res += en[t];
			en[t] = -1;
		}
	}
	return res;
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	int n; string s;
	cin>>n; for(int i=1; i<=n; i++) {cin>>s; build(s);}
	get_fail();
	cin>>s; cout<<solve(s)<<'\n';
}

update 4月6日

【模板】AC 自动机(加强版) - 洛谷 (做法和上面一样,水题)

#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define ROF(i, a, b) for (int i = (a); i >= (b); i--)
const int N=11000;
int n;
int ch[N][26],fail[N],tot,en[N],num[N];
string ss[180]; //所有模式串
map<int,int> mp; //{end_id, string_id}

inline void build(const string&s){ //普通的trie树build函数
    int len=s.size(), x, u=0;
    for(int i=0; i<len; i++){
        x=s[i]-'a';
        if(!ch[u][x]) ch[u][x] = ++tot; //如果没有这个点,就建立
        u=ch[u][x];
    }
    en[u]++; //记录出现次数
}
inline void get_fail(){ //ac自动机的精髓,求解fail数组
    queue<int> q;
    for(int i=0; i<26; i++) //特别处理第一层
        if(ch[0][i]) q.push(ch[0][i]); //第一层结点加入队列
    //注意:所有第一层结点的fail值都没有处理过,也就是默认他们的fail值都是0,回到root点
    while(q.size()){ //bfs求fail指针
        int u=q.front(); q.pop(); //父结点
        for(int i=0; i<26; i++){
            if(ch[u][i]){ //有这个子结点
                fail[ch[u][i]] = ch[fail[u]][i]; //核心步骤,fail = fa->fail->child
                q.push(ch[u][i]);
            } else {ch[u][i] = ch[fail[u]][i];} //特殊处理,建立虚拟子结点,实际上相当于失配
        }
    }
}
inline void init(){
    mp.clear();
    for(int i=1; i<=n; i++) num[i]=0; //出现次数重置
    ROF(i,tot,0){
        FOR(j,0,25) ch[i][j]=0;
        fail[i]=0;
        en[i]=0;
    }
    tot=0;
}
inline void solve(){
    init();
    string s;
    FOR(i,1,n) cin>>ss[i], build(ss[i]), mp[tot]=i; //记录映射
    get_fail();
    cin>>s;

    int u=0;
    for(char c:s){
        u=ch[u][c-'a'];
        for(int t=u; t; t=fail[t]){
            if(en[t]) num[mp[t]] += en[t]; //计算答案
        }
    }

    int ans=0;
    FOR(i,1,n) ans=max(ans,num[i]);
    cout<<ans<<'\n';
    FOR(i,1,n) if(num[i]==ans) cout<<ss[i]<<'\n';
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    while(cin>>n && n) solve();
}

 update 4月7日

【模板】AC 自动机(二次加强版) - 洛谷 (学到新东西,在需要遍历多次的情况下,不能用en=-1标记,暴力跳fail的时间复杂度是O(模式串长度之和*文本串长度,需要优化)

这里优化方法是遍历到每个点之后打上标记,最后一起处理,相当于差分的思路,但由于是个图,最后汇总的时候要按拓扑序,所以要拓扑排序。

#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define ROF(i, a, b) for (int i = (a); i >= (b); i--)
const int N=2e5+50;
int n;
int ch[N][26],fail[N],tot,en[N],cnt[N];
int id[N], ans[N], in[N]; //in表示入度

inline void build(int cur, const string&s){ //普通的trie树build函数
    int len=s.size(), x, u=0;
    for(int i=0; i<len; i++){
        x=s[i]-'a';
        if(!ch[u][x]) ch[u][x] = ++tot; //如果没有这个点,就建立
        u=ch[u][x];
    }
    en[u]=1; //记录出现次数
    id[cur] = u; //记录末尾标号
}
inline void get_fail(){ //ac自动机的精髓,求解fail数组
    queue<int> q;
    for(int i=0; i<26; i++) //特别处理第一层
        if(ch[0][i]) q.push(ch[0][i]); //第一层结点加入队列
    //注意:所有第一层结点的fail值都没有处理过,也就是默认他们的fail值都是0,回到root点
    while(q.size()){ //bfs求fail指针
        int u=q.front(); q.pop(); //父结点
        for(int i=0; i<26; i++){
            if(ch[u][i]){ //有这个子结点
                fail[ch[u][i]] = ch[fail[u]][i]; //核心步骤,fail = fa->fail->child
                in[ch[fail[u]][i]]++; //入度+1(这里用到优化自动机,要加上这步,用于拓扑排序)
                q.push(ch[u][i]);
            } else {ch[u][i] = ch[fail[u]][i];} //特殊处理,建立虚拟子结点,实际上相当于失配
        }
    }
}
inline void solve(){
    string s;
    FOR(i,1,n) cin>>s, build(i,s); //记录映射
    get_fail();
    cin>>s;

    int u=0;
    for(char c:s){
        u=ch[u][c-'a'];
        cnt[u]++; //访问次数+1(优化自动机不用跳fail,跳fail过程统一留到最后)
    }

    //下面开始拓扑排序处理标记
    queue<int> q;
    FOR(i,1,tot) if(in[i]==0) q.push(i);
    while(q.size()){
        int cur=q.front(); q.pop();
        ans[cur]=cnt[cur];

        int nxt = fail[cur];
        in[nxt]--;
        cnt[nxt] += cnt[cur];
        if(in[nxt]==0) q.push(nxt);
    }

    FOR(i,1,n) cout<<ans[id[i]]<<'\n';
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin>>n; solve();
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是AC动机Java模板题U301874的代码实现: ```java import java.io.*; import java.util.*; public class Main { static final int MAXN = 100010, MAXM = 200010; static final int INF = 0x3f3f3f3f; static int n, m, cnt; static int[] trie = new int[MAXN * 30], idx = new int[MAXN * 30]; static int[] fail = new int[MAXN * 30], vis = new int[MAXN * 30]; static int[] head = new int[MAXN], nxt = new int[MAXM], ver = new int[MAXM], tot; static int[] deg = new int[MAXN]; static char[][] str = new char[MAXN][30]; static Map<Character, Integer> map = new HashMap<>(); static int add(char[] s) { int p = 0; for (int i = 0; s[i] != '\0'; i++) { char c = s[i]; if (!map.containsKey(c)) { map.put(c, ++cnt); } int u = map.get(c); if (trie[p] == 0) { trie[p] = ++tot; } p = trie[p]; idx[p] = u; } return p; } static void build() { Queue<Integer> q = new LinkedList<>(); for (int i = 1; i <= cnt; i++) { int u = map.get(str[i][0]); if (trie[0] == 0) { trie[0] = ++tot; } int p = trie[0]; idx[p] = 0; if (trie[p + u] == 0) { trie[p + u] = ++tot; } fail[p + u] = p; q.offer(p + u); } while (!q.isEmpty()) { int u = q.poll(); for (int i = head[idx[u]]; i != 0; i = nxt[i]) { int v = ver[i]; int p = fail[u], q = 0; while (p != 0 && trie[p + v] == 0) { p = fail[p]; } if (trie[p + v] != 0) { q = trie[p + v]; } fail[u + v] = q; q.offer(u + v); } } } static void addEdge(int u, int v) { ver[++tot] = v; nxt[tot] = head[u]; head[u] = tot; } static void topo() { Queue<Integer> q = new LinkedList<>(); for (int i = 1; i <= tot; i++) { if (deg[i] == 0) { q.offer(i); } } while (!q.isEmpty()) { int u = q.poll(); vis[u] = 1; for (int i = head[u]; i != 0; i = nxt[i]) { int v = ver[i]; deg[v]--; if (deg[v] == 0) { q.offer(v); } } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); for (int i = 1; i <= n; i++) { String s = in.next(); str[i] = s.toCharArray(); add(str[i]); } m = in.nextInt(); for (int i = 1; i <= m; i++) { String s = in.next(); int len = s.length(); int p = 0; for (int j = 0; j < len; j++) { char c = s.charAt(j); if (!map.containsKey(c)) { break; } int u = map.get(c); if (trie[p + u] == 0) { break; } p = trie[p + u]; deg[p]++; addEdge(p, p + u); } } build(); topo(); for (int i = 1; i <= n; i++) { int p = 0; for (int j = 0; str[i][j] != '\0'; j++) { p = trie[p + map.get(str[i][j])]; if (vis[p] == 1) { System.out.println("YES"); break; } } if (vis[p] == 0) { System.out.println("NO"); } } } } ``` 该题解释:给定 $n$ 个模式串和 $m$ 个文本串,问每个模式串是否存在于文本串中。其中,模式串和文本串都只包含小写字母。 AC动机是一种可以高效匹配多个模式串的数据结构。该题需要使用AC动机进行多模式串匹配。 代码实现中,使用一个trie树存储所有模式串,每个节点记录了下一层的字符和对应的子节点编号。同时,使用一个map记录每个字符对应的编号,以便于在trie树中查找。 在trie树构建完成后,使用广度优先搜索构建fail指针。搜索过程中,对于每个节点 $u$,依次查找其父亲节点 $p$ 直到根节点,若 $p$ 的子节点 $v$ 与 $u$ 的子节点 $w$ 匹配,则令 $u$ 的fail指针指向 $p+v$ 节点。如果 $p+v$ 节点不存在,则继续向根节点搜索。 在fail指针构建完成后,对于每个文本串,从根节点开始依次匹配每个字符,直到匹配完成或者无法匹配。如果最终匹配的节点已经被访问,则说明该模式串存在于文本串中。 时间复杂度为 $O(\sum |P|+|T|)$,其中 $\sum |P|$ 表示所有模式串的长度之和,$|T|$ 表示所有文本串的长度之和。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值