#P11839. [USACO25FEB] The Best Lineup S

[USACO25FEB] The Best Lineup S

Description

Farmer John has NN (1N2105)(1 \leq N \leq 2 \cdot 10^5) cows in a line aa. The ii'th cow from the front of line aa is labeled an integer aia_i (1aiN1 \leq a_i \leq N). Multiple cows may be labeled the same integer.

FJ will construct another line bb in the following manner:

  • Initially, bb is empty.
  • While aa is nonempty, remove the cow at the front of aa and potentially add that cow to the back of bb.

FJ wants to construct line bb such that the sequence of labels in bb from front to back is lexicographically greatest (see the footnote).

Before FJ constructs line bb, he can perform the following operation at most once:

  • Choose a cow in line aa and move it anywhere before its current position.

Given that FJ optimally performs the aforementioned operation at most once, output the lexicographically greatest label sequence of bb he can achieve.

Each input will consist of TT (1T1001 \leq T \leq 100) independent test cases.

Input Format

The first line contains TT.

The first line of each test case contains NN.

The second line of each test case contains NN space-separated integers a1,a2,,aNa_1, a_2, \ldots, a_N.

It is guaranteed that the sum of NN over all test cases does not exceed 10610^6.

Output Format

For each test case, output the lexicographically greatest bb on a new line.

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

Hint

In the first test case, FJ can move the fifth cow to directly after the second cow. Now, a=[4,3,3,2,1]a = [4, 3, 3, 2, 1]. It can be shown [4,3,3,2,1][4, 3, 3, 2, 1] is also the lexicographically greatest bb.

In the second test case, FJ can move the fourth cow to the front of the line.

In the third test case, FJ does not need to perform any operations. He can construct bb by adding each cow beside the second cow to the back of bb. It can be shown this results in the lexicographically greatest bb.

SCORING:

  • Inputs 2-4: N100N \leq 100
  • Inputs 5-8: N750N \leq 750
  • Inputs 9-18: No additional constraints

FOOTNOTE:

Recall that a sequence ss is lexicographically greater than a sequence tt if and only if one of the following holds:

  • At the first position ii where sitis_i \neq t_i, si>tis_i > t_i.
  • If no such ii exists, ss is longer than tt.