Official

A - Median of Good Sequences Editorial by evima


Consider two cases based on the parity of \(N\).

When \(N\) is even:

The number of good sequences starting with \(1,2,\cdots,N/2\) matches exactly with those starting with \(N/2+1,\cdots,N\). Therefore, the desired sequence is the lexicographically largest one among the good sequences that start with \(N/2\). This can be obtained simply by sorting the remaining elements in descending order.

When \(N\) is odd:

The number of good sequences starting with \(1,2,\cdots,(N-1)/2\) matches exactly with those starting with \((N+3)/2,\cdots,N\). Thus, the first element of the desired sequence will be \((N+1)/2\). The next step is to find the sequence that is exactly at the middle in lexicographical order among the sequences obtained by arranging the remaining elements. Now, let’s consider the second element. If \((N+1)/2\) remains, we can apply the same logic, and thus the second element will also be \((N+1)/2\).

In the end, the first \(K\) elements will be \((N+1)/2\). The remaining part of the sequence can be obtained in the same way as in the even case, so this case is resolved as well.

Implementing the above steps directly yields an \(O(NK)\) time solution.

Sample Code (C++)

posted:
last update: