Official

F - Visibility Sequence Editorial by evima


Consider the graph with edges \(i - P_i\), which is a forest. For simplicity, let us add a positive infinity at the beginning of the sequence, and we can assume the graph is a tree.

Here, the vertices \(1,2,\cdots, N\) are arranged in the pre-order. That is, if we consider the tree rooted by regarding \(0\) as the root, each subtree corresponds to the segment \([l, r]\) for some \(l\) and \(r\), and the root of the subtree is \(l\).

Before counting \(P\), let us consider, for a fixed tree, whether there is a sequence \(H\) that produces a graph that is identical to the tree. We can determine it by greedily assigning the vertices the smallest values possible so that the graph matches the tree.

More specifically, if a vertex \(v\) has children \(u_1 < u_2 \cdots < u_k\), because of how edges are spanned, \(H_v > \max(H_{u_1}, H_{u_2}, \cdots H_{u_k})\) and \( H_{u_1} \leq H_{u_2} \leq \cdots \leq H_{u_k}\) must hold, and it is sufficient for this to hold for every vertex. Thus, if we greedily assign values in DFS where the children are visited in the order from left to right, writing max(brothers to the left, max of children + 1) to each vertex, we can find the minimum possible value written in each vertex. (We can achieve those minimum values simultaneously.)

We will consider a DP using the state after this greedy algorithm as the key. Let us define the following:

\(dp_Tree(l,r,x):= \) considering only the segment \([l,r]\), the number of trees where \(x\) is written on the root after the above greedy algorithm

\(dp_Forest(l,r,x):= \) considering only the segment \([l,r]\), the number of states where there are one or more trees and \(x\) is written on the root of the rightmost tree after the algorithm

Then, the following holds:

\(dp_Tree\) is \(dp_Forest(l+1,r,x-1)\).

\(dp_Forest\) can be computed from \(dp_Tree + \sum_{m=l}^{r-1} dp_Forest(l,m,a) * dp_Tree(m+1, r, b)\) (\(\max(a,b)=x)\), which can be done faster using prefix sums. (To describe it intuitively, after separately considering the tree that we assign to the right, we just match the root if it is smaller than the value to the left.)

The total time complexity will be \(O(N^4)\).

posted:
last update: