Official

B - Adjacent Chmax Editorial by evima


Let us characterize the sequences that \(P\) can become.

For each \(i\), the positions occupied by \(P_i\) in input will form an interval. Let \([l_i,r_i)\) denote this interval.

When the interval is empty, \(l_i\) and \(r_i\) are not unique, but let us make them unique by imposing an additional restriction \(r_i=l_{i+1}\).

For each \(i\), let us define \(L_i\) and \(R_i\) as follows.

  • If there is \(j\) such that \(j<i,P_j>P_i\), let \(L_i\) be the maximum such \(j\). Otherwise, let \(L_i=0\).
  • If there is \(j\) such that \(j>i,P_j>P_i\), let \(R_i\) be the minimum such \(j\). Otherwise, let \(R_i=N+1\).

The conditions that \(l_i\) and \(r_i\) must satisfy can be summarized as follows.

  • \(1=l_1 \leq r_1 = l_2 \leq r_2 = \cdots =l_N \leq r_N=N+1\).
  • \(L_i < l_i < r_i \leq R_i\) or \(l_i=r_i\).

On the other hand, if \(l_i\) and \(r_i\) satisfy these conditions, they are feasible. (“Expand” each value in input until \([l_i,r_i)\) is covered, in ascending order of magnitude.)

One can count \(l_i\) and \(r_i\) that satisfy the above condition by DP: decide \(l_i\) and \(r_i\) in ascending order of \(i\) and let \(dp[i][j]=(\)the number of ways such that \(r_i=j)\).

This DP takes \(O(N^2)\) time.

Sample code (c++)

P.S. There is an \(O(N\log^2N)\) solution.

Sample code (c++)

posted:
last update: