#K60382. Lexicographically Smallest Array by Reversing a Subarray

    ID: 31074 Type: Default 1000ms 256MiB

Lexicographically Smallest Array by Reversing a Subarray

Lexicographically Smallest Array by Reversing a Subarray

You are given an array (A = [a_1, a_2, \dots, a_N]) of (N) integers and a positive integer (K). You are allowed to perform exactly one reverse operation on any consecutive (K) elements. Specifically, if you choose position (i) (with (1 \le i \le N-K+1)), then the segment (a_i, a_{i+1}, \dots, a_{i+K-1}) is reversed. Your task is to choose the best subarray to reverse so that the resulting array is lexicographically smallest.

An array (X) is lexicographically smaller than an array (Y) if there exists an index (j) such that (X_1 = Y_1, X_2 = Y_2, \dots, X_{j-1} = Y_{j-1}) and (X_j < Y_j). Note that you must perform exactly one reverse operation, even if the original array is already the smallest.

For example, if (N = 5, K = 3) and (A = [4, 3, 2, 1, 5]), reversing the subarray starting at index 1 (considering 1-indexed positions) would yield ([2, 3, 4, 1, 5]) which is lexicographically smaller than any other possibility.

inputFormat

The input is read from standard input (stdin) and consists of two lines:

  • The first line contains two integers (N) and (K) separated by a space.
  • The second line contains (N) integers representing the array (A), separated by spaces.

outputFormat

Print the lexicographically smallest array after performing exactly one reverse operation on any consecutive (K) elements. The output should be a single line of (N) integers separated by spaces, written to standard output (stdout).## sample

5 3
4 3 2 1 5
2 3 4 1 5