跳到正文

题解

AC自动机de指针版本题解

Simon439747约 12 分钟
原文
文章信息与版本

文章信息

发布
2026年8月18日
收录
2026年8月18日
更新
2026年11月11日
篇幅
约 12 分钟
题目
P3808

版本

  1. v1当前

我学的是扶苏版本的指针字典树,详见 这里。

然后我将会简单介绍下他的原理,但是我就觉得 这个 讲的很好,推荐,初版代码也是照他写的。

但是会有 50pts50pts 的 TLE 以及 MLE,所以稍作优化。

好的,开始讲解。

首先,AC 自动机和 KMP 有异曲同工之妙。都是用了跳转的方式优化。

我们在学习之前就应该会了 Trie 树。正如同我前言中的描述,我是学习的扶苏的字典树。

而用指针写 AC 自动机是件较难的事情。因为正如我所说,只得了 50pts。所以这篇题解诞生了。

我们来看,首先,我们匹配一个模式串,幸运的配上了,但是我们就要重新从根开始。但是这样太慢了。于是我们不免想到了 KMP 中的 π\pi 集合,这样就很简便了。

于是我们想到:能否使用一个类似 π\pi 的东东去跳转呢?

他来了,他来了,failfail 指针诞生了。

fail 指针

正如其名,在 trie 上失配后才会动用 failfail 指针。

在其他题解中,使用的是数组里的成员表示。但是,我们这里用的是指针。所以采用指针的形式定义一个 trie* fail 即可。

明显,所有第一个字符在失配后只能跑到根。

然后对于其他的节点,我们想要去匹配其他的,可以去到隔壁链上的同样节点,继续匹配。如果没有,打道回府即可。

但是,我们如果想要让他们的操作一样,我们需要一个虚拟节点表示 root 的 fail 指针。在其他题解中,使用的是 00 号节点。但是这里没有,所以使用 dieHeaddieHead 解决。

于是我们可以有:

C++
trie* dieHead=new trie();
void getFail(trie* root){
    for(int i=0;i<26;i++){
        dieHead->nxt[char(i+'a')]=root;
    }
    queue<trie*>q;
    q.push(root);
    root->fail=dieHead;
    while(!q.empty()){
        trie* u=q.front();
        q.pop();
        for(int i=0;i<26;i++){
            if(!u->nxt.count(char('a'+i))){
                u->nxt[char('a'+i)]=u->fail->nxt[char('a'+i)];
                continue;
            }
            u->nxt[char('a'+i)]->fail=u->fail->nxt[char('a'+i)];
            q.push(u->nxt[char('a'+i)]);
        }
    }
}

我们继续。

查询

首先,我们用一个 jj 做部分性的跳转,uu 做全局性跳转。

如果重复了,我们肯定是不会要的。

所以我们会支持一个否定机制:将 flagflag 设为 −1-1。

如果没触发,就累加然后打开机制,反之直接结束,因为后面的他所跳转的也是不会累加的。所以就有整体代码:

TLE 代码
C++
#include <bits/stdc++.h>
using namespace std;
struct trie{
    unordered_map<char,trie*>nxt;
    int flag;
    trie* fail;
    trie():flag(0),fail(nullptr){}
    void insert(const string& s){
        if(s.length()==1){
            flag++;
            return ;
        }
        if(!nxt.count(s[0]))nxt[s[0]]=new trie();
        nxt[s[0]]->insert(s.substr(1));
    }
};
trie* dieHead=new trie();
void getFail(trie* root){
    for(int i=0;i<26;i++){
        dieHead->nxt[char(i+'a')]=root;
    }
    queue<trie*>q;
    q.push(root);
    root->fail=dieHead;
    while(!q.empty()){
        trie* u=q.front();
        q.pop();
        for(int i=0;i<26;i++){
            if(!u->nxt.count(char('a'+i))){
                u->nxt[char('a'+i)]=u->fail->nxt[char('a'+i)];
                continue;
            }
            u->nxt[char('a'+i)]->fail=u->fail->nxt[char('a'+i)];
            q.push(u->nxt[char('a'+i)]);
        }
    }
}
int query(const string &s,trie* root){
    int ans=0;
    trie* u=root;
    for(char c:s){
        trie* j=u->nxt[c];
        while(j!=root&&j!=dieHead&&j->flag!=-1){
            ans+=j->flag;
            j->flag=-1;
            j=j->fail;
        }
        u=u->nxt[c];
    }
    return ans;
}
int main(){
    trie* root=new trie();
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        string s;
        cin>>s;
        root->insert(s);
    }
    getFail(root);
    string s;
    cin>>s;
    cout<<query(s,root)<<endl;
    return 0;
}

好的,我们拿到 50pts 了,距离成功只差一个优化。

优化

trie

这里有一个可以优化的点。

C++
struct trie{
    unordered_map<char,trie*>nxt;
    int flag;
    trie* fail;
    trie():flag(0),fail(nullptr){}
    void insert(const string& s){
        if(s.length()==1){
            flag++;
            return ;
        }
        if(!nxt.count(s[0]))nxt[s[0]]=new trie();
        nxt[s[0]]->insert(s.substr(1));
    }
};

因为出现了递归,以及大量的拷贝,所以会有一个点 MLE。解决办法就是改成利用 pospos 代替 substrsubstr。

fail

这里也需要优化。

我们发现,没有节点的点几乎没用,只是在失配时搞到另一棵树上。于是我们只遍历有的节点。关于跳转下一节会讲。然后我们开始压缩路径,然后压缩完就照旧去做。

query

正如我们之前的那一节所说,我们之前是为了跳转,所以我们直接自动挡改手动挡。

我们计算 cc 匹配结束后的节点 uu,就可以达到目的。

核心的三行:

C++
while(u!=dieHead&&!u->nxt.count(c))u=u->fail;
if(u->nxt.count(c))u=u->nxt[c];
else u=root;

三处优化集结,直接献上 AC Code:

AC Code
C++
//警示后人:十年OI一场空,不开long long见祖宗
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define AC 0
using ll=long long;
using pll=pair<int,int>;
template<typename T>
inline void readinVector(vector<T>& vec,int l,int r){
	for(int i=l;i<=r;i++)cin>>vec[i];
}
template<typename T>
class matvec{
public:
	vector<vector<T> >mat;
	matvec(){}
	matvec(int n){
		mat.resize(n+1);
	}
	void rs(int n){
		mat.resize(n+1);
	}
	matvec(int n,int m){
		mat.resize(n+1,vector<T>(m+1));
	}
	matvec(int n,int m,T v){
		mat.resize(n+1,vector<T>(m+1,v));
	}
	vector<T>& operator[](int i){
		return mat[i];
	}
	void p_b(const vector<T>&vec){
		 mat.push_back(vec);
	}
};
struct trie{
	unordered_map<char,trie*>nxt;
	int flag;
	trie* fail;
	trie():flag(0),fail(nullptr){}
	void add(const string& s,int pos=0){
		if(pos==s.length()){
			flag++;
			return ;
		}
		if(!nxt.count(s[pos]))nxt[s[pos]]=new trie();
		nxt[s[pos]]->add(s,pos+1);
	}
};
trie* dieHead=new trie();
void getFail(trie* root){
	queue<trie*>q;
	root->fail=dieHead;
	for(auto [c,v]:root->nxt){
		v->fail=root;
		q.push(v);
	}
	while(!q.empty()){
		trie* u=q.front();
		q.pop();
		for(auto [c,v]:u->nxt){
			trie* f=u->fail;
			while(f!=dieHead&&!f->nxt.count(c))f=f->fail;
			if(f->nxt.count(c)){
				v->fail=f->nxt[c];
			}else v->fail=root;
			q.push(v);
		}
	}
}
int query(const string& s,trie* root){
	int ans=0;
	trie* u=root;
	for(char c:s){
		while(u!=dieHead&&!u->nxt.count(c))u=u->fail;
		if(u->nxt.count(c))u=u->nxt[c];
		else u=root;
		trie* j=u;
		while(j!=dieHead&&j->flag!=-1){
			ans+=j->flag;
			j->flag=-1;
			j=j->fail; 
		}
	}
    return ans;
}
int T=1;
void solve(){
	trie* root=new trie();
	int n;
	cin>>n;
	for(int i=1;i<=n;i++){
		string s;
		cin>>s;
		root->add(s);
	}
	getFail(root);
	string s;
	cin>>s;
	cout<<query(s,root)<<endl;
}
signed main(){
//	freopen("xxx.in","r",stdin);
//	freopen("xxx.out","w",stdout);
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
//  cin>>T;
	while(T--)solve();
	return AC;
	//AK IOI!;
}
复杂度分析

ss 是模式串,TT 是待匹配的字符串。

建树:是 trie 的复杂度 O(∑∣si∣)O(\sum|s_i|)。

构建指针:均摊 O(∑∣si∣)O(\sum|s_i|)。

因为我们跳完一次后就不会在经过了,所以我们合计一下每条树边都会经过一次,所以是 O(∑∣si∣)O(\sum|s_i|) 的。

查询:均摊 O(∣T∣+∑∣si∣)O(|T|+\sum|s_i|)。

首先我们先考虑跳链的那部分,类似于构建指针那部分,合起来应该是 O(∑∣si∣)O(\sum|s_i|) 的。

然后是手动跳转,因为我们是逐渐下降的,所以这部分是 max⁡si\max s_i 的,然后再加上外边的循环,所以应该是 O(T)O(T) 的。合起来,这部分的是 O(∑si+T)O(\sum s_i+T) 的。

优化是可以用到其他地方的,比如数组版本。