Official

C - LIS to Original Sequence Editorial by evima


We will prove that there is always a solution for any input satisfying the condition in Problem Statement by induction on \(N\), and simultaneously give the lexicographically smallest construction of \(P\).

Let us decide the values in the sequence from left to right.

First, if \(K=1\), the only solution is \(P=(N,N-1,N-2,\cdots,1)\).

Consider the case \(K \geq 2\). When \(A_1=1\), we may choose \(P_1=1\). For the remaining values \((P_2,P_3,\cdots,P_N)\), we will choose them recursively. That is, we find the solution for the input \((A_2-1, A_3-1, \cdots, A_K-1)\) (which is possible from the induction hypothesis) and use it after adding \(1\) to each value.

When \(A_1>1\), it turns out that \(P_1=A_1\) will be chosen. If \(P_1 < A_1\), \(P_1<A_1<A_2<\cdots<A_K\) would be a subsequence of \(P\), which violates the requirement that \(A\) is a LIS. On the other hand, a solution with \(P_1 = A_1\) always exists, as shown below, so \(P_1=A_1\) must hold in order for \(P\) to be the lexicographically smallest.

Next, it also turns out that \(P_2 = 1\), because there exists a solution with \(P_2 = 1\), which will be the lexicographically smallest choice. Now, we will prove that there is a solution with \(P_1 = A_1\) and \(P_2 = 1\).

We can show from the induction hypothesis that there is a permutation \((P_3,P_4,\cdots,P_N)\) of \((2,3,\cdots,A_1-1,A_1+1,\cdots,N)\) whose LIS is \((A_2,A_3,\cdots,A_K)\). The length of the LIS of such \(P\) is indeed \(K\), because \(P_1 >P_2\) and the increasing subsequence using \(P_2\) has the length of \(1+(K-1)=K\). Naturally, \(P\) contains \(A\) as a subsequence, satisfying the requirement. Additionally, by choosing the lexicographically smallest values for \((P_3,P_4,\cdots,P_N)\), the entire sequence \(P\) will also be the lexicographically smallest.

Therefore, we can solve the problem recursively following the procedure shown above. In the actual implementation, it would be simpler to maintain a list of unused values rather than calling a recursive function. The total time complexity will be \(O(N)\).

posted:
last update: