package main

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

var scanner = bufio.NewScanner(os.Stdin)

func scanNum() int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}

func main() {
	scanner.Split(bufio.ScanWords)
	n := scanNum()
	idMap, L, R := map[int]int{}, -1, -1
	for i := 0; i < n; i++ {
		scanner.Scan()
		mode := scanner.Text()
		num := scanNum()
		if R == -1 {
			idMap[num], L, R = 0, 0, 0
			continue
		}
		if mode == "R" {
			idMap[num], R = R+1, R+1
		}
		if mode == "L" {
			idMap[num], L = L-1, L-1
		}
		if mode == "?" {
			c1, c2 := idMap[num]-L, R-idMap[num]
			if c1 < c2 {
				fmt.Println(c1)
			} else {
				fmt.Println(c2)
			}
		}
	}
}

package main

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

const (
	MaxN = 200005
)

var n int
var p1, p2 int
var data [MaxN]int

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

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(inBuf, "%d\n", &n)
	p1, p2 = 0, 1
	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()
	for i := 0; i < n; i++ {
		var q byte
		var val int
		fmt.Fscanf(inBuf, "%c %d\n", &q, &val)
		if q == 'L' {
			data[val] = p1
			p1--
		}
		if q == 'R' {
			data[val] = p2
			p2++
		}
		if q == '?' {
			pos := data[val]
			fmt.Println(min(pos - p1, p2 - pos) - 1)
		}
	}
}

package main

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

var qnum int
var lnum, rnum int = 0, 0

var qtype map[int]string
var qlnum, qrnum map[int]int
var qtotal map[int]int

var total int = 0

func getAns(id int) int {
  var l, r = lnum - qlnum[id], rnum - qrnum[id]
  if qtype[id] == "L" {
    r += qtotal[id] - 1
  } else {
    l += qtotal[id] - 1
  }
  if l < r {
    return l
  } else {
    return r
  }
}

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

  qtype = make(map[int]string)
  qlnum = make(map[int]int)
  qrnum = make(map[int]int)
  qtotal = make(map[int]int)

  fmt.Fscanf(reader, "%d\n", &qnum)
  for i := 0; i < qnum; i++ {
    var q string
    var id int
    fmt.Fscanf(reader, "%s %d\n", &q, &id)
    if q == "L" {
      lnum++
    } else if q == "R" {
      rnum++
    }
    if q == "?" {
      fmt.Fprintf(writer, "%d\n", getAns(id))
    } else {
      total++
      qtype[id] = q
      qlnum[id] = lnum
      qrnum[id] = rnum
      qtotal[id] = total
    }
  }
}

package main

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

func min(x int, y int) int{
	if(x < y){
		return x
	}
	return y
}

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

	var n, id int
	l, r := 0, 0
	mp := make(map[int]int)
	dir := make(map[int]int)
	var str string

	fmt.Fscan(reader, &n)
	for i := 0; i < n; i ++{
		//fmt.Fscanf(reader,"%s %d", &str, &id)
		fmt.Fscan(reader, &str, &id)
		//fmt.Println(n, str, id)
		if str == "L"{
			l ++
			mp[id] = l
			dir[id] = -1
		} else if str == "R" {
			r ++
			mp[id] = r
			dir[id] = 1
		}else {
			if dir[id] == -1 {
				fmt.Fprintln(writer, min(l-mp[id], mp[id]-1+r))
				//fmt.Println(min(l-mp[id], mp[id]-1+r))
			}else{
				fmt.Fprintln(writer, min(r-mp[id], mp[id]-1+l))
				//fmt.Println(min(r-mp[id], mp[id]-1+l))
			}
			//fmt.Printf("l=%d, mp[id]=%d, r=%d\n", l, mp[id], r)
		}
	}

}

package main

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

var qnum int
var lnum, rnum = 0, 0

var qtype map[int]string
var qlnum, qrnum map[int]int
var qtotal map[int]int

var total = 0

func getAns(id int) int {
  var l, r = lnum - qlnum[id], rnum - qrnum[id]
  if qtype[id] == "L" {
    r += qtotal[id] - 1
  } else {
    l += qtotal[id] - 1
  }
  if l < r {
    return l
  } else {
    return r
  }
}

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

  qtype = make(map[int]string)
  qlnum = make(map[int]int)
  qrnum = make(map[int]int)
  qtotal = make(map[int]int)

  fmt.Fscanf(reader, "%d\n", &qnum)
  for i := 0; i < qnum; i++ {
    var q string
    var id int
    fmt.Fscanf(reader, "%s %d\n", &q, &id)
    qtype[id] = q
    if q == "L" {
      lnum++
    } else if q == "R" {
      rnum++
    }
    if q == "?" {
      fmt.Fprintf(writer, "%d\n", getAns(id))
    } else {
      total++
      qlnum[id] = lnum
      qrnum[id] = rnum
      qtotal[id] = total
    }
  }
}

package main

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

func min(x int, y int) int{
	if(x < y){
		return x
	}
	return y
}

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

	var n, id int
	l, r := 0, 0
	mp := make(map[int]int)
	dir := make(map[int]int)
	var str string
	fmt.Scan(&n)
	for i := 0; i < n; i ++{
		fmt.Fscanf(reader,"%s %d", &str, &id)
		//fmt.Println(n, str, id)
		if str == "L"{
			l ++
			mp[id] = l
			dir[id] = -1
		} else if str == "R" {
			r ++
			mp[id] = r
			dir[id] = 1
		}else {
			if dir[id] == -1 {
				fmt.Fprintln(writer, min(l-mp[id], mp[id]-1+r))
				//fmt.Println(min(l-mp[id], mp[id]-1+r))
			}else{
				fmt.Fprintln(writer, min(r-mp[id], mp[id]-1+l))
				//fmt.Println(min(r-mp[id], mp[id]-1+l))
			}
		}
	}

}


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(' ')
	}
}


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) }


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"
	"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"
	"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()
}


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"
	"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"
	"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))
		}
	}
}


package main

import (
	"fmt"
)

func main() {
	var n, time, left, right, leftZeros, leftOnes, rightZeros, rightOnes uint16

	fmt.Scan(&n)

	for i := 0; i < int(n); i++ {
		fmt.Scan(&left)
		fmt.Scan(&right)

		switch left {
		case 1:
			leftOnes++
			break
		default:
			leftZeros++
		}

		switch right {
		case 1:
			rightOnes++
			break
		default:
			rightZeros++
		}
	}

	if leftZeros > leftOnes {
		time = leftOnes
	} else {
		time = leftZeros
	}

	if rightZeros > rightOnes {
		time += rightOnes
	} else {
		time += rightZeros
	}

	fmt.Println(time)
}

package main

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

func main() {
	n := readi()
	var leftCount, rightCount int
	for i := 0; i < n; i++ {
		l, r := readi(), readi()
		leftCount += l
		rightCount += r
	}
	fmt.Fprintln(writer, min(leftCount, n-leftCount)+min(rightCount, n-rightCount))
	writer.Flush()
}

func median(values []int) float64 {
	res := 0
	for _, v := range values {
		res += v
	}
	return float64(res) / float64(len(values))
}

func perfectPermutation(n int) string {
	if n%2 == 1 {
		return "-1"
	}
	values := make([]int, 0)
	for i := 0; i < n; i++ {
		values = append(values, n-i)
	}
	str := ""
	for _, v := range values {
		str += fmt.Sprint(v, " ")
	}
	return str
}

func isNextPrime(n, m int) bool {
	for i := n + 1; i < m; i++ {
		if isPrime(i) {
			return false
		}
	}
	return isPrime(m)
}

func isPrime(n int) bool {
	for x := 2; x*x <= n; x++ {
		if n%x == 0 {
			return false
		}
	}
	return n > 1
}

func withSameCase(word string) string {
	lowerCount := 0
	for _, letter := range word {
		if unicode.IsLower(letter) {
			lowerCount++
		}
	}
	if lowerCount*2 >= len(word) {
		return strings.ToLower(word)
	}
	return strings.ToUpper(word)
}

func solve(matrix [][]int) []string {
	n := 3
	state := make([][]byte, n)
	for i := range state {
		state[i] = make([]byte, n)
		for j := range matrix[i] {
			state[i][j] = byte(matrix[i][j])
			if i > 0 {
				state[i][j] += byte(matrix[i-1][j])
			}
			if i+1 < n {
				state[i][j] += byte(matrix[i+1][j])
			}
			if j > 0 {
				state[i][j] += byte(matrix[i][j-1])
			}
			if j+1 < n {
				state[i][j] += byte(matrix[i][j+1])
			}
			state[i][j] &= 1
			state[i][j] ^= 1
			state[i][j] += '0'
		}
	}
	res := make([]string, n)
	for i := range res {
		res[i] = string(state[i])
	}
	return res
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func abs64(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

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

func max64(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

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

func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

var (
	reader = bufio.NewReaderSize(os.Stdin, 1<<13)
	writer = bufio.NewWriterSize(os.Stdout, 1<<13)
)

func readi() int {
	return int(readi64())
}

func read2i() (int, int) {
	return readi(), readi()
}

func read3i() (int, int, int) {
	return readi(), readi(), readi()
}

func read4i() (int, int, int, int) {
	return readi(), readi(), readi(), readi()
}

func readis(n int) []int {
	res := make([]int, n)
	for i := range res {
		res[i] = readi()
	}
	return res
}

func readi64() int64 {
	b, err := reader.ReadByte()
	for !isValid(b, err) {
		b, err = reader.ReadByte()
	}
	sign, res := int64(1), int64(0)
	if b == '-' {
		sign *= -1
		b, err = reader.ReadByte()
	}
	for isValid(b, err) {
		res = res*10 + int64(b-'0')
		b, err = reader.ReadByte()
	}
	return res * sign
}

func readi64s(n int) []int64 {
	res := make([]int64, n)
	for i := range res {
		res[i] = readi64()
	}
	return res
}

func readline() string {
	res := new(bytes.Buffer)
	for {
		line, isPrefix, err := reader.ReadLine()
		if err != nil {
			panic(err)
		}
		res.Write(line)
		if !isPrefix {
			break
		}
	}
	return res.String()
}

func isValid(b byte, err error) bool {
	return err == nil && (('0' <= b && b <= '9') || b == '-')
}

package main

import (
	"fmt"
)

func main() {
	var n,a,b,c,d,e,f int
	fmt.Scan(&n)
	a,b=0,0
	for i:=0;i<n;i++ {
		fmt.Scan(&c,&d)
		a+=c
		b+=d
	}
	if a>n-a {
		e=n-a
	} else {
		e=a
	}
	if b>n-b {
		f=n-b
	} else {
		f=b
	}
	fmt.Println(e+f)
}

package main

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

func scanInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	x, _ := strconv.Atoi(scanner.Text())
	return x
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	left, right := 0, 0
	for i := 0; i < n; i++ {
		l, r := scanInt(scanner), scanInt(scanner)
		left += l
		right += r
	}
	if n-left < left {
		left = n-left
	}
	if n-right < right {
		right = n-right
	}
	writer.WriteString(fmt.Sprintf("%d\n", left+right))
}

package main

import "fmt"

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

func main() {
    var n,l,r int
    fmt.Scan(&n)
    L, R := 0, 0
    for i := 0; i < n; i++ {
        fmt.Scan(&l,&r)
        L += l
        R += r
    }
    fmt.Println(min(L,n-L)+min(R,n-R))
}

package main

import "fmt"

func min(a,b int) int { if a < b { return a } else { return b } }   // fungsi yang mengembalikan nilai terkecil di antara 2 bilangan

func main() {
    var n,l,r int               // membuat variabel n, l, dan r dengan tipe data int
    fmt.Scan(&n)                // menerima input n
    L, R := 0, 0                // membuat variabel L dan R dengan tipe data int dengan nilai awal 0
    for i := 0; i < n; i++ {    // looping sebanyak n kali
        fmt.Scan(&l,&r)         // menerima input l dan r
        L += l                  // tambahkan l ke L
        R += r                  // tambahkan r ke R
    }
    fmt.Println(min(L,n-L)+min(R,n-R))      // mencetak output nilai penjumlahan antara nilai minimum L dengan n-L dan nilai minimum R dengan n-R
}

package main

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

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...) }

type intPair struct {
	a int64
	b int64
}

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

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

func main() {
	defer writer.Flush()
	var n int
	scanf("%d\n", &n)
	left := map[int]bool{}
	right := map[int]bool{}

	for i :=0;i<n;i++ {
		var li,ri int
		scanf("%d %d\n", &li, &ri)
		if(li == 1) {
			left[i] = true
		}
		if(ri == 1) {
			right[i] = true
		}
	}
	ans := min(len(left), n-len(left)) + min(len(right), n-len(right))
	printf("%d\n", ans)
}

package main

import "fmt"

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

func main() {
    var n,l,r int
    fmt.Scan(&n)
    L, R := 0, 0
    for i := 0; i < n; i++ {
        fmt.Scanf("%d %d\n",&l,&r)
        L += l
        R += r
    }
    fmt.Println(min(L,n-L)+min(R,n-R))
}

package main

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

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...) }

type intPair struct {
	a int64
	b int64
}

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

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

func main() {
	defer writer.Flush()
	var n int
	scanf("%d\n", &n)
	left := map[int]bool{}
	right := map[int]bool{}

	for i :=0;i<n;i++ {
		var li,ri int
		scanf("%d %d\n", &li, &ri)
		if(li == 1) {
			left[i] = true
		}
		if(ri == 1) {
			right[i] = true
		}
	}
	ans := min(max(len(left), n-len(left)), max(len(right), n-len(right)))
	printf("%d\n", ans)
}

package main

import (
	"fmt"
)

func main() {
	var n, time, left, right, leftZeros, leftOnes, rightZeros, rightOnes uint8

	fmt.Scan(&n)

	for i := 0; i < int(n); i++ {
		fmt.Scan(&left)
		fmt.Scan(&right)

		switch left {
		case 1:
			leftOnes++
			break
		default:
			leftZeros++
		}

		switch right {
		case 1:
			rightOnes++
			break
		default:
			rightZeros++
		}
	}

	if leftZeros > leftOnes {
		time = leftOnes
	} else {
		time = leftZeros
	}

	if rightZeros > rightOnes {
		time += rightOnes
	} else {
		time += rightZeros
	}

	fmt.Println(time)
}


package main

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

type PairInt struct {
	first, second int
}

func main() {
	scanner.Split(bufio.ScanWords)
	var N = NextInt()
	var M = NextInt()
	var K = NextInt()
	var qr, qc []PairInt
	qr = make([]PairInt, N)
	qc = make([]PairInt, M)

	for i := 0; i < K; i++ {
		var q, rc, color int
		q = NextInt()
		rc = NextInt()
		color = NextInt()
		rc--
		if q == 1 { //row
			qr[rc].first = color
			qr[rc].second = i + 1
		} else {
			qc[rc].first = color
			qc[rc].second = i + 1
		}
	}
	for i := 0; i < N; i++ {
		for j := 0; j < M; j++ {
			if qr[i].second < qc[j].second {
				fmt.Print(qc[j].first, " ")
			} else {
				fmt.Print(qr[i].first, " ")
			}
		}
		fmt.Println()
	}
}

//---------------------------------template--------------------------------

var scanner = bufio.NewScanner(os.Stdin)

var writer = bufio.NewWriter(os.Stdout)

func NextToken() string {
	scanner.Scan()
	return scanner.Text()
}

func NextInt() int {
	val, err := strconv.Atoi(NextToken())
	if err != nil {
		panic(err.Error())
	}
	return val
}

func PrintInt(x int) {
	writer.WriteString(strconv.Itoa(x))
}
func PrintString(x string) {
	writer.WriteString(x)
}

package main

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

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

    var n, m, k int;
    fmt.Fscan(in, &n, &m, &k)

    rows := make([]struct { time int; color int }, n)
    columns := make([]struct { time int; color int }, m)

    for i := 1; i <= k; i++ {
        var oper, index, color int
        fmt.Fscan(in, &oper, &index, &color)

        switch oper {
        case 1:
            rows[index-1].time = i
            rows[index-1].color = color
        case 2:
            columns[index-1].time = i
            columns[index-1].color = color
        }
    }

    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            if rows[i].time > columns[j].time {
                fmt.Fprint(out, rows[i].color)
            } else {
                fmt.Fprint(out, columns[j].color)
            }

            if (j < m - 1) {
                fmt.Fprint(out, " ")
            } else {
                fmt.Fprint(out, "\n")
            }
        }
    }

    out.Flush()
}

package main

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

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

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

func main() {
    stdin := bufio.NewReader(os.Stdin)
    var n, m, k int
    fmt.Fscan(stdin, &n, &m, &k)

    rowColor := make([]int, n)
    rowLast := make([]int, n)
    colColor := make([]int, m)
    colLast := make([]int, m)

    for i := 0; i < k; i++ {
      var t, x, c int
      fmt.Fscan(stdin, &t, &x, &c)
      x--
      if t == 1 {  // rows
        rowColor[x] = c
        rowLast[x] = i+1
      } else {  // cols
        colColor[x] = c
        colLast[x] = i+1
      }
    }

    for i := 0; i < n; i++ {
      for j := 0; j < m; j++ {
        if rowLast[i] > colLast[j] {
          fmt.Print(" ", rowColor[i])
        } else {
          fmt.Print(" ", colColor[j])
        }
      }
      fmt.Println()
    }
}

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

func init() {
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer = bufio.NewWriter(os.Stdout)
}

func nextToken() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	v, _ := strconv.Atoi(nextToken())
	return v
}

func nextInt64() int64 {
	v, _ := strconv.ParseInt(nextToken(), 10, 64)
	return v
}

func nextFloat() float64 {
	v, _ := strconv.ParseFloat(nextToken(), 64)
	return v
}

func printInt(x int) {
	writer.WriteString(strconv.Itoa(x))
}

func printInt64(x int64) {
	writer.WriteString(strconv.FormatInt(x, 10))
}

func printString(x string) {
	writer.WriteString(x)
}

type Pair struct {
	t, col int
}

func main() {
	n, m, k := nextInt(), nextInt(), nextInt()
	var r, c [5100]Pair
	for i := 1; i <= k; i++ {
		t, q, w := nextInt(), nextInt(), nextInt()
		q--
		if t == 1 {
			r[q].col = w
			r[q].t = i
		} else {
			c[q].col = w
			c[q].t = i
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if r[i].t < c[j].t {
				printInt(c[j].col)
			} else {
				printInt(r[i].col)
			}
			printString(" ")
		}
		printString("\n")
	}

	writer.Flush()
}

package main

import (
"fmt"
"bufio"
"os"
"strconv"
)
var in = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)
func NextToken() string {
	in.Scan()
	return in.Text()
}
func nextInt() int {
	val, err := strconv.Atoi(NextToken())
	if err != nil {
		panic(err.Error())
	}
	return val
}

type pair struct {
    color, level int
}
func main() {
    in.Split(bufio.ScanWords)
    // p := bufio.NewWriter(os.Stdout)

    n := 0
    m := 0
    n = nextInt()
    m = nextInt()
    k := nextInt()

    rows := make([]pair, n + 1)
    cols := make([]pair, m + 1)

    for i:=0; i<k; i++ {
        a := nextInt()
        b := nextInt()
        c := nextInt()
        if a == 1 {
            rows[b] = pair{c, i + 1}
        } else {
            cols[b] = pair{c, i + 1}
        }
    }

    for i:=1; i<=n; i++ {
        for j:=1; j<=m; j++ {
            k := 0
            if rows[i].level > cols[j].level {
                k = rows[i].color
            } else {
                k = cols[j].color
            }
            fmt.Fprintf(out, "%d ", k)
        }
        fmt.Fprintf(out, "\n")
    }

    out.Flush()
}

package main

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

var (
	sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr *bufio.Writer  = bufio.NewWriter(os.Stdout)
)

func readInt() int {
	sc.Scan()
	ans, _ := strconv.Atoi(sc.Text())
	return ans
}

func printInts(ints ...int) {
	for _, v := range ints {
		wr.WriteString(strconv.Itoa(v))
		wr.WriteByte(' ')
	}
}

func println() {
	wr.WriteByte('\n')
}

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)

	var n, m, k int = readInt(), readInt(), readInt()
	n++
	m++
	rs := make([]int, n)
	rt := make([]int, n)
	cs := make([]int, m)
	ct := make([]int, m)
	var t, rc, a int
	for i := 1; i <= k; i++ {
		t, rc, a = readInt(), readInt(), readInt()
		if t == 1 {
			rs[rc] = a
			rt[rc] = i
		} else {
			cs[rc] = a
			ct[rc] = i
		}
	}

	for i := 1; i < n; i++ {
		for j := 1; j < m; j++ {
			var v int
			if rt[i] == ct[j] {
				v = 0
			} else if rt[i] > ct[j] {
				v = rs[i]
			} else {
				v = cs[j]
			}
			printInts(v)
		}
		println()
	}
}

package main

import (
	"fmt"
)

type ord struct {
	v, o int
}

func main() {
	var n, m, k int
	fmt.Scan(&n, &m, &k)
	mm := make([][]int, n+1)
	m0 := make([][]int, n+1)
	for i := 1; i <= n; i++ {
		mm[i] = make([]int, m+1)
		m0[i] = make([]int, m+1)
	}

	rs := make([]ord, n+1)
	cs := make([]ord, m+1)
	var t, rc, a int
	for i := 0; i < k; i++ {
		fmt.Scan(&t, &rc, &a)
		if t == 1 {
			rs[rc] = ord{a, i}
		} else {
			cs[rc] = ord{a, i}
		}
	}

	rsize := 0
	for i, or := range rs {
		if or.v == 0 && or.o == 0 {
			continue
		}
		for j := 1; j <= m; j++ {
			mm[i][j] = or.v
			m0[i][j] = or.o
		}
		rsize++
	}
	if rsize != n {

		for j, or := range cs {
			if or.v == 0 && or.o == 0 {
				continue
			}
			for i := 1; i <= n; i++ {
				if or.o >= m0[i][j] {
					mm[i][j] = or.v
				}
			}
		}
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			fmt.Printf("%d ", mm[i][j])
		}
		fmt.Println()
	}
}

package main

import (
	"fmt"
)

type ord struct {
	v, o int
}

func main() {
	var n, m, k int
	fmt.Scan(&n, &m, &k)
	mm := make([][]int, n+1)
	m0 := make([][]int, n+1)
	for i := 1; i <= n; i++ {
		mm[i] = make([]int, m+1)
		m0[i] = make([]int, m+1)
	}

	rs := make([]ord, n+1)
	cs := make([]ord, m+1)
	var t, rc, a int
	for i := 0; i < k; i++ {
		fmt.Scan(&t, &rc, &a)
		if t == 1 {
			rs[rc] = ord{a, i}
		} else {
			cs[rc] = ord{a, i}
		}
	}

	for i, or := range rs {
		if or.v == 0 && or.o == 0 {
			continue
		}
		for j := 1; j <= m; j++ {
			mm[i][j] = or.v
			m0[i][j] = or.o
		}
	}
	for j, or := range cs {
		if or.v == 0 && or.o == 0 {
			continue
		}
		for i := 1; i <= n; i++ {
			if or.o > m0[i][j] {
				mm[i][j] = or.v
			}
		}
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			fmt.Printf("%d ", mm[i][j])
		}
		fmt.Println()
	}
}

package main

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

type PairInt struct {
	first, second int
}

func main() {
	scanner.Split(bufio.ScanWords)
	var N = NextInt()
	var M = NextInt()
	var K = NextInt()
	var qr, qc []PairInt
	qr = make([]PairInt, N)
	qc = make([]PairInt, M)

	for i := 0; i < K; i++ {
		var q, rc, color int
		q = NextInt()
		rc = NextInt()
		color = NextInt()
		rc--
		if q == 1 { //row
			qr[rc].first = color
			qr[rc].second = i
		} else {
			qc[rc].first = color
			qc[rc].second = i
		}
	}
	for i := 0; i < N; i++ {
		for j := 0; j < M; j++ {
			if qr[i].second < qc[j].second {
				fmt.Print(qc[j].first, " ")
			} else {
				fmt.Print(qr[i].first, " ")
			}
		}
		fmt.Println()
	}
}

//---------------------------------template--------------------------------

var scanner = bufio.NewScanner(os.Stdin)

var writer = bufio.NewWriter(os.Stdout)

func NextToken() string {
	scanner.Scan()
	return scanner.Text()
}

func NextInt() int {
	val, err := strconv.Atoi(NextToken())
	if err != nil {
		panic(err.Error())
	}
	return val
}

func PrintInt(x int) {
	writer.WriteString(strconv.Itoa(x))
}
func PrintString(x string) {
	writer.WriteString(x)
}