John Doe has found the beautiful permutation formula.Let's take permutation p = p1, p2, ..., pn. Let's define transformation f of this permutation: where k (k > 1) is an integer, the transformation parameter, r is such maximum integer that rk ≤ n. If rk = n, then elements prk + 1, prk + 2 and so on are omitted. In other words, the described transformation of permutation p cyclically shifts to the left each consecutive block of length k and the last block with the length equal to the remainder after dividing n by k. John Doe thinks that permutation f(f( ... f(p = [1, 2, ..., n], 2) ... , n - 1), n) is beautiful. Unfortunately, he cannot quickly find the beautiful permutation he's interested in. That's why he asked you to help him.Your task is to find a beautiful permutation for the given n. For clarifications, see the notes to the third sample.

A single line contains integer n (2 ≤ n ≤ 106).

Print n distinct space-separated integers from 1 to n — a beautiful permutation of size n.

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	var n int
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewReader(bs)
	writer := bytes.NewBuffer(make([]byte, 0, 1000000))
	fmt.Fscanf(reader, "%d", &n)
	seq := make([]int, n)
	for i := 0; i < n; i++ {
		seq[i] = i
	}

	for i := 2; i <= n; i++ {
		num := seq[0]
		for j := i; j < n; j += i {
			seq[j], num = num, seq[j]
		}
		seq = append(seq, num)
		seq = seq[1:]
	}
	for i := 0; i < n; i++ {
		fmt.Fprintf(writer, "%d ", seq[i]+1)
	}
	writer.WriteTo(os.Stdout)
}

package main

import (
	"bufio"
	"os"
	"strconv"
	"strings"
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func main() {
	defer out.Flush()
	defer out.WriteByte('\n')
	line, _ := in.ReadString('\n')
	n, _ := strconv.Atoi(strings.TrimSpace(line))
	a := make([]int, n*2)
	for i := 0; i < n; i++ {
		a[i] = i + 1
	}
	for i := 2; i <= n; i++ {
		j := 0
		for ; j*i <= n; j++ {
		}
		for j--; j >= 0; j-- {
			a[min((j+1)*i, n)+i-2] = a[j*i+i-2]
		}
	}
	for i := 0; i < n; i++ {
		out.WriteString(strconv.Itoa(a[i+n-1]))
		out.WriteByte(' ')
	}
}

package main

import (
	"bufio"
	"os"
	"strconv"
	"strings"
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func main() {
	defer out.Flush()
	defer out.WriteByte('\n')
	line, _ := in.ReadString('\n')
	n, _ := strconv.Atoi(strings.TrimSpace(line))
	a := make([]int, n*2)
	for i := 0; i < n; i++ {
		a[i] = i + 1
	}
	for i := 2; i <= n; i++ {
		j := 0
		for j = (n - 1) / i; j >= 0; j-- {
			a[min((j+1)*i, n)+i-2] = a[j*i+i-2]
		}
	}
	for i := 0; i < n; i++ {
		out.WriteString(strconv.Itoa(a[i+n-1]))
		out.WriteByte(' ')
	}
}

package main

import (
	"bufio"
	"os"
	"strconv"
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func main() {
	defer out.Flush()
	line, _ := in.ReadString('\n')
	n, _ := strconv.Atoi(line[:len(line)-1])
	a := make([]int, n*2)
	for i := 0; i < n; i++ {
		a[i] = i + 1
	}
	for i := 2; i <= n; i++ {
		j := 0
		for ; j*i <= n; j++ {
		}
		for j--; j >= 0; j-- {
			a[min((j+1)*i, n)+i-2] = a[j*i+i-2]
		}
	}
	for i := 0; i < n; i++ {
		out.WriteString(strconv.Itoa(a[i+n-1]))
		out.WriteByte(' ')
	}
}

package main

import (
	"bufio"
	"os"
	"strconv"
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func main() {
	defer out.Flush()
	defer out.WriteByte('\n')
	line, _ := in.ReadString('\n')
	n, _ := strconv.Atoi(line[:len(line)-1])
	a := make([]int, n*2)
	for i := 0; i < n; i++ {
		a[i] = i + 1
	}
	for i := 2; i <= n; i++ {
		j := 0
		for ; j*i <= n; j++ {
		}
		for j--; j >= 0; j-- {
			a[min((j+1)*i, n)+i-2] = a[j*i+i-2]
		}
	}
	for i := 0; i < n; i++ {
		out.WriteString(strconv.Itoa(a[i+n-1]))
		out.WriteByte(' ')
	}
}


There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation on it:  Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l \le r \le n$$$ and $$$a_l = a_r$$$. Then, reverse the subsegment from the $$$l$$$-th to the $$$r$$$-th element, i. e. set $$$[a_l, a_{l + 1}, \ldots, a_{r - 1}, a_r]$$$ to $$$[a_r, a_{r-1}, \ldots, a_{l+1}, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Find a sequence of at most $$$n^2$$$ operations that transforms array $$$a$$$ into $$$b$$$, or report that no such sequence exists.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 500$$$) — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$.

For each test case, output "NO" (without quotes) if it is impossible to turn $$$a$$$ into $$$b$$$ using at most $$$n^2$$$ operations. Otherwise, output "YES" (without quotes). Then output an integer $$$k$$$ ($$$0 \leq k \leq n^2$$$) denoting the number of operations you will perform. Note that you don't have to minimize the number of operations. Afterwards, output $$$k$$$ lines. The $$$i$$$-th line should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$) — the left and right indices for the $$$i$$$-th operation. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). If there are multiple possible sequences of operations, you may output any of them.

NoteIn the first test case, we can perform the following operations: $$$$$$[1,2,4,3,1,2,1,1] \xrightarrow[l=5,\,r=8]{} [1,2,4,3,1,1,2,1] \xrightarrow[l=1,\,r=6]{} [1,1,3,4,2,1,2,1].$$$$$$In the second test case, we can perform the following operations: $$$$$$[1,2,3,1,3,2,3] \xrightarrow[l=1,\,r=4]{} [1,3,2,1,3,2,3] \xrightarrow[l=3,\,r=6]{} [1,3,2,3,1,2,3].$$$$$$It can be proven that it is impossible to turn $$$a$$$ into $$$b$$$ in the third and fourth test cases.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int) []float64  { res := make([]float64,n); for i:=0;i<n;i++ { res[i] = gf() }; return res }
func gss(n int) []string  { res := make([]string,n); for i:=0;i<n;i++ { res[i] = gs() }; return res }
func gi64() int64     { i,e := strconv.ParseInt(gs(),10,64); if e != nil {panic(e)}; return i }
func gis64(n int) []int64  { res := make([]int64,n); for i:=0;i<n;i++ { res[i] = gi64() }; return res }

func ia(m int) []int { return make([]int,m) }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi(n int,m int,v int) [][]int {
	r := make([][]int,n); for i:=0;i<n;i++ { x := make([]int,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int) ([]int,[]int,[]int) { a,b,c := ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int) ([]int,[]int,[]int,[]int) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int) int { if a < 0 { return -a }; return a }
func rev(a []int) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max(a,b int) int { if a > b { return a }; return b }
func min(a,b int) int { if a > b { return b }; return a }
func maxarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int) int { ans := 0; for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod(a,e,mod int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int) int { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int) (int,int,int) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int) (int,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
func makefact(n int,mod int) ([]int,[]int) {
	fact,factinv := make([]int,n+1),make([]int,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}

func ia64(m int) []int64 { return make([]int64,m) }
func iai64(m int,v int64) []int64 { a := make([]int64,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi64(n int,m int,v int64) [][]int64 {
	r := make([][]int64,n); for i:=0;i<n;i++ { x := make([]int64,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill264(m int) ([]int64,[]int64) { a,b := ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i] = gi64(),gi64()}; return a,b }
func fill364(m int) ([]int64,[]int64,[]int64) { a,b,c := ia64(m),ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi64(),gi64(),gi64()}; return a,b,c }
func fill464(m int) ([]int64,[]int64,[]int64,[]int64) { a,b,c,d := ia64(m),ia64(m),ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi64(),gi64(),gi64(),gi64()}; return a,b,c,d }
func abs64(a int64) int64 { if a < 0 { return -a }; return a }
func rev64(a []int64) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max64(a,b int64) int64 { if a > b { return a }; return b }
func min64(a,b int64) int64 { if a > b { return b }; return a }
func maxarr64(a []int64) int64 { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr64(a []int64) int64 { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr64(a []int64) int64 { ans := int64(0); for _,aa := range(a) { ans += aa }; return ans }
func zeroarr64(a []int64) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod64(a,e,mod int64) int64 { res, m := int64(1), a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint64(a,e int64) int64 { res, m := int64(1), a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd64(a,b int64) int64 { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended64(a,b int64) (int64,int64,int64) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended64(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv64(a,m int64) (int64,bool) { g,x,_ := gcdExtended64(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func vecint64string(a []int64) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.FormatInt(a,10) }; return strings.Join(astr," ") }
func makefact64(n int,mod int64) ([]int64,[]int64) {
	fact,factinv := make([]int64,n+1),make([]int64,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * int64(i) % mod }
	factinv[n] = powmod64(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * int64(i+1) % mod }
	return fact,factinv
}
type pair struct {x,y int}
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N := gi(); A := gis(N); B := gis(N)
		ok := (A[0]==B[0])
		ansarr := []pair{}
		dorev := func(l,r int) {
			ansarr = append(ansarr,pair{l+1,r+1})
			for l < r { A[l],A[r] = A[r],A[l]; l++; r-- }
		}
		for i:=1; ok && i < N; i++ {
			if A[i] == B[i] { continue }

			// Pass 1 : look for B[i] --> B[i-1] in the rest of A
			found := false
			for j:=i;j+1<N;j++ {
				if A[j] == B[i] && A[j+1] == B[i-1] {
					dorev(i-1,j+1); found = true; break
				}
			}
			if found { continue }

			// Pass 2 : look for B[i-1] --> B[i] in the rest of A
			jidx := -1
			for j:=i;j+1<N;j++ {
				if A[j] == B[i-1] && A[j+1] == B[i] { jidx = j; break }
			}
			if jidx == -1 { ok = false; break }
			for l:=jidx;l>=i-1;l-- {
				for r:=jidx+1;r<N;r++ {
					if A[l] != A[r] { continue }
					dorev(l,r)
					found = true
					if A[i] == B[i] { break }
					for j:=i;j+1<N;j++ {
						if A[j] == B[i] && A[j+1] == B[i-1] {
							dorev(i-1,j+1); break
						}
					}
					break
				}
				if found { break }
			}
			if !found { ok = false; break }
		}
		if !ok {
			fmt.Fprintln(wrtr,"NO")
		} else {
			fmt.Fprintln(wrtr,"YES")
			fmt.Fprintln(wrtr,len(ansarr))
			for _,p := range ansarr { fmt.Fprintf(wrtr,"%v %v\n",p.x,p.y) }
		}
	}
}


You are given an array $$$a_1, a_2, \dots, a_n$$$. You can perform the following operation any number of times:  Choose a pair of two neighboring equal elements $$$a_i = a_{i + 1}$$$ (if there is at least one such pair).  Replace them by one element with value $$$a_i + 1$$$. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $$$a$$$ you can get?

The first line contains the single integer $$$n$$$ ($$$1 \le n \le 500$$$) — the initial length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — the initial array $$$a$$$.

Print the only integer — the minimum possible length you can get after performing the operation described above any number of times.

package main

import "fmt"

const maxn, maxInt int = 600, 600

var n int
var a, dp, marr [maxn]int

func min(_x int, _y int) int {
	if _x > _y {
		return _y
	}
	return _x
}

func main() {
	fmt.Scanf("%d\n", &n)
	for i := 1; i <= n; i++ {
		fmt.Scanf("%d", &a[i])
		dp[i] = maxInt
	}
	dp[0] = 0
	for i := 1; i <= n; i++ {
		var cnt = 0
		for j := i; j <= n; j++ {
			cnt++
			marr[cnt] = a[j]
			for cnt > 0 && marr[cnt] == marr[cnt-1] {
				cnt--
				marr[cnt]++
			}
			if cnt == 1 {
				dp[j] = min(dp[j], dp[i-1]+1)
			}
		}
	}
	fmt.Printf("%d", dp[n])
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1312E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	var n int
	Fscan(in, &n)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}

	dp := make([][]int, n)
	for i := range dp {
		dp[i] = make([]int, n)
	}
	var f func(l, r int) int
	f = func(l, r int) int {
		if l == r {
			return a[l]
		}
		if dp[l][r] != 0 {
			return dp[l][r]
		}
		dp[l][r] = -1
		for m := l; m < r; m++ {
			if dpl := f(l, m); dpl > 0 && dpl == f(m+1, r) {
				dp[l][r] = dpl + 1
				break
			}
		}
		return dp[l][r]
	}

	dp2 := make([]int, n+1)
	for i := range dp2 {
		dp2[i] = 1e9
	}
	dp2[0] = 0
	for i := range dp2 {
		for j := i + 1; j <= n; j++ {
			if f(i, j-1) > 0 {
				if dp2[i]+1 < dp2[j] {
					dp2[j] = dp2[i] + 1
				}
			}
		}
	}
	Fprint(_w, dp2[n])
}

func main() { CF1312E(os.Stdin, os.Stdout) }


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \le l \le r \le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation.

For each test case print the lexicographically smallest permutation you can obtain.

NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$.

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

var v [505]int

func find(val, n int) (index int) {
	for i := 1; i <= n; i++ {
		if val == v[i] {
			index = i
			break
		}
	}
	return
}

func reverse(l, r int) {
	if l > r {
		l, r = r, l
	}
	for l < r {
		v[l], v[r] = v[r], v[l]
		l++
		r--
	}
}

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	var n, t, g int
	var first bool
	for t = read(); t > 0; t-- {
		n = read()
		first = true
		g = 1
		for i := 1; i <= n; i++ {
			v[i] = read()
			if first && v[g] == g {
				g++
				continue
			}
			first = false
		}
		if g <= n {
			reverse(g, find(g, n))
		}
		for i := 1; i < n; i++ {
			Fprint(out, v[i], " ")
		}
		Fprintln(out, v[n])
	}
}

func main() {
	run(os.Stdin, os.Stdout)
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

var v [505]int

func find(val, n int) (index int) {
	for i := 1; i <= n; i++ {
		if val == v[i] {
			index = i
			break
		}
	}
	return
}

func reverse(l, r int) {
	if l > r {
		l, r = r, l
	}
	for l < r {
		v[l], v[r] = v[r], v[l]
		l++
		r--
	}
}

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	var n, t, g int
	for t = read(); t > 0; t-- {
		n = read()
		for i := 1; i <= n; i++ {
			v[i] = read()
		}
		g = 1
		for g <= n && v[g] == g {
			g++
		}
		if g <= n {
			reverse(g, find(g, n))
		}
		for i := 1; i < n; i++ {
			Fprint(out, v[i], " ")
		}
		Fprintln(out, v[n])
	}
}

func main() {
	run(os.Stdin, os.Stdout)
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var n, t int
	Fscan(r, &t)
	for t > 0{
		t--
		Fscan(r, &n)
		a := make([]int, n)
		for i := range a{
			Fscan(r, &a[i])
		}
		index := -1
		for i := range a{
			if in(i, a){
				index = i
				break
			}
		}
		if index != -1{
				start := index
				end := index
				min := 600
				for i := index+1; i < len(a); i++{
					if a[i] < min{
						min = a[i]
						end = i
					}
				}
				reverse(a, start, end)
			}
		for i := range a{
			if i != len(a) - 1{
				Fprintf(w, "%d ", a[i])
			}else{
				Fprintf(w, "%d\n", a[i])
			}
		}
	}
}

func in(index int, a []int) bool{
	for i := index + 1; i < len(a); i++{
		if a[i] < a[index] {
			return true
		}
	}
	return false
}

func reverse(a []int, start, end int){
	for start < end{
		a[start], a[end] = a[end], a[start]
		start++
		end--
	}
}

func str(a []int, start, end int) string{
	b := make([]byte, 0)
	for i := end; i >= start; i--{
		b = append(b, byte(a[i]))
	}
	for i := end + 1; i < len(a); i++ {
		b = append(b, byte(a[i]))
	}
	return string(b)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var (
	stdin  = bufio.NewReader(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
)

func printf(f string, a ...interface{}) { fmt.Fprintf(stdout, f, a...) }

func reverse(slice []int, l int, r int) {
	for l < r {
		slice[l], slice[r] = slice[r], slice[l]
		l++
		r--
	}
}

func main() {
	defer stdout.Flush()

	t := readInt()

	for t > 0 {
		n := readInt()
		a := readNInt()

		l, r := -1, -1
		for i := 1; i <= n; i++ {
			if a[i-1] != i {
				l = i - 1
				j := i + 1
				for ; j <= n; j++ {
					if a[j-1] == i {
						r = j - 1
						break
					}
				}
				break
			}
		}

		reverse(a, l, r)
		for _, e := range a {
			printf("%d ", e)
		}
		printf("\n")

		t--
	}
}

func readInt() int {
	nStr, _ := stdin.ReadString('\n')
	nStr = strings.TrimRight(nStr, "\r\n")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readNInt() []int {
	nStr, _ := stdin.ReadString('\n')
	nStr = strings.TrimRight(nStr, "\r\n")
	arrStr := strings.Split(nStr, " ")
	arr := make([]int, len(arrStr))
	for idx, e := range arrStr {
		arr[idx], _ = strconv.Atoi(e)
	}
	return arr
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var (
	stdin  = bufio.NewReader(os.Stdin)
	printf = fmt.Printf
)

func reverse(slice []int, l int, r int) {
	for l < r {
		slice[l], slice[r] = slice[r], slice[l]
		l++
		r--
	}
}

func main() {
	t := readInt()

	for t > 0 {
		n := readInt()
		a := readNInt()

		l, r := -1, -1
		for i := 1; i <= n; i++ {
			if a[i-1] != i {
				l = i - 1
				j := i + 1
				for ; j <= n; j++ {
					if a[j-1] == i {
						r = j - 1
						break
					}
				}
				break
			}
		}

		reverse(a, l, r)
		for _, e := range a {
			printf("%d ", e)
		}
		printf("\n")

		t--
	}
}

func readInt() int {
	nStr, _ := stdin.ReadString('\n')
	nStr = strings.TrimRight(nStr, "\r\n")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readNInt() []int {
	nStr, _ := stdin.ReadString('\n')
	nStr = strings.TrimRight(nStr, "\r\n")
	arrStr := strings.Split(nStr, " ")
	arr := make([]int, len(arrStr))
	for idx, e := range arrStr {
		arr[idx], _ = strconv.Atoi(e)
	}
	return arr
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type CF1638A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1638A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1638A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1638A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1638A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1638A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1638A
Date: 12/03/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1638/A
Problem: CF1638A
**/
func (in *CF1638A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		index := 1
		ws := true
		pos := 0
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
			if arr[i] == i+1 && ws {
				index++
			} else {
				ws = false
			}
			if arr[i] == index {
				pos = i
			}
		}

		for i, j := index-1, pos; i < j; i++ {
			arr[i], arr[j] = arr[j], arr[i]
			j--
		}

		var sb strings.Builder
		for i := 0; i < n; i++ {
			sb.WriteString(fmt.Sprintf("%d ", arr[i]))
		}
		fmt.Println(sb.String())
	}
}

func NewCF1638A(r *bufio.Reader) *CF1638A {
	return &CF1638A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1638A(bufio.NewReader(os.Stdin)).Run()
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type CF1638A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1638A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1638A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1638A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1638A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1638A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1638A
Date: 12/03/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1638/A
Problem: CF1638A
**/
func (in *CF1638A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		index := 1
		ws := true
		pos := 0
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
			if arr[i] == i+1 && ws {
				index++
			} else {
				ws = false
			}
			if arr[i] == index {
				pos = i
			}
		}

		for i, j := index-1, pos; i < j; i++ {
			arr[i], arr[j] = arr[j], arr[i]
			j--
		}

		for i := 0; i < n; i++ {
			fmt.Print(arr[i], " ")
		}
		fmt.Println()
	}
}

func NewCF1638A(r *bufio.Reader) *CF1638A {
	return &CF1638A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1638A(bufio.NewReader(os.Stdin)).Run()
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type CF1638A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1638A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1638A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1638A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1638A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1638A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1638A
Date: 12/03/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1638/A
Problem: CF1638A
**/
func (in *CF1638A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		index := 1
		ws := true
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
			if arr[i] == i+1 && ws {
				index++
			} else {
				ws = false
			}
		}

		pos := 0
		for i := 0; i < n; i++ {
			if arr[i] == index {
				pos = i
			}
		}

		for i, j := index-1, pos; i < j; i++ {
			arr[i], arr[j] = arr[j], arr[i]
			j--
		}

		for i := 0; i < n; i++ {
			fmt.Print(arr[i], " ")
		}
		fmt.Println()
	}
}

func NewCF1638A(r *bufio.Reader) *CF1638A {
	return &CF1638A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1638A(bufio.NewReader(os.Stdin)).Run()
}

package main

import (
	"bufio"
	"crypto/rand"
	"fmt"
	"math"
	"math/big"
	"os"
	"sort"
	"strconv"
)

func main() {

	reader := bufio.NewReader(os.Stdin)
	writter := bufio.NewWriter(os.Stdout)
	defer writter.Flush()

	t := 0
	fmt.Fscan(reader, &t)

	for t > 0 {
		n := 0
		fmt.Fscan(reader, &n)

		p := make([]int, n)
		for i := range p {
			fmt.Fscan(reader, &p[i])
		}

		array := solve(n, p)

		for i := range array {
			fmt.Fprintf(writter, "%d ", array[i])
		}

		fmt.Fprintln(writter)

		t--
	}

	// n := 4
	// p := []int{1, 4, 3, 2}
	// fmt.Println(solve(n, p))

	//getPower()

}

func solve(n int, p []int) []int {

	l, r := -1, -1

	for i := range p {

		if p[i] == i+1 {
			continue
		}

		l = i

		for j := l + 1; j < n; j++ {
			if p[j] == i+1 {
				r = j
				break
			}
		}

		//fmt.Println(l, r)

		for j := l; j <= (l+r)/2; j++ {
			p[j], p[r-(j-l)] = p[r-(j-l)], p[j]
		}

		break

	}

	return p
}

func palindrome(str string) bool {

	size := len(str)

	for i := 0; i < size/2; i++ {
		if str[i] != str[size-1-i] {
			return false
		}
	}

	return true

}

func reverseString(str string) string {
	result := ""

	for i := len(str) - 1; i >= 0; i-- {

		result += string(str[i])

	}

	return result
}

func arraySum(array []int) int {
	sum := 0

	for i := range array {
		sum += array[i]
	}

	return sum
}

func numSum(num int) int {
	sum := 0

	for i := num; i > 0; i-- {
		sum += i
	}

	return sum
}

func strToint(str string) int {
	num, _ := strconv.Atoi(str)
	return num
}

func max(a, b int) int {
	if a >= b {
		return a
	}

	return b
}

func getFactor(num int) []int {
	result := []int{}

	for i := 1; i <= int(math.Sqrt(float64(num))); i++ {
		if num%i == 0 {
			result = append(result, i)
			result = append(result, num/i)
		}
	}

	return result
}

func gcd(a, b int) int {
	if a == 0 {
		return b
	}

	return gcd(b%a, a)
}

func printMatrix(matrix [][]int) {
	for i := range matrix {

		for j := range matrix[i] {
			fmt.Printf("%d ", matrix[i][j])
		}

		fmt.Println()

	}
}

func checkPrime(num int) bool {

	if num < 2 {
		return false
	}

	for i := 2; i <= int(math.Sqrt(float64(num))); i++ {
		if num%i == 0 {
			return false
		}
	}

	return true
}

func getPower() {
	A := []int{}

	for i := 1; i <= 38; i++ {
		A = append(A, i)
	}

	for j := 0; j < 10000; j++ {
		for i := range A {
			target, _ := rand.Int(rand.Reader, big.NewInt(38))
			A[i], A[target.Int64()] = A[target.Int64()], A[i]
		}
	}

	B, _ := rand.Int(rand.Reader, big.NewInt(8))

	result := A[:6]
	sort.Ints(result)

	fmt.Println(result)
	fmt.Println(int(B.Int64()) + 1)
}

func xor(a, b int) int {
	aBit := strconv.FormatInt(int64(a), 2)
	bBit := strconv.FormatInt(int64(b), 2)

	size := max(len(aBit), len(bBit))

	for i := size - len(aBit); i > 0; i-- {
		aBit = "0" + aBit
	}
	for i := size - len(bBit); i > 0; i-- {
		bBit = "0" + bBit
	}

	result := ""
	for i := range aBit {
		if aBit[i] == bBit[i] {
			result += "0"
		} else {
			result += "1"
		}
	}

	//fmt.Println(result)
	num, _ := strconv.ParseInt(result, 2, 64)

	return int(num)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var o []int

func rev(l, r int) {
	for l < r {
		o[l], o[r] = o[r], o[l]
		l++
		r--
	}
}

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n := 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		o = make([]int, n)
		m := map[int]int{}
		for j := 0; j < n; j++ {
			fmt.Fscan(f, &o[j])
			m[o[j]] = j
		}
		for j, k := 1, 0; j <= n; j++ {
			if m[j] != k {
				rev(k, m[j])
				break
			}
			k++
		}
		for _, v := range o {
			fmt.Fprint(w, v, " ")
		}
		fmt.Fprintln(w, "")
	}
	w.Flush()
}

func main() {
	solve()
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		list:= make([]int,n)
		for j:=0;j<n;j++{
			fmt.Fscan(in,&list[j])
		}
		var start,end,key int
		if list[0] != 1 {
			key= 1
			start= 0
		} else {
			for j:=1;j<n;j++{
				if list[j-1]+1 != list[j]  {
					start = j
					key = list[j-1]+1
					break
				}
			}
		}
		for j:=1;j<n;j++{
			if list[j] == key {
				end=j
				break
			}
		}
		counter:=0
		for j:=start;j<(end-counter);j++{
			list[j],list[end-counter] = list[end-counter],list[j]
			counter++
		}
		for j:=0;j<len(list);j++{
			fmt.Fprintf(out,"%v ",list[j])
		}
		fmt.Fprintln(out,)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var in = bufio.NewReader(os.Stdin)

func main() {
	t := readInt(in)
	for ; t != 0; t-- {
		solve()
	}
}

func solve() {
	n := readInt(in)
	a := readArrInt(in)

	l := 0
	for ; l < n && a[l] == l+1; l++ {
	}
	r := l
	for ; r < n; r++ {
		if a[r] == l+1 {
			break
		}
	}

	for i := 0; i < l; i++ {
		fmt.Print(a[i], " ")
	}

	for i := r; i >= l && i < n; i-- {
		fmt.Print(a[i], " ")
	}

	for i := r + 1; i < n; i++ {
		fmt.Print(a[i], " ")
	}
	fmt.Println()
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

//nolint
package main

import (
	"bufio"
	"fmt"
	"os"
)

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func print(a ...interface{})            { fmt.Fprint(writer, a...) }
func println(a ...interface{})          { fmt.Fprintln(writer, a...) }
func scan(a ...interface{})             { fmt.Fscan(reader, a...) }

func main() {
	defer writer.Flush()

	var t, n int
	a := make([]int, 501)
	scan(&t)
	for i := 0; i < t; i++ {
		var l, r int
		scan(&n)
		for j := 0; j < n; j++ {
			scan(&a[j])
			if l == 0 && a[j] != j+1 {
				l = j + 1
			}
			if l != 0 && a[j] == l {
				r = j + 1
			}
		}
		printResult(a, n, l, r)
	}
}

func printResult(a []int, n, l, r int) {
	l--
	r--
	idx := r
	for i := 0; i < n; i++ {
		if i < l || i > r {
			print(a[i], " ")
		} else {
			print(a[idx], " ")
			idx--
		}
	}
	println()
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

type color bool

const (
	black, red color = true, false
)

// Tree holds elements of the red-black tree
type Tree struct {
	Root       *Node
	size       int
	Comparator Comparator
}

// Node is a single element within the tree
type Node struct {
	Key    interface{}
	Value  interface{}
	color  color
	Left   *Node
	Right  *Node
	Parent *Node
}

// NewWith instantiates a red-black tree with the custom comparator.
func NewWith(comparator Comparator) *Tree {
	return &Tree{Comparator: comparator}
}

// NewWithIntComparator instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Tree {
	return &Tree{Comparator: IntComparator}
}

// NewWithStringComparator instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Tree {
	return &Tree{Comparator: StringComparator}
}

// Put inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) {
	var insertedNode *Node
	if tree.Root == nil {
		// Assert key is of comparator's type for initial tree
		tree.Comparator(key, key)
		tree.Root = &Node{Key: key, Value: value, color: red}
		insertedNode = tree.Root
	} else {
		node := tree.Root
		loop := true
		for loop {
			compare := tree.Comparator(key, node.Key)
			switch {
			case compare == 0:
				node.Key = key
				node.Value = value
				return
			case compare < 0:
				if node.Left == nil {
					node.Left = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Left
					loop = false
				} else {
					node = node.Left
				}
			case compare > 0:
				if node.Right == nil {
					node.Right = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Right
					loop = false
				} else {
					node = node.Right
				}
			}
		}
		insertedNode.Parent = node
	}
	tree.insertCase1(insertedNode)
	tree.size++
}

// Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
	node := tree.lookup(key)
	if node != nil {
		return node.Value, true
	}
	return nil, false
}

// Remove remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) {
	node := tree.lookup(key)
	tree.RemoveNode(node)
}

// RemoveNode removeNode
func (tree *Tree) RemoveNode(node *Node) {
	var child *Node
	if node == nil {
		return
	}
	if node.Left != nil && node.Right != nil {
		pred := node.Left.maximumNode()
		node.Key = pred.Key
		node.Value = pred.Value
		node = pred
	}
	if node.Left == nil || node.Right == nil {
		if node.Right == nil {
			child = node.Left
		} else {
			child = node.Right
		}
		if node.color == black {
			node.color = nodeColor(child)
			tree.deleteCase1(node)
		}
		tree.replaceNode(node, child)
		if node.Parent == nil && child != nil {
			child.color = black
		}
	}
	tree.size--
}

// Empty returns true if tree does not contain any nodes
func (tree *Tree) Empty() bool {
	return tree.size == 0
}

// Size returns number of nodes in the tree.
func (tree *Tree) Size() int {
	return tree.size
}

// Keys returns all keys in-order
func (tree *Tree) Keys() []interface{} {
	keys := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		keys[i] = it.Key()
	}
	return keys
}

// Values returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
	values := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		values[i] = it.Value()
	}
	return values
}

// Left returns the left-most (min) node or nil if tree is empty.
func (tree *Tree) Left() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Left
	}
	return parent
}

// Right returns the right-most (max) node or nil if tree is empty.
func (tree *Tree) Right() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Right
	}
	return parent
}

// Floor Finds floor node of the input key, return the floor node or nil if no floor is found.
// Second return parameter is true if floor was found, otherwise false.
//
// Floor node is defined as the largest node that is smaller than or equal to the given node.
// A floor node may not be found, either because the tree is empty, or because
// all nodes in the tree are larger than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Floor(key interface{}) (floor *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			node = node.Left
		case compare > 0:
			floor, found = node, true
			node = node.Right
		}
	}
	if found {
		return floor, true
	}
	return nil, false
}

// Lower node is defined as the largest node that is smaller than to the given node.
func (tree *Tree) Lower(key interface{}) (floor *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			node = node.Left
		case compare < 0:
			node = node.Left
		case compare > 0:
			floor, found = node, true
			node = node.Right
		}
	}
	if found {
		return floor, true
	}
	return nil, false
}

// Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
// Second return parameter is true if ceiling was found, otherwise false.
//
// Ceiling node is defined as the smallest node that is larger than or equal to the given node.
// A ceiling node may not be found, either because the tree is empty, or because
// all nodes in the tree are smaller than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Ceiling(key interface{}) (ceiling *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			ceiling, found = node, true
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	if found {
		return ceiling, true
	}
	return nil, false
}

// Higher node is defined as the smallest node that is larger than to the given node.
func (tree *Tree) Higher(key interface{}) (ceiling *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			node = node.Right
		case compare < 0:
			ceiling, found = node, true
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	if found {
		return ceiling, true
	}
	return nil, false
}

// Clear removes all nodes from the tree.
func (tree *Tree) Clear() {
	tree.Root = nil
	tree.size = 0
}

// String returns a string representation of container
func (tree *Tree) String() string {
	str := "RedBlackTree\n"
	if !tree.Empty() {
		output(tree.Root, "", true, &str)
	}
	return str
}

func (node *Node) String() string {
	return Sprintf("%v", node.Key)
}

func output(node *Node, prefix string, isTail bool, str *string) {
	if node.Right != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "│   "
		} else {
			newPrefix += "    "
		}
		output(node.Right, newPrefix, false, str)
	}
	*str += prefix
	if isTail {
		*str += "└── "
	} else {
		*str += "┌── "
	}
	*str += node.String() + "\n"
	if node.Left != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "    "
		} else {
			newPrefix += "│   "
		}
		output(node.Left, newPrefix, true, str)
	}
}

func (tree *Tree) lookup(key interface{}) *Node {
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node
		case compare < 0:
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	return nil
}

func (node *Node) grandparent() *Node {
	if node != nil && node.Parent != nil {
		return node.Parent.Parent
	}
	return nil
}

func (node *Node) uncle() *Node {
	if node == nil || node.Parent == nil || node.Parent.Parent == nil {
		return nil
	}
	return node.Parent.sibling()
}

func (node *Node) sibling() *Node {
	if node == nil || node.Parent == nil {
		return nil
	}
	if node == node.Parent.Left {
		return node.Parent.Right
	}
	return node.Parent.Left
}

func (tree *Tree) rotateLeft(node *Node) {
	right := node.Right
	tree.replaceNode(node, right)
	node.Right = right.Left
	if right.Left != nil {
		right.Left.Parent = node
	}
	right.Left = node
	node.Parent = right
}

func (tree *Tree) rotateRight(node *Node) {
	left := node.Left
	tree.replaceNode(node, left)
	node.Left = left.Right
	if left.Right != nil {
		left.Right.Parent = node
	}
	left.Right = node
	node.Parent = left
}

func (tree *Tree) replaceNode(old *Node, new *Node) {
	if old.Parent == nil {
		tree.Root = new
	} else {
		if old == old.Parent.Left {
			old.Parent.Left = new
		} else {
			old.Parent.Right = new
		}
	}
	if new != nil {
		new.Parent = old.Parent
	}
}

func (tree *Tree) insertCase1(node *Node) {
	if node.Parent == nil {
		node.color = black
	} else {
		tree.insertCase2(node)
	}
}

func (tree *Tree) insertCase2(node *Node) {
	if nodeColor(node.Parent) == black {
		return
	}
	tree.insertCase3(node)
}

func (tree *Tree) insertCase3(node *Node) {
	uncle := node.uncle()
	if nodeColor(uncle) == red {
		node.Parent.color = black
		uncle.color = black
		node.grandparent().color = red
		tree.insertCase1(node.grandparent())
	} else {
		tree.insertCase4(node)
	}
}

func (tree *Tree) insertCase4(node *Node) {
	grandparent := node.grandparent()
	if node == node.Parent.Right && node.Parent == grandparent.Left {
		tree.rotateLeft(node.Parent)
		node = node.Left
	} else if node == node.Parent.Left && node.Parent == grandparent.Right {
		tree.rotateRight(node.Parent)
		node = node.Right
	}
	tree.insertCase5(node)
}

func (tree *Tree) insertCase5(node *Node) {
	node.Parent.color = black
	grandparent := node.grandparent()
	grandparent.color = red
	if node == node.Parent.Left && node.Parent == grandparent.Left {
		tree.rotateRight(grandparent)
	} else if node == node.Parent.Right && node.Parent == grandparent.Right {
		tree.rotateLeft(grandparent)
	}
}

func (node *Node) maximumNode() *Node {
	if node == nil {
		return nil
	}
	for node.Right != nil {
		node = node.Right
	}
	return node
}

func (tree *Tree) deleteCase1(node *Node) {
	if node.Parent == nil {
		return
	}
	tree.deleteCase2(node)
}

func (tree *Tree) deleteCase2(node *Node) {
	sibling := node.sibling()
	if nodeColor(sibling) == red {
		node.Parent.color = red
		sibling.color = black
		if node == node.Parent.Left {
			tree.rotateLeft(node.Parent)
		} else {
			tree.rotateRight(node.Parent)
		}
	}
	tree.deleteCase3(node)
}

func (tree *Tree) deleteCase3(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == black &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		tree.deleteCase1(node.Parent)
	} else {
		tree.deleteCase4(node)
	}
}

func (tree *Tree) deleteCase4(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == red &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		node.Parent.color = black
	} else {
		tree.deleteCase5(node)
	}
}

func (tree *Tree) deleteCase5(node *Node) {
	sibling := node.sibling()
	if node == node.Parent.Left &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == red &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		sibling.Left.color = black
		tree.rotateRight(sibling)
	} else if node == node.Parent.Right &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Right) == red &&
		nodeColor(sibling.Left) == black {
		sibling.color = red
		sibling.Right.color = black
		tree.rotateLeft(sibling)
	}
	tree.deleteCase6(node)
}

func (tree *Tree) deleteCase6(node *Node) {
	sibling := node.sibling()
	sibling.color = nodeColor(node.Parent)
	node.Parent.color = black
	if node == node.Parent.Left && nodeColor(sibling.Right) == red {
		sibling.Right.color = black
		tree.rotateLeft(node.Parent)
	} else if nodeColor(sibling.Left) == red {
		sibling.Left.color = black
		tree.rotateRight(node.Parent)
	}
}

func nodeColor(node *Node) color {
	if node == nil {
		return black
	}
	return node.color
}

//------------------Iterator---------------------

// IteratorWithIndex is stateful iterator for ordered containers whose values can be fetched by an index.
type IteratorWithIndex interface {
	// Next moves the iterator to the next element and returns true if there was a next element in the container.
	// If Next() returns true, then next element's index and value can be retrieved by Index() and Value().
	// If Next() was called for the first time, then it will point the iterator to the first element if it exists.
	// Modifies the state of the iterator.
	Next() bool

	// Value returns the current element's value.
	// Does not modify the state of the iterator.
	Value() interface{}

	// Index returns the current element's index.
	// Does not modify the state of the iterator.
	Index() int

	// Begin resets the iterator to its initial state (one-before-first)
	// Call Next() to fetch the first element if any.
	Begin()

	// First moves the iterator to the first element and returns true if there was a first element in the container.
	// If First() returns true, then first element's index and value can be retrieved by Index() and Value().
	// Modifies the state of the iterator.
	First() bool
}

// IteratorWithKey is a stateful iterator for ordered containers whose elements are key value pairs.
type IteratorWithKey interface {
	// Next moves the iterator to the next element and returns true if there was a next element in the container.
	// If Next() returns true, then next element's key and value can be retrieved by Key() and Value().
	// If Next() was called for the first time, then it will point the iterator to the first element if it exists.
	// Modifies the state of the iterator.
	Next() bool

	// Value returns the current element's value.
	// Does not modify the state of the iterator.
	Value() interface{}

	// Key returns the current element's key.
	// Does not modify the state of the iterator.
	Key() interface{}

	// Begin resets the iterator to its initial state (one-before-first)
	// Call Next() to fetch the first element if any.
	Begin()

	// First moves the iterator to the first element and returns true if there was a first element in the container.
	// If First() returns true, then first element's key and value can be retrieved by Key() and Value().
	// Modifies the state of the iterator.
	First() bool
}

// ReverseIteratorWithIndex is stateful iterator for ordered containers whose values can be fetched by an index.
//
// Essentially it is the same as IteratorWithIndex, but provides additional:
//
// Prev() function to enable traversal in reverse
//
// Last() function to move the iterator to the last element.
//
// End() function to move the iterator past the last element (one-past-the-end).
type ReverseIteratorWithIndex interface {
	// Prev moves the iterator to the previous element and returns true if there was a previous element in the container.
	// If Prev() returns true, then previous element's index and value can be retrieved by Index() and Value().
	// Modifies the state of the iterator.
	Prev() bool

	// End moves the iterator past the last element (one-past-the-end).
	// Call Prev() to fetch the last element if any.
	End()

	// Last moves the iterator to the last element and returns true if there was a last element in the container.
	// If Last() returns true, then last element's index and value can be retrieved by Index() and Value().
	// Modifies the state of the iterator.
	Last() bool

	IteratorWithIndex
}

// ReverseIteratorWithKey is a stateful iterator for ordered containers whose elements are key value pairs.
//
// Essentially it is the same as IteratorWithKey, but provides additional:
//
// Prev() function to enable traversal in reverse
//
// Last() function to move the iterator to the last element.
type ReverseIteratorWithKey interface {
	// Prev moves the iterator to the previous element and returns true if there was a previous element in the container.
	// If Prev() returns true, then previous element's key and value can be retrieved by Key() and Value().
	// Modifies the state of the iterator.
	Prev() bool

	// End moves the iterator past the last element (one-past-the-end).
	// Call Prev() to fetch the last element if any.
	End()

	// Last moves the iterator to the last element and returns true if there was a last element in the container.
	// If Last() returns true, then last element's key and value can be retrieved by Key() and Value().
	// Modifies the state of the iterator.
	Last() bool

	IteratorWithKey
}

func assertIteratorImplementation() {
	var _ ReverseIteratorWithKey = (*Iterator)(nil)
}

// Iterator holding the Iterator 's state
type Iterator struct {
	tree     *Tree
	node     *Node
	position position
}

type position byte

const (
	begin, between, end position = 0, 1, 2
)

// Iterator returns a stateful iterator whose elements are key/value pairs.
func (tree *Tree) Iterator() Iterator {
	return Iterator{tree: tree, node: nil, position: begin}
}

// Next moves the iterator to the next element and returns true if there was a next element in the container.
// If Next() returns true, then next element's key and value can be retrieved by Key() and Value().
// If Next() was called for the first time, then it will point the iterator to the first element if it exists.
// Modifies the state of the iterator.
func (iterator *Iterator) Next() bool {
	if iterator.position == end {
		goto end
	}
	if iterator.position == begin {
		left := iterator.tree.Left()
		if left == nil {
			goto end
		}
		iterator.node = left
		goto between
	}
	if iterator.node.Right != nil {
		iterator.node = iterator.node.Right
		for iterator.node.Left != nil {
			iterator.node = iterator.node.Left
		}
		goto between
	}
	if iterator.node.Parent != nil {
		node := iterator.node
		for iterator.node.Parent != nil {
			iterator.node = iterator.node.Parent
			if iterator.tree.Comparator(node.Key, iterator.node.Key) <= 0 {
				goto between
			}
		}
	}

end:
	iterator.node = nil
	iterator.position = end
	return false

between:
	iterator.position = between
	return true
}

// Prev moves the iterator to the previous element and returns true if there was a previous element in the container.
// If Prev() returns true, then previous element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Prev() bool {
	if iterator.position == begin {
		goto begin
	}
	if iterator.position == end {
		right := iterator.tree.Right()
		if right == nil {
			goto begin
		}
		iterator.node = right
		goto between
	}
	if iterator.node.Left != nil {
		iterator.node = iterator.node.Left
		for iterator.node.Right != nil {
			iterator.node = iterator.node.Right
		}
		goto between
	}
	if iterator.node.Parent != nil {
		node := iterator.node
		for iterator.node.Parent != nil {
			iterator.node = iterator.node.Parent
			if iterator.tree.Comparator(node.Key, iterator.node.Key) >= 0 {
				goto between
			}
		}
	}

begin:
	iterator.node = nil
	iterator.position = begin
	return false

between:
	iterator.position = between
	return true
}

// Value returns the current element's value.
// Does not modify the state of the iterator.
func (iterator *Iterator) Value() interface{} {
	return iterator.node.Value
}

// Key returns the current element's key.
// Does not modify the state of the iterator.
func (iterator *Iterator) Key() interface{} {
	return iterator.node.Key
}

// Begin resets the iterator to its initial state (one-before-first)
// Call Next() to fetch the first element if any.
func (iterator *Iterator) Begin() {
	iterator.node = nil
	iterator.position = begin
}

// End moves the iterator past the last element (one-past-the-end).
// Call Prev() to fetch the last element if any.
func (iterator *Iterator) End() {
	iterator.node = nil
	iterator.position = end
}

// First moves the iterator to the first element and returns true if there was a first element in the container.
// If First() returns true, then first element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator
func (iterator *Iterator) First() bool {
	iterator.Begin()
	return iterator.Next()
}

// Last moves the iterator to the last element and returns true if there was a last element in the container.
// If Last() returns true, then last element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Last() bool {
	iterator.End()
	return iterator.Prev()
}

//------------------Comparator---------------------

type Comparator func(a, b interface{}) int

// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
	s1 := a.(string)
	s2 := b.(string)
	min := len(s2)
	if len(s1) < len(s2) {
		min = len(s1)
	}
	diff := 0
	for i := 0; i < min && diff == 0; i++ {
		diff = int(s1[i]) - int(s2[i])
	}
	if diff == 0 {
		diff = len(s1) - len(s2)
	}
	if diff < 0 {
		return -1
	}
	if diff > 0 {
		return 1
	}
	return 0
}

// IntComparator provides a basic comparison on int
func IntComparator(a, b interface{}) int {
	aAsserted := a.(int)
	bAsserted := b.(int)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int8Comparator provides a basic comparison on int8
func Int8Comparator(a, b interface{}) int {
	aAsserted := a.(int8)
	bAsserted := b.(int8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int16Comparator provides a basic comparison on int16
func Int16Comparator(a, b interface{}) int {
	aAsserted := a.(int16)
	bAsserted := b.(int16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int32Comparator provides a basic comparison on int32
func Int32Comparator(a, b interface{}) int {
	aAsserted := a.(int32)
	bAsserted := b.(int32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int64Comparator provides a basic comparison on int64
func Int64Comparator(a, b interface{}) int {
	aAsserted := a.(int64)
	bAsserted := b.(int64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UIntComparator provides a basic comparison on uint
func UIntComparator(a, b interface{}) int {
	aAsserted := a.(uint)
	bAsserted := b.(uint)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt8Comparator provides a basic comparison on uint8
func UInt8Comparator(a, b interface{}) int {
	aAsserted := a.(uint8)
	bAsserted := b.(uint8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt16Comparator provides a basic comparison on uint16
func UInt16Comparator(a, b interface{}) int {
	aAsserted := a.(uint16)
	bAsserted := b.(uint16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt32Comparator provides a basic comparison on uint32
func UInt32Comparator(a, b interface{}) int {
	aAsserted := a.(uint32)
	bAsserted := b.(uint32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt64Comparator provides a basic comparison on uint64
func UInt64Comparator(a, b interface{}) int {
	aAsserted := a.(uint64)
	bAsserted := b.(uint64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float32Comparator provides a basic comparison on float32
func Float32Comparator(a, b interface{}) int {
	aAsserted := a.(float32)
	bAsserted := b.(float32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float64Comparator provides a basic comparison on float64
func Float64Comparator(a, b interface{}) int {
	aAsserted := a.(float64)
	bAsserted := b.(float64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// ByteComparator provides a basic comparison on byte
func ByteComparator(a, b interface{}) int {
	aAsserted := a.(byte)
	bAsserted := b.(byte)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// RuneComparator provides a basic comparison on rune
func RuneComparator(a, b interface{}) int {
	aAsserted := a.(rune)
	bAsserted := b.(rune)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var T int
	Fscan(r, &T)
	for t := 0; t < T; t++ {
		var n int
		Fscan(r, &n)
		mp := NewWithIntComparator()
		a := make([]int, n)
		for i := range a {
			Fscan(r, &a[i])
			mp.Put(a[i], i)
		}
		v1 := 0
		v2 := 0
		l := 0
		for {
			mp.Remove(a[l])
			left := mp.Left()

			if left == nil {
				break
			}
			if left.Key.(int) == a[l] {
				l++
			} else if left.Key.(int) < a[l] {
				v1 = l
				v2 = left.Value.(int)
				break
			} else {
				l++
			}
		}
		reverseInPlace(a, v1, v2)
		for i := range a {
			Fprint(w, a[i], " ")
		}
		Fprintln(w)

	}

}

func reverseInPlace(a []int, s, e int) {
	n := e - s + 1
	for i := s; i < s+n/2; i++ {
		j := n - (i - s) - 1 + s
		a[i], a[j] = a[j], a[i]
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)

	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &arr[i])
		}

		l, r := 0, 0
		for i := 0; i < n-1; i++ {
			minIdx := i
			for j := n - 1; j >= i; j-- {
				if arr[j] < arr[minIdx] {
					minIdx = j
				}
			}

			if minIdx != i {
				l = i
				r = minIdx
				break
			}
		}

		for i := 0; i < l; i++ {
			fmt.Fprintf(out, "%d ", arr[i])
		}

		for i := r; i >= l; i-- {
			fmt.Fprintf(out, "%d ", arr[i])
		}

		for i := r + 1; i < n; i++ {
			fmt.Fprintf(out, "%d ", arr[i])
		}
		fmt.Fprintln(out)
	}
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
)

/*
7
1
1
2
2 1
2
1 2
3
3 1 2
3
3 2 1
3
1 2 3
4
3 1 2 4
---
1
1 2
1 3 2
1 2 3
1 2 3
1 3 2 4
======
1
4
1 4 2 3

*/

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		var n int
		scanf("%d\n", &n)

		p := make([]int, n)

		for i := range p {
			scanf("%d", &p[i])
		}
		scanf("\n")

		ans := make([]int, 0)

		for i, num := range p {
			inPlace := num == i+1
			if !inPlace {
				for j := i + 1; j < n; j++ {
					if p[j] == i+1 {
						for k := j; k >= i; k-- {
							ans = append(ans, p[k])
						}

						ans = append(ans, p[j+1:n]...)

						break
					}
				}

				break
			} else {
				ans = append(ans, num)
			}
		}

		for _, num := range ans {
			fmt.Fprintf(writer, "%d ", num)
		}
		fmt.Fprintln(writer)
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int) int {
	quot := num / div
	if num%div != 0 {
		quot++
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	minimum := nums[0]
	for _, num := range nums {
		if num < minimum {
			minimum = num
		}
	}
	return minimum
}

//goland:noinspection GoUnusedFunction
func max(nums ...int64) int64 {
	maximum := nums[0]
	for _, num := range nums {
		if num > maximum {
			maximum = num
		}
	}
	return maximum
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//A.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)
	for ; T > 0; T-- {
		var n int
		fmt.Fscan(in, &n)
		nums := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &nums[i])
		}
		var l, r int
		for ; l < n; l++ {
			if nums[l] > l+1 {
				break
			}
		}
		if l < n {
			for ; r < n; r++ {
				if nums[r] == l+1 {
					break
				}
			}
			for l < r {
				nums[l], nums[r] = nums[r], nums[l]
				l++
				r--
			}
		}
		for i := 0; i < n; i++ {
			fmt.Fprintf(out, "%d ", nums[i])
		}
		fmt.Fprintln(out)
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

var v [505]int

func find(val, n int) (index int) {
	for i := 1; i <= n; i++ {
		if val == v[i] {
			index = i
			break
		}
	}
	return
}

func reverse(l, r int) {
	if l > r {
		l, r = r, l
	}
	for l < r {
		v[l], v[r] = v[r], v[l]
		l++
		r--
	}
}

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	var n, t, g int
	first := true
	for t = read(); t > 0; t-- {
		n = read()
		for i, g := 1, 1; i <= n; i++ {
			v[i] = read()
			if first && v[g] == g {
				g++
				continue
			}
			first = false
		}
		if g <= n {
			reverse(g, find(g, n))
		}
		for i := 1; i < n; i++ {
			Fprint(out, v[i], " ")
		}
		Fprintln(out, v[n])
	}
}

func main() {
	run(os.Stdin, os.Stdout)
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

var v [505]int

func reverse(l, r int) {
	if l > r {
		l, r = r, l
	}
	for l < r {
		v[l], v[r] = v[r], v[l]
		l++
		r--
	}
}

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	var n, t, g int
	for t = read(); t > 0; t-- {
		n = read()
		for i := 1; i <= n; i++ {
			v[i] = read()
		}
		g = 1
		for g <= n && v[g] == g {
			g++
		}
		if g <= n {
			reverse(g, v[g])
		}
		for i := 1; i < n; i++ {
			Fprint(out, v[i], " ")
		}
		Fprintln(out, v[n])
	}
}

func main() {
	run(os.Stdin, os.Stdout)
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

var v [505]int

func reverse(l, r int) {
	if l > r {
		l, r = r, l
	}
	for l < r {
		v[l], v[r] = v[r], v[l]
		l++
		r--
	}
}

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	var n, t, g int
	for t = read(); t > 0; t-- {
		n = read()
		for i := 1; i <= n; i++ {
			v[i] = read()
		}
		g = 1
		for g <= n && v[g] == g {
			g++
		}
		reverse(g, v[g])
		Println(n)
		for i := 1; i < n; i++ {
			Fprint(out, v[i], " ")
		}
		Fprintln(out, v[n])
	}
}

func main() {
	run(os.Stdin, os.Stdout)
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var n, t int
	Fscan(r, &t)
	for t > 0{
		t--
		Fscan(r, &n)
		a := make([]int, n)
		for i := range a{
			Fscan(r, &a[i])
		}
		index := -1
		for i := range a{
			if in(i, a){
				index = i
				break
			}
		}
		if index != -1{
				start := index
				end := index
				min := 10
				for i := index+1; i < len(a); i++{
					if a[i] < min{
						min = a[i]
						end = i
					}
				}
				reverse(a, start, end)
			}
		for i := range a{
			if i != len(a) - 1{
				Fprintf(w, "%d ", a[i])
			}else{
				Fprintf(w, "%d\n", a[i])
			}
		}
	}
}

func in(index int, a []int) bool{
	for i := index + 1; i < len(a); i++{
		if a[i] < a[index] {
			return true
		}
	}
	return false
}

func reverse(a []int, start, end int){
	for start < end{
		a[start], a[end] = a[end], a[start]
		start++
		end--
	}
}

func str(a []int, start, end int) string{
	b := make([]byte, 0)
	for i := end; i >= start; i--{
		b = append(b, byte(a[i]))
	}
	for i := end + 1; i < len(a); i++ {
		b = append(b, byte(a[i]))
	}
	return string(b)
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var n, t int
	Fscan(r, &t)
	for t > 0{
		t--
		Fscan(r, &n)
		a := make([]int, n)
		for i := range a{
			Fscan(r, &a[i])
		}
		index := -1
		for i := range a{
			if in(i, a){
				index = i
				break
			}
		}
		//if index != -1{
		//	start := index
		//	end := index
		//	min := str(a, index, index)
		//	for i := index+1; i < len(a); i++{
		//		t := str(a, index, i)
		//		if t < min{
		//			min = t
		//			end = i
		//		}
		//	}
		//	reverse(a, start, end)
		//}
		if index != -1{
				start := index
				end := index
				min := 10
				for i := index+1; i < len(a); i++{
					if a[i] < min{
						min = t
						end = i
					}
				}
				reverse(a, start, end)
			}
		for i := range a{
			if i != len(a) - 1{
				Fprintf(w, "%d ", a[i])
			}else{
				Fprintf(w, "%d\n", a[i])
			}
		}
	}
}

func in(index int, a []int) bool{
	for i := index + 1; i < len(a); i++{
		if a[i] < a[index] {
			return true
		}
	}
	return false
}

func reverse(a []int, start, end int){
	for start < end{
		a[start], a[end] = a[end], a[start]
		start++
		end--
	}
}

func str(a []int, start, end int) string{
	b := make([]byte, 0)
	for i := end; i >= start; i--{
		b = append(b, byte(a[i]))
	}
	for i := end + 1; i < len(a); i++ {
		b = append(b, byte(a[i]))
	}
	return string(b)
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var n, t int
	Fscan(r, &t)
	for t > 0{
		t--
		Fscan(r, &n)
		a := make([]int, n)
		for i := range a{
			Fscan(r, &a[i])
		}
		index := -1
		for i := range a{
			if in(i, a){
				index = i
				break
			}
		}
		if index != -1{
			start := index
			end := index
			min := str(a, index, index)
			for i := index+1; i < len(a); i++{
				t := str(a, index, i)
				if t < min{
					min = t
					end = i
				}
			}
			reverse(a, start, end)
		}
		for i := range a{
			if i != len(a) - 1{
				Fprintf(w, "%d ", a[i])
			}else{
				Fprintf(w, "%d\n", a[i])
			}
		}
	}
}

func in(index int, a []int) bool{
	for i := index + 1; i < len(a); i++{
		if a[i] < a[index] {
			return true
		}
	}
	return false
}

func reverse(a []int, start, end int){
	for start < end{
		a[start], a[end] = a[end], a[start]
		start++
		end--
	}
}

func str(a []int, start, end int) string{
	b := make([]byte, 0)
	for i := end; i >= start; i--{
		b = append(b, byte(a[i]))
	}
	for i := end + 1; i < len(a); i++ {
		b = append(b, byte(a[i]))
	}
	return string(b)
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var n, t int
	Fscan(r, &t)
	for t > 0{
		t--
		Fscan(r, &n)
		a := make([]int, n)
		for i := range a{
			Fscan(r, &a[i])
		}
		index := -1
		for i := range a{
			if in(i, a){
				index = i
				break
			}
		}
		if index != -1{
			start := index
			end := index
			min := str(a, index, index)
			for i := index+1; i < len(a); i++{
				t := str(a, index, i)
				if t < min{
					min = t
					end = i
				}
			}
			reverse(a, start, end)
		}
		for i := range a{
			if i != len(a) - 1{
				Fprintf(w, "%d ", a[i])
			}else{
				Fprintf(w, "%d\n", a[i])
			}
		}
	}
}

func in(index int, a []int) bool{
	for i := index + 1; i < len(a); i++{
		if a[i] < a[index] {
			return true
		}
	}
	return false
}

func reverse(a []int, start, end int){
	for start < end{
		a[start], a[end] = a[end], a[start]
		start++
		end--
	}
}

func str(a []int, start, end int) string{
	b := make([]byte, 0)
	for i := end; i >= start; i--{
		b = append(b, byte(a[i]))
	}
	return string(b)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var (
	stdin  = bufio.NewReader(os.Stdin)
	stdout = bufio.NewWriter(os.Stdin)
)

func printf(f string, a ...interface{}) { fmt.Fprintf(stdout, f, a...) }

func reverse(slice []int, l int, r int) {
	for l < r {
		slice[l], slice[r] = slice[r], slice[l]
		l++
		r--
	}
}

func main() {
	t := readInt()

	for t > 0 {
		n := readInt()
		a := readNInt()

		l, r := -1, -1
		for i := 1; i <= n; i++ {
			if a[i-1] != i {
				l = i - 1
				j := i + 1
				for ; j <= n; j++ {
					if a[j-1] == i {
						r = j - 1
						break
					}
				}
				break
			}
		}

		reverse(a, l, r)
		for _, e := range a {
			printf("%d ", e)
		}
		printf("\n")

		t--
	}
}

func readInt() int {
	nStr, _ := stdin.ReadString('\n')
	nStr = strings.TrimRight(nStr, "\r\n")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readNInt() []int {
	nStr, _ := stdin.ReadString('\n')
	nStr = strings.TrimRight(nStr, "\r\n")
	arrStr := strings.Split(nStr, " ")
	arr := make([]int, len(arrStr))
	for idx, e := range arrStr {
		arr[idx], _ = strconv.Atoi(e)
	}
	return arr
}

package main

import (
	"bufio"
	"crypto/rand"
	"fmt"
	"math"
	"math/big"
	"os"
	"sort"
	"strconv"
)

func main() {

	reader := bufio.NewReader(os.Stdin)
	writter := bufio.NewWriter(os.Stdout)
	defer writter.Flush()

	t := 0
	fmt.Fscan(reader, &t)

	for t > 0 {
		n := 0
		fmt.Fscan(reader, &n)

		p := make([]int, n)
		for i := range p {
			fmt.Fscan(reader, &p[i])
		}

		array := solve(n, p)

		for i := range array {
			fmt.Fprintf(writter, "%d ", array[i])
		}

		fmt.Fprintln(writter)

		t--
	}

	// n := 3
	// p := []int{2, 1, 3}
	// fmt.Println(solve(n, p))

	//getPower()

}

func solve(n int, p []int) []int {

	l, r := -1, -1

	for i := range p {

		if p[i] == i+1 {
			continue
		}

		l = i

		for j := i + 1; j < n; j++ {
			if j == i+1 {
				r = j
				break
			}
		}

		for j := l; j <= (l+r)/2; j++ {
			p[j], p[r-(j-l)] = p[r-(j-l)], p[j]
		}

		break

	}

	return p
}

func palindrome(str string) bool {

	size := len(str)

	for i := 0; i < size/2; i++ {
		if str[i] != str[size-1-i] {
			return false
		}
	}

	return true

}

func reverseString(str string) string {
	result := ""

	for i := len(str) - 1; i >= 0; i-- {

		result += string(str[i])

	}

	return result
}

func arraySum(array []int) int {
	sum := 0

	for i := range array {
		sum += array[i]
	}

	return sum
}

func numSum(num int) int {
	sum := 0

	for i := num; i > 0; i-- {
		sum += i
	}

	return sum
}

func strToint(str string) int {
	num, _ := strconv.Atoi(str)
	return num
}

func max(a, b int) int {
	if a >= b {
		return a
	}

	return b
}

func getFactor(num int) []int {
	result := []int{}

	for i := 1; i <= int(math.Sqrt(float64(num))); i++ {
		if num%i == 0 {
			result = append(result, i)
			result = append(result, num/i)
		}
	}

	return result
}

func gcd(a, b int) int {
	if a == 0 {
		return b
	}

	return gcd(b%a, a)
}

func printMatrix(matrix [][]int) {
	for i := range matrix {

		for j := range matrix[i] {
			fmt.Printf("%d ", matrix[i][j])
		}

		fmt.Println()

	}
}

func checkPrime(num int) bool {

	if num < 2 {
		return false
	}

	for i := 2; i <= int(math.Sqrt(float64(num))); i++ {
		if num%i == 0 {
			return false
		}
	}

	return true
}

func getPower() {
	A := []int{}

	for i := 1; i <= 38; i++ {
		A = append(A, i)
	}

	for j := 0; j < 10000; j++ {
		for i := range A {
			target, _ := rand.Int(rand.Reader, big.NewInt(38))
			A[i], A[target.Int64()] = A[target.Int64()], A[i]
		}
	}

	B, _ := rand.Int(rand.Reader, big.NewInt(8))

	result := A[:6]
	sort.Ints(result)

	fmt.Println(result)
	fmt.Println(int(B.Int64()) + 1)
}

func xor(a, b int) int {
	aBit := strconv.FormatInt(int64(a), 2)
	bBit := strconv.FormatInt(int64(b), 2)

	size := max(len(aBit), len(bBit))

	for i := size - len(aBit); i > 0; i-- {
		aBit = "0" + aBit
	}
	for i := size - len(bBit); i > 0; i-- {
		bBit = "0" + bBit
	}

	result := ""
	for i := range aBit {
		if aBit[i] == bBit[i] {
			result += "0"
		} else {
			result += "1"
		}
	}

	//fmt.Println(result)
	num, _ := strconv.ParseInt(result, 2, 64)

	return int(num)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var o []int

func rev(l, r int) {
	for l < r {
		o[l], o[r] = o[r], o[l]
		l++
		r--
	}
}

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n := 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		o = make([]int, n)
		m := map[int]int{}
		for j := 0; j < n; j++ {
			fmt.Fscan(f, &o[j])
			m[o[j]] = j
		}
		for j, k := 1, 0; j <= n; j++ {
			if m[j] != 0 && m[j] != k {
				rev(k, m[o[j]])
				break
			}
			k++
		}
		for _, v := range o {
			fmt.Fprint(w, v, " ")
		}
		fmt.Fprintln(w, "")
	}
	w.Flush()
}

func main() {
	solve()
}


There are $$$n$$$ people in this world, conveniently numbered $$$1$$$ through $$$n$$$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $$$d(a,b)$$$ denote the debt of $$$a$$$ towards $$$b$$$, or $$$0$$$ if there is no such debt.Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money. When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done:  Let $$$d(a,b) > 0$$$ and $$$d(c,d) > 0$$$ such that $$$a \neq c$$$ or $$$b \neq d$$$. We can decrease the $$$d(a,b)$$$ and $$$d(c,d)$$$ by $$$z$$$ and increase $$$d(c,b)$$$ and $$$d(a,d)$$$ by $$$z$$$, where $$$0 < z \leq \min(d(a,b),d(c,d))$$$.  Let $$$d(a,a) > 0$$$. We can set $$$d(a,a)$$$ to $$$0$$$. The total debt is defined as the sum of all debts:$$$$$$\Sigma_d = \sum_{a,b} d(a,b)$$$$$$Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.

The first line contains two space separated integers $$$n$$$ ($$$1 \leq n \leq 10^5$$$) and $$$m$$$ ($$$0 \leq m \leq 3\cdot 10^5$$$), representing the number of people and the number of debts, respectively. $$$m$$$ lines follow, each of which contains three space separated integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), $$$d_i$$$ ($$$1 \leq d_i \leq 10^9$$$), meaning that the person $$$u_i$$$ borrowed $$$d_i$$$ burles from person $$$v_i$$$.

On the first line print an integer $$$m'$$$ ($$$0 \leq m' \leq 3\cdot 10^5$$$), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint. After that print $$$m'$$$ lines, $$$i$$$-th of which contains three space separated integers $$$u_i, v_i, d_i$$$, meaning that the person $$$u_i$$$ owes the person $$$v_i$$$ exactly $$$d_i$$$ burles. The output must satisfy $$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$ and $$$0 < d_i \leq 10^{18}$$$. For each pair $$$i \neq j$$$, it should hold that $$$u_i \neq u_j$$$ or $$$v_i \neq v_j$$$. In other words, each pair of people can be included at most once in the output.

NoteIn the first example the optimal sequence of operations can be the following:  Perform an operation of the first type with $$$a = 1$$$, $$$b = 2$$$, $$$c = 2$$$, $$$d = 3$$$ and $$$z = 5$$$. The resulting debts are: $$$d(1, 2) = 5$$$, $$$d(2, 2) = 5$$$, $$$d(1, 3) = 5$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 2$$$. The resulting debts are: $$$d(1, 2) = 5$$$, $$$d(1, 3) = 5$$$, all other debts are $$$0$$$. In the second example the optimal sequence of operations can be the following:  Perform an operation of the first type with $$$a = 1$$$, $$$b = 2$$$, $$$c = 3$$$, $$$d = 1$$$ and $$$z = 10$$$. The resulting debts are: $$$d(3, 2) = 10$$$, $$$d(2, 3) = 15$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the first type with $$$a = 2$$$, $$$b = 3$$$, $$$c = 3$$$, $$$d = 2$$$ and $$$z = 10$$$. The resulting debts are: $$$d(2, 2) = 10$$$, $$$d(3, 3) = 10$$$, $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 2$$$. The resulting debts are: $$$d(3, 3) = 10$$$, $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 3$$$. The resulting debts are: $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 1$$$. The resulting debts are: $$$d(2, 3) = 5$$$, all other debts are $$$0$$$.

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

type node struct {
	l, r, id int
}

type nodes []node

func (a nodes) Len() int           { return len(a) }
func (a nodes) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a nodes) Less(i, j int) bool { return a[i].r > a[j].r }

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, m := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &m)
	o, p, q := 0, 0, 0
	debt := make([]int64, n)
	for i := 0; i < m; i++ {
		fmt.Fscanf(in, "%d %d %d\n", &o, &p, &q)
		debt[o-1] += int64(q)
		debt[p-1] -= int64(q)
	}
	a := []int{}
	b := []int{}
	for i := 0; i < n; i++ {
		if debt[i] > 0 {
			a = append(a, i)
		} else if debt[i] < 0 {
			b = append(b, i)
		}
	}
	ans := [][]int64{}
	//fmt.Println("debug", a, b)
	//fmt.Println(debt)
	for true {
		//fmt.Println("debug", a, b)
		//fmt.Println(debt)
		if len(a) == 0 || len(b) == 0 {
			break
		}

		if len(a) > 0 && debt[a[0]] == 0 {
			a = a[1:]
		}
		if len(b) > 0 && debt[b[0]] == 0 {
			b = b[1:]
		}
		if len(a) == 0 || len(b) == 0 {
			break
		}
		if debt[a[0]]+debt[b[0]] >= 0 {
			debt[a[0]] += debt[b[0]]
			ans = append(ans, []int64{int64(a[0]), int64(b[0]), -debt[b[0]]})
			b = b[1:]
		} else {
			debt[b[0]] += debt[a[0]]
			ans = append(ans, []int64{int64(a[0]), int64(b[0]), debt[a[0]]})
			a = a[1:]
		}
	}
	fmt.Fprintf(out, "%d\n", len(ans))
	for i := 0; i < len(ans); i++ {
		fmt.Fprintf(out, "%d %d %d\n", ans[i][0]+1, ans[i][1]+1, ans[i][2])
	}
	return
}

func findPattern(a []int, m int) int {
	sort.Ints(a)
	for i := 1; i <= len(a)/2; i++ {
		if len(a)%i == 0 {
			if work(a, i, m) {
				return len(a) / i
			}
		}
	}
	return 1
}

func work(a []int, l int, m int) bool {
	//fmt.Println(a, l, m)
	n := len(a)
	numOfSeg := n / l
	for i := 1; i < numOfSeg; i++ {
		if a[i*l]-a[(i-1)*l] != (a[0] + m - a[(numOfSeg-1)*l]) {
			//fmt.Println(a, l, "debug")
			return false
		}
	}
	for j := 1; j < l; j++ {
		for i := 1; i < n/l; i++ {
			if a[i*l+j]-a[i*l+j-1] != a[j]-a[j-1] {
				//fmt.Println(a, l, "debug2")
				return false
			}
		}
	}
	return true
}

func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}


A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.You are given a binary string $$$s$$$ of length $$$n$$$. Construct two balanced bracket sequences $$$a$$$ and $$$b$$$ of length $$$n$$$ such that for all $$$1\le i\le n$$$:   if $$$s_i=1$$$, then $$$a_i=b_i$$$  if $$$s_i=0$$$, then $$$a_i\ne b_i$$$ If it is impossible, you should report about it.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ is even). The next line contains a string $$$s$$$ of length $$$n$$$, consisting of characters 0 and 1. The sum of $$$n$$$ across all test cases does not exceed $$$2\cdot 10^5$$$.

If such two balanced bracked sequences exist, output "YES" on the first line, otherwise output "NO". You can print each letter in any case (upper or lower). If the answer is "YES", output the balanced bracket sequences $$$a$$$ and $$$b$$$ satisfying the conditions on the next two lines. If there are multiple solutions, you may print any.

NoteIn the first test case, $$$a=$$$"()()()" and $$$b=$$$"((()))". The characters are equal in positions $$$1$$$, $$$3$$$, $$$4$$$, and $$$6$$$, which are the exact same positions where $$$s_i=1$$$.In the second test case, $$$a=$$$"()()((()))" and $$$b=$$$"(())()()()". The characters are equal in positions $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$10$$$, which are the exact same positions where $$$s_i=1$$$.In the third test case, there is no solution.

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n := readNum(reader)
		s := readString(reader)
		a, b, ok := solve(s[:n])
		if !ok {
			buf.WriteString("NO\n")
		} else {
			buf.WriteString("YES\n")
			buf.WriteString(a)
			buf.WriteByte('\n')
			buf.WriteString(b)
			buf.WriteByte('\n')
		}
	}

	fmt.Print(buf.String())
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func solve(s string) (string, string, bool) {
	// s[i] == 1, then a[i] = b[i], else a[i] != b[i]
	// s[i] = 1, a[i] => b[i], else a[i] => !b[i]
	// 相同的部分如果是偶数 可以一半 (, 一半)
	n := len(s)

	if s[0] != '1' || s[n-1] != '1' {
		return "", "", false
	}
	a := make([]byte, n)
	b := make([]byte, n)

	var cnt0, cnt1 int

	a[0] = '('
	b[0] = '('

	for i := 1; i < n-1; i++ {
		if s[i] == '0' {
			cnt0++
			if cnt0&1 == 1 {
				a[i] = '('
				b[i] = ')'
			} else {
				a[i] = ')'
				b[i] = '('
			}
		} else {
			cnt1++
			if cnt1&1 == 1 {
				b[i] = '('
				a[i] = '('
			} else {
				b[i] = ')'
				a[i] = ')'
			}
		}
	}

	if cnt0&1 > 0 {
		return "", "", false
	}
	a[n-1] = ')'
	b[n-1] = ')'

	return string(a), string(b), true
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var n int
		fmt.Fscan(in,&n)
		var s []byte
		fmt.Fscan(in,&s)
		a := []byte{}
		b := []byte{}
		cnt1:=0
		cnt0:=0
		for i:=0;i<len(s);i++{
			if s[i]=='1'{
				cnt1++
			}else{
				cnt0++
			}
		}
		t1 := cnt1
		if cnt1%2==1||cnt0%2==1||s[0]=='0'||s[len(s)-1]=='0'{
			fmt.Fprintln(out,"NO")
			continue
		}
		for i:=0;i<len(s);i++{
			if s[i]=='1'{
				if cnt1>t1/2{
					a = append(a,'(')
					b = append(b,'(')
					cnt1--
				}else{
					a = append(a,')')
					b = append(b,')')
				}
			}else{
				if cnt0%2==0{
					a = append(a,')')
					b = append(b,'(')
				}else{
					a = append(a,'(')
					b = append(b,')')
				}
				cnt0--
			}
		}

			fmt.Fprintln(out,"YES")
			fmt.Fprintln(out,string(a))
			fmt.Fprintln(out,string(b))

	}
}

package main
import (
	"bufio"
	. "fmt"
	"os"
	"strings"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	T, n, s, f := 0, 0, "", false
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &s)
		o := strings.Count(s, "1")
		if s[0] == '0' || s[n-1] == '0' || o&1 > 0 {
			Fprintln(out, "NO")
			continue
		}
		o /= 2
		x := make([]byte, n)
		y := make([]byte, n)
		for i, b := range s {
			if b == '1' {
				if o > 0 {
					x[i]='(';y[i]='(';o--
				} else {
					x[i]=')';y[i]=')'
				}
			} else {
				if f = !f;f {
					x[i]='(';y[i]=')'
				} else {
					x[i]=')';y[i]='('
				}
			}
		}
		Fprintf(out, "YES\n%s\n%s\n", x, y)
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"strings"
)

// github.com/EndlessCheng/codeforces-go
func CF1503A(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, n, c0 int
	var s string
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &s)
		c1 := strings.Count(s, "1")
		if s[0] == '0' || s[n-1] == '0' || c1&1 > 0 {
			Fprintln(out, "NO")
			continue
		}
		c1 /= 2
		x := make([]byte, n)
		y := make([]byte, n)
		for i, b := range s {
			if b == '1' {
				if c1 > 0 {
					c1--
					x[i] = '('
					y[i] = '('
				} else {
					x[i] = ')'
					y[i] = ')'
				}
			} else {
				c0 ^= 1
				if c0 > 0 {
					x[i] = '('
					y[i] = ')'
				} else {
					x[i] = ')'
					y[i] = '('
				}
			}
		}
		Fprintf(out, "YES\n%s\n%s\n", x, y)
	}
}

func main() { CF1503A(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n := readNum(reader)
		s := readString(reader)
		a, b, ok := solve(s[:n])
		if !ok {
			buf.WriteString("NO\n")
		} else {
			buf.WriteString("YES\n")
			buf.WriteString(a)
			buf.WriteByte('\n')
			buf.WriteString(b)
			buf.WriteByte('\n')
		}
	}

	fmt.Print(buf.String())
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func solve(s string) (string, string, bool) {
	// s[i] == 1, then a[i] = b[i], else a[i] != b[i]
	// s[i] = 1, a[i] => b[i], else a[i] => !b[i]
	// 相同的部分如果是偶数 可以一半 (, 一半)
	n := len(s)
	a := make([]byte, n)
	b := make([]byte, n)

	que := make([]int, n)
	var front, end int

	var open_a, open_b int

	for i := 0; i < n; i++ {
		if open_a > 0 {
			a[i] = ')'
			open_a--
		} else {
			a[i] = '('
			open_a++
		}
		if s[i] == '1' {
			b[i] = a[i]
			if a[i] == ')' {
				// may change in future
				que[end] = i
				end++
			}
		} else {
			b[i] = ')'
			if a[i] == ')' {
				b[i] = '('
			}
		}
		if b[i] == '(' {
			open_b++
		} else {
			open_b--
		}

		if open_b < 0 {
			if front == end {
				return "", "", false
			}
			ii := que[front]
			front++
			a[ii] = '('
			open_a += 2
			b[ii] = '('
			open_b += 2
		}
	}

	for i := n - 1; i > 0 && open_a > 1 && open_b > 1; i-- {
		if a[i] == '(' && b[i] == '(' {
			a[i] = ')'
			b[i] = ')'
			open_a -= 2
			open_b -= 2
		}
	}

	if open_a > 0 || open_b > 0 {
		return "", "", false
	}
	return string(a), string(b), true
}

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n := readNum(reader)
		s := readString(reader)
		a, b, ok := solve(s[:n])
		if !ok {
			buf.WriteString("NO\n")
		} else {
			buf.WriteString("YES\n")
			buf.WriteString(a)
			buf.WriteByte('\n')
			buf.WriteString(b)
			buf.WriteByte('\n')
		}
	}

	fmt.Print(buf.String())
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func solve(s string) (string, string, bool) {
	// s[i] == 1, then a[i] = b[i], else a[i] != b[i]
	// s[i] = 1, a[i] => b[i], else a[i] => !b[i]
	// 相同的部分如果是偶数 可以一半 (, 一半)
	n := len(s)
	a := make([]byte, n)
	b := make([]byte, n)

	que := make([]int, n)
	var front, end int

	var open_a, open_b int

	for i := 0; i < n; i++ {
		if open_a > 0 {
			a[i] = ')'
			open_a--
		} else {
			a[i] = '('
			open_a++
		}
		if s[i] == '1' {
			b[i] = a[i]
			if a[i] == ')' {
				// may change in future
				que[end] = i
				end++
			}
		} else {
			b[i] = ')'
			if a[i] == ')' {
				b[i] = '('
			}
		}
		if b[i] == '(' {
			open_b++
		} else {
			open_b--
		}

		if open_b < 0 {
			if front == end {
				return "", "", false
			}
			ii := que[front]
			front++
			a[ii] = '('
			open_a += 2
			b[ii] = '('
			open_b += 2
		}
	}

	if open_a > 0 || open_b > 0 {
		return "", "", false
	}
	return string(a), string(b), true
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var n int
		fmt.Fscan(in,&n)
		var s []byte
		fmt.Fscan(in,&s)
		a := []byte{}
		for i:=0;i<len(s);i++{
			if i%2==0{
				a = append(a,'(')
			}else{
				a = append(a,')')
			}
		}
		b := []byte{}
		for i:=0;i<len(s);i++{
			if s[i]=='1'{
				if a[i]=='('{
					b = append(b,'(')
				}
				if a[i]==')'{
					b = append(b,')')
				}
			}else{
				if a[i]=='('{
					b = append(b,')')
				}
				if a[i]==')'{
					b = append(b,'(')
				}
			}
		}
		st := []byte{}
		flag := true
		for i:=0;i<len(s);i++{
			if b[i]==')'{
				if len(st)==0{
					flag = false
					break
				}else{
					st = st[:len(st)-1]
				}
			}else{
				st = append(st,'(')
			}
		}
		if len(st)>0{
			flag= false
		}
		if !flag{
			fmt.Fprintln(out,"NO")
		}else{
			fmt.Fprintln(out,"YES")
			fmt.Fprintln(out,string(a))
			fmt.Fprintln(out,string(b))
		}
	}
}