#abc252g. G - Pre-Order
G - Pre-Order
Score : points
问题陈述
存在一棵具有 个顶点的有根树,顶点依次标记为 Vertex , , , ,且以 Vertex 为根。
我们从根节点出发执行了一次深度优先搜索,并得到了这棵树的前序遍历序列:。在搜索过程中,当当前顶点有多个子节点时,我们选择未访问过的索引最小的顶点。
什么是前序遍历?
我们从根节点开始,按照以下步骤重复操作来列出树的所有顶点:
- 如果当前顶点 还未被记录,则记录它。
- 然后,如果 有未访问过的子顶点,则移动到那个子顶点。
- 否则,如果 是根节点,则结束遍历;如果不是,则返回到 的父节点。
按照此处记录顺序得到的顶点列表即为该树的前序遍历。
找出与给定前序遍历相一致的根树的数量,结果对 取模。
对于两棵具有 个顶点且均以 Vertex 为根的根树,当这两棵树中存在至少一个非根顶点,其父节点在两棵树中不同,则认为这两棵树是不同的。
以上为通义千问 qwen-max 翻译,仅供参考。
Problem Statement
There is a rooted tree with vertices called Vertex , , , , rooted at Vertex .
We performed a depth-first search starting at the root and obtained a preorder traversal of the tree: .
During the search, when the current vertex had multiple children, we chose the unvisited vertex with the smallest index.
What is a preorder traversal?
We start at the root and repeat the following procedure to list the vertices of the tree.- If the current vertex is not recorded yet, record it.
- Then, if has an unvisited vertex, go to that vertex.
- Otherwise, terminate if is the root, and go to the parent of if it is not. The list of vertices in the order they are recorded here is the preorder traversal of the tree.
Find the number of rooted trees consistent with the preorder traversal, modulo .
Two rooted trees (with vertices and rooted at Vertex ) are considered different when there is a non-root vertex whose parent is different in the two trees.
Constraints
- All are distinct.
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
Print the number of rooted trees consistent with the preorder traversal, modulo .
Sample Input 1
4
1 2 4 3
Sample Output 1
3
The rooted trees consistent with the preorder traversal are the three shown below, so the answer is .
Note that the tree below does not count. This is because, among the children of Vertex , we visit Vertex before visiting Vertex , resulting in the preorder traversal .
Sample Input 2
8
1 2 3 5 6 7 8 4
Sample Output 2
202
update @ 2024/3/10 10:46:26