声明
我们把 的 部分截取出来的结果记为 。
默认你已经学过 Trie。
写文章的背景
打 abc437 E 的时候,直接想到之前写的 trie 上 dfs 做P3809 【模板】后缀排序,但由于我有心理阴影,不敢写 trie。
显然,后缀排序的代码是假的。空间复杂度是 。 但是这次 abc E 是对的,因为是前缀,不是后缀。
官方 E 题题解
E - Sort Arrays 题解 by en_translator
You are asked to sort in lexicographical order. This can be solved with a data structure called Trie.
Construct a Trie with the keys being . Here, the same sequence should be corresponded to a single node. If a parent node has a child node with value , reuse that node; otherwise, construct a new node and add an edge . 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.
您被要求将 按词典顺序排序。这可以用一种名为 Trie 的数据结构来解决。
构建一个 Trie,键为 。在此,同一序列应对应一个节点。如果父节点 有一个值为 的子节点,则重复使用该节点;否则,构建一个新节点 并添加一条边 。子节点以关联数组的形式管理(类似于 C++ 中的 map 或 Python 中的 dict)。每个节点还存储相应序列的索引。
在此 Trie 上执行 DFS(深度优先搜索)即可找到答案。如果一个节点有多条边,则按其值的升序访问它们。在 DFS 过程中,每访问一个节点,就将该节点对应的序列索引按升序添加到答案数组中。
Lazy-tag Trie
这里有一只可爱的 trie。
但是她的链很多,好像不那么可爱了……
于是,我们想:如果一个节点的父亲只有它一个儿子,那么我们直接插在这里不管了,记录一下 ,存储当前深度和当前插入的字符串,如果后面还有字符串插入到这里,就先把标记中的字符串下放。 下放时应该插入的就是 了。
看着可爱多了。
可是啊,这样还是会被卡掉啊!
左边的两条链没办法压缩了。
依旧是 lazy-tag 的处理方式。
这次我们不能直接下放标记了。
对于一个节点上的标记 ,和即将插入的 ,我们只需要展开她们的 LCP 之后的部分即可,其它部分保留。
比如插入 。当前层有一个标记是 。
比较 和 得到
她们的 LCP 是 。
这样,我们就需要存储 了,代表标记是 。
求 LCP 的方法有很多种,hash 和倍增是两种较好的方式。



