#P1750. Lexicographically Smallest Stack Permutation
Lexicographically Smallest Stack Permutation
Lexicographically Smallest Stack Permutation
You are given a sequence of n elements \(A = [a_1, a_2, \dots, a_n]\). You must process them using a stack of capacity \(c\) according to the following procedure:
- The elements must be pushed in the given order.
- You may choose when to pop from the stack, but you can only pop the top element.
- At any point, the number of elements in the stack cannot exceed \(c\).
Each pop operation outputs an element. Thus, a full processing produces an output sequence of n numbers (all input numbers will eventually be popped). There can be many valid output sequences. Your task is to find the one that is lexicographically smallest. That is, if there are two sequences \(X = [x_1, x_2, \dots, x_n]\) and \(Y = [y_1, y_2, \dots, y_n]\) that can be achieved by some valid sequence of push/pop operations, then \(X\) is considered smaller than \(Y\) if for the smallest index \(i\) such that \(x_i \neq y_i\), we have \(x_i < y_i\).
Note: All formulas are in \(\LaTeX\) format.
inputFormat
The first line contains two integers \(n\) and \(c\) where \(1 \le n \le 10^5\) (in our test cases, \(n\) is small) and \(1 \le c \le n\). The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) representing the sequence.
outputFormat
Output the lexicographically smallest sequence that can be generated by a valid push/pop process using the stack. The numbers should be separated by a single space.
sample
3 2
3 1 2
1 2 3