Official

B - Chmax Editorial by evima


Let’s consider the relationship between \(P\) and \(F(P)\).
We express \(P\) in the form of what is called cycle decomposition. That is, consider a directed graph with the following \(N\) vertices and \(N\) edges:

  • \(N\) vertices \(1, 2, \dots, N\), and
  • \(N\) directed edges (the \(i\)-th edge goes from vertex \(i\) to vertex \(P_i\)).

Such a graph is always composed of several cycles. For example, when \(P = (3, 1, 5, 6, 2, 4)\), the graph generated by \(P\) is composed of a cycle \(1 \to 3 \to 5 \to 2 \to 1\) and another cycle \(4 \to 6 \to 4\).

Let’s consider \(F(P)\) when \(P\) is expressed in this way.
For example, when \(P = (3, 1, 5, 6, 2, 4)\), the first, third, and fifth elements of \(F(P)\) are all \(5\), because they are connected on the cycle as \(1 \to 3 \to 5\), and the edge extending from \(5\) connects to \(2\) \((\lt 5)\).
Generalizing this, using the graph that appears in the cycle decomposition, \(F(P)\) can be expressed as follows:

  • Remove from the graph the edges with (the number of the starting vertex) \(\geq\) (the number of the ending vertex). The graph is now decomposed into several paths.
    Let \(v_1 \to v_2 \to \dots \to v_k\) be one of those paths, and the \(v_i\)-th elements of \(F(P)\) will all be \(v_k\).

This property allows us to solve the problem.

For the \(A\) given as input, let’s say \(n\) is written as \(A_{x_1}, A_{x_2}, \dots, A_{x_k}\). (\(x_1 \lt x_2 \lt \dots \lt x_k\))
Using the property mentioned above, the following facts hold in the graph generated by \(P\):

  • There is a path \(x_1 \to x_2 \to \dots \to x_k\).
  • The number of the starting vertex of the edge going to vertex \(x_1\) is greater than or equal to \(x_1\).
  • The number of the ending vertex of the edge coming out of vertex \(x_k\) is less than or equal to \(x_k\).

Also, it is necessary that \(x_k = n\). If \(x_k \neq n\), no \(P\) satisfies the condition, and the answer is \(0\).

Assume that the condition \(x_k = n\) holds for all \(n\) contained in \(A\). Then, several paths have been determined in the graph generated by \(P\). Now, let’s say \(m\) paths are determined, with the starting vertex of the \(i\)-th path being \(s_i\), and the ending vertex being \(t_i\).
Since one graph in the form of cycle decomposition corresponds to one \(P\), the answer is the number of ways to connect the paths with edges to form cycles. In other words, it is the number of ways to match \((t_1, t_2, \dots, t_m)\) and \((s_1, s_2, \dots, s_m)\) under these constraints:

  • The number of the ending vertex of the edge coming out of vertex \(t_i\) is less than or equal to \(t_i\).
  • The number of the starting vertex of the edge going to vertex \(s_i\) is greater than or equal to \(s_i\).

This can be counted by looking at the vertex numbers in ascending order.

Thus, the problem is solved. The computational complexity is \(\mathrm{O}(N)\), which is sufficiently small.

posted:
last update: