##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
5
4 1 2 1 3 2 4
5 1 2 1 3 2 4 2 5
6 1 2 1 3 1 4 2 5 2 6
6 1 2 1 3 2 4 2 5 3 6
7 1 2 1 3 2 4 4 5 3 6 3 7
4
8
11
11
12
You are given a tree with vertices. The tree is rooted at vertex .
A DFS order of the tree is the order in which vertices are first visited by a depth-first search starting from vertex . The children of each vertex may be visited in any order.
For an ordered pair with , call the pair good if there exists a DFS order of the tree such that vertex is the -th vertex in the order, and vertex appears before vertex in that order.
Count the number of good pairs.
The DFS orders are and . Vertex is never the third vertex, so no pair of the form is good. Vertex can be second after vertex . Vertex can be fourth after all smaller vertices. Therefore the good pairs are , , , and .
The DFS orders are , , , and . Vertex is never the third vertex. Vertex can be fourth in , where vertices , , and are before it. Vertex can be fifth in , where all smaller vertices are before it. Together with , this gives good pairs.
Vertex is never the fourth vertex. Vertex can be third, for example in , but then among smaller vertices only vertex is before it. Vertex can be fifth after all smaller vertices, for example in . Vertex can be sixth after all smaller vertices, for example in . Therefore the answer is .
The DFS orders are , , , and . Vertex is never the third vertex. Vertex can be fourth only in orders starting with , so only vertices and may be smaller vertices before it. Vertex can be fifth with vertices , , and before it. Vertex can be sixth after all smaller vertices, for example in . Together with , this gives good pairs.
Every DFS order starts by completely visiting either the subtree of vertex or the subtree of vertex . Therefore vertices and are never in their own numbered positions. Vertex can be sixth after all smaller vertices, for example in . Vertex can be seventh after all smaller vertices, for example in . Together with , this gives good pairs.