Editorial for CEOI '16 P2 - Kangaroo
Submitting an official solution before solving the problem yourself is a bannable offence.
A sequence of jumps from to can be mirrored and thus obtaining a valid sequence of jumps from to . Due to this symmetry, and can be swapped such that .
We will add the following definitions:
- the number of alternating permutations that start ascending, having the first and the last elements and
- the number of alternating permutations that start descending, having the first and the last elements and
- , (our target)
- , (for formal reasons)
Let's consider an alternating permutation of length that starts with and ends with . By removing the left extremity () and decreasing all values greater than by , we'll obtain an alternating permutation of order . We can infer the following recurrences:
In other words, the number of alternating permutations of length starting ascending with and ending with is equal to the number of alternating permutations of length starting descending with and ending with . Similarly for .
The above recurrences can be rewritten more conveniently:
and from here we obtain:
After a few manipulations, we can further derive:
Let's stop for a moment to assess the complexity. The answer can be easily computed in using the above recurrence, but it can be reduced to as follows.
Note the following invariant that is preserved by the recurrence:
This is a key observation that shows the first and the third index of will not be independent of each other by repeatedly using the recurrence starting backwards from . Therefore, instead of three independent variables, , we'll have only two (since ), so the complexity will be for a proper implementation.
We have one more thing to do, namely handling the corner cases :
Case n mod 2 = 1
X[n][1][j] = A[n][1][j] = A[n][j][1]
A[n][j][1] = D[n-1][j][1] + D[n-1][j+1][1] + … + D[n-1][n-1][1]
A[n][j][1] = A[n-1][1][j] + A[n-1][1][j+1] + … + A[n-1][1][n-1]
A[n][1][j] = A[n][1][j-1] - A[n-1][1][j-1]
Case n mod 2 = 0
X[n][1][j] = A[n][1][j] = D[n][j][1]
D[n][j][1] = A[n-1][j-1][1] + A[n-1][j-2][1] + … + A[n-1][3][1]
D[n][j][1] = A[n-1][1][j-1] + A[n-1][1][j-2] + … + A[n-1][1][3]
A[n][1][j] = A[n][1][j-1] + A[n-1][1][j-1]
resulting in
X[n][1][j] = X[n][1][j-1] - X[n-1][1][j-1], n mod 2 = 1
X[n][1][j] = X[n][1][j-1] + X[n-1][1][j-1], n mod 2 = 0
We have also:
A[n][2][j] = A[n][1][j] - D[n-1][1][j-1] = A[n][1][j] = X[n][1][j]
D[n][2][j] = D[n][1][j] + A[n-1][1][j-1] = A[n-1][1][j-1] = X[n-1][1][j-1]
(there is no descending permutation starting with 1)
X[n][2][j] = X[n][1][j] + X[n-1][1][j-1]
Comments