#C10173. Lexicographically Smallest Array Sequence

    ID: 39349 Type: Default 1000ms 256MiB

Lexicographically Smallest Array Sequence

Lexicographically Smallest Array Sequence

Given an array of integers, you are allowed to perform exactly one operation: either swap two adjacent elements or reverse any contiguous subarray. Your task is to choose the operation that yields the lexicographically smallest sequence possible. If no operation can produce a sequence that is lexicographically smaller than the original, return the original sequence.

Formally, for a sequence \(A = [a_1, a_2, \dots, a_n]\), a sequence \(B\) is defined to be lexicographically smaller than \(A\) if there exists an index \(k\) such that for all \(i b_k\). The operations allowed are:

  • Swap: Choose an index \(i\) (\(1 \le i < n\)) and swap elements \(a_i\) and \(a_{i+1}\).
  • Reverse: Choose two indices \(i\) and \(j\) with \(i < j\) and reverse the subarray from \(a_i\) to \(a_j\) (both inclusive).

Return the lexicographically smallest sequence after performing exactly one operation.

inputFormat

The input begins with a single integer \(T\) representing the number of test cases. Each test case consists of two lines:

  • The first line contains an integer \(n\), the number of integers in the sequence.
  • The second line contains \(n\) space-separated integers.

outputFormat

For each test case, output a single line containing the lexicographically smallest sequence after performing the allowed operation. Numbers should be separated by a single space.

## sample
2
5
3 2 1 5 4
3
4 3 2
1 2 3 5 4

2 3 4

</p>