Official

E - LEQ and NEQ Editorial by evima


Let us use the inclusion-exclusion principle.

Let \(dp[pos][k]\) be the number of choices of \(X[1],X[2],\ldots,X[pos]\) where the parity of the number of \(i\) for which we purposely make \(X_i = X_{i+1}\) is \(k\). The answer is \(dp[N][0]-dp[N][1]\).

We have the following transitions: \(dp[pos'][k+(pos'-pos-1)]+=\min(A[pos+1],..,A[pos']) \times dp[pos][k]\), but directly implementing it results in a complexity of \(O(N^2)\) and runs out of time.

By focusing on the structure of the Cartesian Tree, we can jointly deal with the transitions with the same \(\min(A[pos+1], .., A[pos'])\). The sketch of this follows:

  • In ascending order of \(i\), we deal with the transitions where \(\min(A[pos+1], .., A[pos'])\) is \(A[i]\). If \(A\) contains repetitions, we assign them some order.
  • Before we do the transition for \(i\), all values in \(dp\) where \(pos < i\) are determined. We maintain prefix sums for each parity of \(pos + k\).
  • Then, from \(i\) to the destinations \((pos \geq i)\), we do an addition to an interval for each parity of \(pos + k\), using another array of prefix sums.

If we find the Cartesian Tree using a stack, the complexity of the solution is \(O(N)\).

posted:
last update: