Editorial for CEOI '16 P2 - Kangaroo
Submitting an official solution before solving the problem yourself is a bannable offence.
A sequence of jumps from
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
In other words, the number of alternating permutations of length
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
Note the following invariant that is preserved by the recurrence:
This is a key observation that shows the first and the third index of
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