The Best Lineup

시간 제한2초메모리 제한2048 MB

요약
수열에서 원소 하나를 앞쪽 임의 위치로 옮길 수 있고, 이후 앞에서 하나씩 꺼내며 뒤에 붙일지 선택해 만들 수 있는 사전순 최대 수열을 구한다.
난이도

어려움10점 중 8점

유형
그리디, 스택, 배열, 시뮬레이션
정답자
아직 제출이 없습니다

문제

Farmer John has NN (1≤N≤2⋅105)(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 a_ia\_i (1≤a_i≤N1 \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 (1≤T≤1001 \leq T \leq 100) independent test cases.

입력

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 a_1,a_2,…,a_Na\_1, a\_2, \ldots, a\_N.

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

출력

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

힌트

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 s_i≠t_is\_i \neq t\_i, s_i>t_is\_i > t\_i.
  • If no such ii exists, ss is longer than tt.

예제1

  1. 예제 1

    입력
    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