Alpha Cow Bessie has a stack of N ≤ 100,000 pancakes, each with a unique flavor F_i (denoted by the numbers from 1 to N). She repeatedly takes the top pancake of the stack and eats it. However, up to K times, she can take the top pancake in the stack and place it somewhere else in the stack. Find the lexicographically least permutation of pancake flavors that Bessie can eat.
Constraints:
- N < 100,000
- 1 ≤ K ≤ N
- 1 ≤ F_i ≤ N
Input format:
- The first line contains two integers: N, K - the number of pancakes and the number of times Bessie can reposition the top pancake.
- The second line is a list of space-separated integers: F_1, F_2, … F_N, the flavor of the pancakes which are stacked upon each other. The pancake with flavor F_1 is on top, and the pancake with flavor F_N is on the bottom; in general, the pancake with flavor F_m is the mth pancake from the top. Note that the list is some permutation of the numbers from 1 to N.
Output format:
Your output should be a single line of space-separated integers which is the lexicographically least permutation of pancake flavors that Bessie can eat.
(Problem credit: Eric Zhang & Isaac Li)
5 1 1 4 2 5 3
1 2 4 5 3
Bessie eats the first pancake (with flavor 1), but then takes the next pancake (with flavor 4) and slots it in between the pancakes with flavors 2 and 5. Then Bessie eats the rest of the pancakes in order, resulting in the optimal permutation 1,2,4,5,3.
Please login to use the editor
You need to be logged in to access the code editor
Loading...
Please wait while we load the editor
No editorial available for this problem.
Please login to use the editor
You need to be logged in to access the code editor
Loading...
Please wait while we load the editor