跳到正文

个人记录

Trie 的优化 Trick

_CuteRalsei_约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月21日
更新
2025年12月29日
篇幅
约 5 分钟

版本

  1. v1当前

声明

我们把 ss 的 [l,r][l,r] 部分截取出来的结果记为 s[l,r]s_{[l,r]}。


默认你已经学过 Trie。

写文章的背景

打 abc437 E 的时候,直接想到之前写的 trie 上 dfs 做P3809 【模板】后缀排序,但由于我有心理阴影,不敢写 trie。

显然,后缀排序的代码是假的。空间复杂度是 O(n2)\bm{O(n^2)}。 但是这次 abc E 是对的,因为是前缀,不是后缀。

官方 E 题题解

E - Sort Arrays 题解 by en_translator


You are asked to sort A1,A2,…,ANA_1, A_2, \ldots,A_N in lexicographical order. This can be solved with a data structure called Trie.

Construct a Trie with the keys being A1,…,ANA_1, \ldots, A_N. Here, the same sequence should be corresponded to a single node. If a parent node vv has a child node with value xix_i, reuse that node; otherwise, construct a new node uu and add an edge v⟶xiuv\stackrel{x_i}{\longrightarrow} u. The children is managed in an associative array (like map in C++ or dict in Python). Each node also stores the indices of the corresponding sequences.

The answer can be found by performing a DFS (Depth-First Search) on this Trie. If a node has multiple edges, visit them in ascending order of their values. During the DFS, every time you visit a node, add the indices of the sequences corresponding to the node to the answer array in ascending order.


您被要求将 A1,A2,…,ANA_1, A_2, \ldots,A_N 按词典顺序排序。这可以用一种名为 Trie 的数据结构来解决。

构建一个 Trie,键为 A1,…,ANA_1, \ldots, A_N 。在此,同一序列应对应一个节点。如果父节点 vv 有一个值为 xix_i 的子节点,则重复使用该节点;否则,构建一个新节点 uu 并添加一条边 v⟶xiuv\stackrel{x_i}{\longrightarrow} u 。子节点以关联数组的形式管理(类似于 C++ 中的 map 或 Python 中的 dict)。每个节点还存储相应序列的索引。

在此 Trie 上执行 DFS(深度优先搜索)即可找到答案。如果一个节点有多条边,则按其值的升序访问它们。在 DFS 过程中,每访问一个节点,就将该节点对应的序列索引按升序添加到答案数组中。

Lazy-tag Trie

这里有一只可爱的 trie。

cute_trie

但是她的链很多,好像不那么可爱了……

于是,我们想:如果一个节点的父亲只有它一个儿子,那么我们直接插在这里不管了,记录一下 dep,id\bm{dep,id},存储当前深度和当前插入的字符串,如果后面还有字符串插入到这里,就先把标记中的字符串下放。 下放时应该插入的就是 sid[dep+1,end]s_{id[dep+1,end]} 了。

看着可爱多了。

可是啊,这样还是会被卡掉啊!

左边的两条链没办法压缩了。

依旧是 lazy-tag 的处理方式。

这次我们不能直接下放标记了。

对于一个节点上的标记 sid[dep+1,end]s_{id[dep+1,end]},和即将插入的 s[dep+1,end′]′s'_{[dep+1,end']},我们只需要展开她们的 LCP 之后的部分即可,其它部分保留。

比如插入 bizv\text{bizv}。当前层有一个标记是 izy\text{izy}。

比较 izy\text{\fcolorbox{white}{yellow}{iz}y} 和 izv\text{\fcolorbox{white}{yellow}{iz}v} 得到

她们的 LCP 是 iz\text{\fcolorbox{white}{yellow}{iz}}。

这样,我们就需要存储 depl,depr,iddepl,depr,id 了,代表标记是 sid[depl,depr]s_{id[depl,depr]}。

求 LCP 的方法有很多种,hash 和倍增是两种较好的方式。

原文