package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var x int
		var w string
		fmt.Fscan(in, &w)
		fmt.Fscan(in, &x)
		s := make([]byte, len(w))
		for j := 0; j < len(w); j++ {
			if w[j] == '0' {
				if j-x >= 0 {
					s[j-x] = '0'
				}
				if j+x < len(w) {
					s[j+x] = '0'
				}
			}
		}
		for j := 0; j < len(w); j++ {
			if s[j] != '0' {
				s[j] = '1'
			}
		}
		possible := true
		for j := 0; j < len(w); j++ {
			if w[j] == '1' {
				if j-x >= 0 && s[j-x] == '1' {
					continue
				}
				if j+x < len(w) && s[j+x] == '1' {
					continue
				}
				possible = false
			}
		}
		if possible {
			fmt.Println(string(s))
		} else {
			fmt.Println(-1)
		}
	}
}

package main

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

func convsw(x int, s string) string {
	n := len(s)
	w := make([]byte, n)

	for i := range s {
		if s[i] == '0' {
			if i - x >= 0 {
				w[i-x] = '0'
			}
			if i + x < n {
				w[i+x] = '0'
			}
		}
	}

	for i := range w {
		if w[i] != '0' {
			w[i] = '1'
		}
	}

	return string(w)
}

func convws(x int, w string) string {
	n := len(w)
	s := make([]byte, n)

	for i := range w {
		if w[i] == '1' {
			if i - x >= 0{
				s[i-x] = '1'
			}

			if i + x < n {
				s[i+x] = '1'
			}
		}
	}

	for i := range s {
		if s[i] != '1' {
			s[i] = '0'
		}
	}

	return string(s)
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanWords)

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

	ins := func() string {
		sc.Scan()
		return sc.Text()
	}

	for t := ini(); t > 0; t-- {
		s := ins()
		x := ini()

		w := convsw(x, s)
		//fmt.Println(w)
		s1 := convws(x, w)
		//fmt.Println(s1)

		if s == s1 {
			fmt.Println(w)
		} else {
			fmt.Println(-1)
			//fmt.Println(s1)
		}
	}
}

/*
URL:
https://codeforces.com/contest/1400/problem/C
*/

package main

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

var (
	t int

	S []rune
	x int
)

func main() {
	t = readi()
	for tc := 0; tc < t; tc++ {
		S = ReadRuneSlice()
		x = readi()

		solve()
	}
}

func solve() {
	n := len(S)
	T := make([]rune, n)
	for i := 0; i < n; i++ {
		T[i] = '!'
	}

	// 両方ともfalseのケース
	for i := 0; i < n; i++ {
		left, right := false, false
		if i-x >= 0 {
			left = true
		}
		if i+x < n {
			right = true
		}

		if !left && !right && S[i] == '1' {
			fmt.Println(-1)
			return
		}
	}

	// 結果が0のところから確定させる
	for i := 0; i < n; i++ {
		if S[i] == '0' {
			if i-x >= 0 {
				T[i-x] = '0'
			}
			if i+x < n {
				T[i+x] = '0'
			}
		}
	}

	// 単方向の1から確定させる、矛盾があたら-1
	for i := 0; i < n; i++ {
		if S[i] == '1' {
			left, right := false, false
			if i-x >= 0 {
				left = true
			}
			if i+x < n {
				right = true
			}

			if left && right {
				continue
			}

			if left {
				if T[i-x] == '0' {
					fmt.Println(-1)
					return
				} else {
					T[i-x] = '1'
				}
			}

			if right {
				if T[i+x] == '0' {
					fmt.Println(-1)
					return
				} else {
					T[i+x] = '1'
				}
			}
		}
	}

	// PrintfDebug("%v\n", string(T))

	// 双方向の1をみる、両方0なら矛盾
	for i := 0; i < n; i++ {
		if S[i] == '1' {
			left, right := false, false
			if i-x >= 0 {
				left = true
			}
			if i+x < n {
				right = true
			}

			if left && right {
				if T[i-x] == '0' && T[i+x] == '0' {
					fmt.Println(-1)
					return
				}
			}
		}
	}

	// 残った部分は1
	for i := 0; i < n; i++ {
		if T[i] != '0' && T[i] != '1' {
			T[i] = '1'
		}
	}

	fmt.Println(string(T))
}

func output(S []rune) {
	n := len(S)
	T := make([]rune, n)
	for i := 0; i < n; i++ {
		T[i] = '!'
	}

	// 結果が0のところから確定させる
	for i := 0; i < n; i++ {
		if S[i] == '0' {
			if i-x >= 0 {
				T[i-x] = '0'
			}
			if i+x < n {
				T[i+x] = '0'
			}
		}
	}

	// 単方向の1から確定させる、矛盾があたら-1
	for i := 0; i < n; i++ {
		if S[i] == '1' {
			left, right := false, false
			if i-x >= 0 {
				left = true
			}
			if i+x < n {
				right = true
			}

			if left && right {
				continue
			}

			if left {
				if T[i-x] == '0' {
					fmt.Println(-1)
					return
				} else {
					T[i-x] = '1'
				}
			}

			if right {
				if T[i+x] == '0' {
					fmt.Println(-1)
					return
				} else {
					T[i+x] = '1'
				}
			}
		}
	}

	// PrintfDebug("%v\n", string(T))

	// 双方向の1をみる、両方0なら矛盾
	for i := 0; i < n; i++ {
		if S[i] == '1' {
			left, right := false, false
			if i-x >= 0 {
				left = true
			}
			if i+x < n {
				right = true
			}

			if left && right {
				if T[i-x] == '0' && T[i+x] == '0' {
					fmt.Println(-1)
					return
				}
			}
		}
	}

	// 残った部分は1
	for i := 0; i < n; i++ {
		if T[i] != '0' && T[i] != '1' {
			T[i] = '1'
		}
	}

	fmt.Println(string(T))
}

/*******************************************************************/

/********** common constants **********/

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(readInt64())
}
func readi2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func readi3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func readi4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return readInt64()
}
func readll2() (int64, int64) {
	return readInt64(), readInt64()
}
func readll3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Output ***********/

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

package main

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

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

	var T, x int
	var t []byte
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &t, &x)
		n := len(t)
		s := make([]byte, n)
		for i, b := range t {
			if b == '0' {
				if i >= x {
					s[i-x] = '0'
				}
				if i+x < n {
					s[i+x] = '0'
				}
			}
		}
		for i, b := range s {
			if b == 0 {
				s[i] = '1'
			}
		}
		for i, b := range t {
			if b == '1' && !(i >= x && s[i-x] == '1' || i+x < n && s[i+x] == '1') {
				Fprintln(out, -1)
				continue o
			}
		}
		Fprintln(out, string(s))
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var s string
		fmt.Fscan(reader, &s)

		var x int
		fmt.Fscan(reader, &x)

		w := make([]string, len(s))
		for j := 0; j < len(s); j++ {
			w[j] = "1"
		}

		for j := 0; j < len(s); j++ {
			if s[j] == '0' {
				if j-x >= 0 {
					w[j-x] = "0"
				}

				if j+x < len(s) {
					w[j+x] = "0"
				}
			}
		}

		for j := 0; j < len(s); j++ {
			if s[j] == '1' {
				at_least_one := false

				if (j-x) >= 0 && w[j-x] == "1" {
					at_least_one = true
				}

				if (j+x < len(s)) && w[j+x] == "1" {
					at_least_one = true
				}

				if !at_least_one {
					w = nil
					break
				}
			}
		}

		if w == nil {
			fmt.Println("-1")
		} else {
			fmt.Println(strings.Join(w, ""))
		}
	}
}

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

		s, _ := reader.ReadString('\n')
		x := readNum(reader)

		ok, w := solve(s, x)

		if !ok {
			buf.WriteString("-1")
		} else {
			buf.WriteString(w)
		}
		buf.WriteByte('\n')
	}
	fmt.Print(buf.String())
}

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 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 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 solve(s string, x int) (bool, string) {
	w := make([]byte, len(s))
	var n int
	for i := 0; i < len(s); i++ {
		if s[i] != '0' && s[i] != '1' {
			break
		}
		w[i] = '1'
		n++
	}
	w = w[:n]
	for i := 0; i < n; i++ {
		if s[i] == '0' {
			if i-x >= 0 {
				w[i-x] = '0'
			}
			if i+x < n {
				w[i+x] = '0'
			}
		}
	}

	for i := 0; i < n; i++ {
		if s[i] == '1' {
			if i-x >= 0 && w[i-x] == '1' {
				continue
			}
			if i+x < n && w[i+x] == '1' {
				continue
			}
			return false, ""
		} else {
			// s[i] == '0'
			if i-x >= 0 && w[i-x] == '1' {
				return false, ""
			}
			if i+x < n && w[i+x] == '1' {
				return false, ""
			}
		}
	}
	return true, string(w)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		ss, x := io.Next(), io.NextInt()
		n := len(ss)

		s := make([]byte, n*3)
		copy(s[n:], ss)
		off := n

		ok := true
		ans := make([]byte, 3*n)
		for i := off; i < off+x; i++ {
			if i+x < off+n || s[i] == '0' {
				ans[i+x] = s[i]
			} else {
				ok = false
			}
		}
		for i := off + n - x; i < off+n; i++ {
			if (i-x < off && s[i] == '0') || (i-x >= off && (ans[i-x] == s[i] || ans[i-x] == 0)) {
				ans[i-x] = s[i]
			} else {
				ok = false
			}
		}
		for i := off + x; i < off+n-x; i++ {
			if s[i] == '0' {
				if (ans[i-x] == 0 || ans[i-x] == '0') && (ans[i+x] == 0 || ans[i+x] == '0') {
					ans[i-x] = '0'
					ans[i+x] = '0'
				} else {
					ok = false
				}
			} else if (i-x >= off && ans[i-x] == 0) || ans[i-x] == '1' {
				ans[i-x] = '1'
			} else if (i+x < off+n && ans[i+x] == 0) || ans[i+x] == '1' {
				ans[i+x] = '1'
			} else {
				ok = false
			}
		}
		ans = ans[off : off+n]
		for i := range ans {
			if ans[i] == 0 {
				ans[i] = '0'
			}
		}

		if ok {
			io.Println(string(ans))
		} else {
			io.Println(-1)
		}
	}
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		ss, x := io.Next(), io.NextInt()
		n := len(ss)

		s := make([]byte, n*3)
		copy(s[n:], ss)
		off := n

		ok := true
		ans := make([]byte, 3*n)
		copy(ans[off+x:off+2*x], s[off:off+x])
		for i := off + n - x; i < off+n; i++ {
			if ans[i-x] == 0 || ans[i-x] == s[i] {
				ans[i-x] = s[i]
			} else {
				ok = false
			}
		}
		for i := off + x; i < off+n-x; i++ {
			if s[i] == '0' {
				if (ans[i-x] == 0 || ans[i-x] == '0') && (ans[i+x] == 0 || ans[i+x] == '0') {
					ans[i-x] = '0'
					ans[i+x] = '0'
				} else {
					ok = false
				}
			} else if ans[i-x] == 0 || ans[i-x] == '1' {
				ans[i-x] = '1'
			} else if ans[i+x] == 0 || ans[i+x] == '1' {
				ans[i+x] = '1'
			} else {
				ok = false
			}
		}
		ans = ans[off : off+n]
		for i := range ans {
			if ans[i] == 0 {
				ans[i] = '0'
			}
		}

		if ok {
			io.Println(string(ans))
		} else {
			io.Println(-1)
		}
	}
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		ss, x := io.Next(), io.NextInt()
		n := len(ss)

		s := make([]byte, n*3)
		copy(s[n:], ss)
		off := n

		ok := true
		ans := make([]byte, 3*n)
		copy(ans[off+x:off+2*x], s[off:off+x])
		for i := off + n - x; i < off+n; i++ {
			if ans[i-x] == 0 || ans[i-x] == s[i] {
				ans[i-x] = s[i]
			} else {
				ok = false
			}
		}
		for i := off + x; i < off+n-x; i++ {
			if s[i] == '0' {
				if (ans[i-x] == 0 || ans[i-x] == '0') && (ans[i+x] == 0 || ans[i+x] == '0') {
					ans[i-x] = '0'
					ans[i+x] = '0'
				} else {
					ok = false
				}
			} else if (i-x >= off && ans[i-x] == 0) || ans[i-x] == '1' {
				ans[i-x] = '1'
			} else if (i+x < off+n && ans[i+x] == 0) || ans[i+x] == '1' {
				ans[i+x] = '1'
			} else {
				ok = false
			}
		}
		ans = ans[off : off+n]
		for i := range ans {
			if ans[i] == 0 {
				ans[i] = '0'
			}
		}

		if ok {
			io.Println(string(ans))
		} else {
			io.Println(-1)
		}
	}
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		ss, x := io.Next(), io.NextInt()
		n := len(ss)

		s := make([]byte, n*3)
		copy(s[n:], ss)
		off := n

		ok := true
		ans := make([]byte, 3*n)
		copy(ans[off+x:off+2*x], s[off:off+x])
		for i := off + n - x; i < off+n; i++ {
			if (i-x >= off && ans[i-x] == 0) || ans[i-x] == s[i] {
				ans[i-x] = s[i]
			} else {
				ok = false
			}
		}
		for i := off + x; i < off+n-x; i++ {
			if s[i] == '0' {
				if (ans[i-x] == 0 || ans[i-x] == '0') && (ans[i+x] == 0 || ans[i+x] == '0') {
					ans[i-x] = '0'
					ans[i+x] = '0'
				} else {
					ok = false
				}
			} else if (i-x >= off && ans[i-x] == 0) || ans[i-x] == '1' {
				ans[i-x] = '1'
			} else if (i+x < off+n && ans[i+x] == 0) || ans[i+x] == '1' {
				ans[i+x] = '1'
			} else {
				ok = false
			}
		}
		ans = ans[off : off+n]
		for i := range ans {
			if ans[i] == 0 {
				ans[i] = '0'
			}
		}

		if ok {
			io.Println(string(ans))
		} else {
			io.Println(-1)
		}
	}
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

func convsw(x int, s string) string {
	n := len(s)
	w := make([]byte, n)

	for i := range s {
		if s[i] == '0' {
			if i - x >= 0 {
				w[i-x] = '0'
			}
			if i + x < n {
				w[i+x] = '0'
			}
		}
	}

	for i := range w {
		if w[i] != '0' {
			w[i] = '1'
		}
	}

	return string(w)
}

func convws(x int, w string) string {
	n := len(w)
	s := make([]byte, n)

	for i := range w {
		if w[i] == '1' {
			if i - x >= 0{
				s[i-x] = '1'
			}

			if i + x < n {
				s[i+x] = '1'
			}
		}
	}

	for i := range s {
		if s[i] != '1' {
			s[i] = '0'
		}
	}

	return string(s)
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanLines)

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

	ins := func() string {
		sc.Scan()
		return sc.Text()
	}

	for t := ini(); t > 0; t-- {
		s := ins()
		x := ini()

		w := convws(x, s)
		s1 := convsw(x, w)

		if s == s1 {
			fmt.Println(w)
		} else {
			fmt.Println(-1)
		}
	}
}

/*
URL:
https://codeforces.com/contest/1400/problem/C
*/

package main

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

var (
	t int

	S []rune
	x int
)

func main() {
	t = readi()
	for tc := 0; tc < t; tc++ {
		S = ReadRuneSlice()
		x = readi()

		solve()
	}
}

func solve() {
	n := len(S)
	T := make([]rune, n)
	for i := 0; i < n; i++ {
		T[i] = '!'
	}

	for i := 0; i < n; i++ {
		if S[i] == '0' {
			if i-x >= 0 {
				T[i-x] = '0'
			}
			if i+x < n {
				T[i+x] = '0'
			}
		}
	}

	for i := 0; i < n; i++ {
		if S[i] == '1' {
			left, right := false, false
			if i-x >= 0 {
				left = true
			}
			if i+x < n {
				right = true
			}

			if left && right {
				continue
			}

			if left {
				if T[i-x] == '0' {
					fmt.Println(-1)
					return
				} else {
					T[i-x] = '1'
				}
			}

			if right {
				if T[i+x] == '0' {
					fmt.Println(-1)
					return
				} else {
					T[i+x] = '1'
				}
			}
		}
	}

	for i := 0; i < n; i++ {
		if T[i] != '0' && T[i] != '1' {
			T[i] = '1'
		}
	}

	fmt.Println(string(T))
}

/*******************************************************************/

/********** common constants **********/

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(readInt64())
}
func readi2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func readi3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func readi4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return readInt64()
}
func readll2() (int64, int64) {
	return readInt64(), readInt64()
}
func readll3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Output ***********/

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

/*
URL:
https://codeforces.com/contest/1400/problem/C
*/

package main

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

var (
	t int

	S []rune
	x int
)

func main() {
	t = readi()
	for tc := 0; tc < t; tc++ {
		S = ReadRuneSlice()
		x = readi()

		solve()
	}
}

func solve() {
	n := len(S)
	T := make([]rune, n)
	for i := 0; i < n; i++ {
		T[i] = '!'
	}

	// 結果が0のところから確定させる
	for i := 0; i < n; i++ {
		if S[i] == '0' {
			if i-x >= 0 {
				T[i-x] = '0'
			}
			if i+x < n {
				T[i+x] = '0'
			}
		}
	}

	// 単方向の1から確定させる、矛盾があたら-1
	for i := 0; i < n; i++ {
		if S[i] == '1' {
			left, right := false, false
			if i-x >= 0 {
				left = true
			}
			if i+x < n {
				right = true
			}

			if left && right {
				continue
			}

			if left {
				if T[i-x] == '0' {
					fmt.Println(-1)
					return
				} else {
					T[i-x] = '1'
				}
			}

			if right {
				if T[i+x] == '0' {
					fmt.Println(-1)
					return
				} else {
					T[i+x] = '1'
				}
			}
		}
	}

	// PrintfDebug("%v\n", string(T))

	// 双方向の1をみる、両方0なら矛盾
	for i := 0; i < n; i++ {
		if S[i] == '1' {
			left, right := false, false
			if i-x >= 0 {
				left = true
			}
			if i+x < n {
				right = true
			}

			if left && right {
				if T[i-x] == '0' && T[i+x] == '0' {
					fmt.Println(-1)
					return
				}
			}
		}
	}

	// 残った部分は1
	for i := 0; i < n; i++ {
		if T[i] != '0' && T[i] != '1' {
			T[i] = '1'
		}
	}

	fmt.Println(string(T))
}

/*******************************************************************/

/********** common constants **********/

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(readInt64())
}
func readi2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func readi3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func readi4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return readInt64()
}
func readll2() (int64, int64) {
	return readInt64(), readInt64()
}
func readll3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Output ***********/

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var s string
		fmt.Fscan(reader, &s)

		var x int
		fmt.Fscan(reader, &x)

		check := make([]string, len(s))
		for j := 0; j < len(s); j++ {
			check[j] = "1"
		}

		for j := 0; j < len(s); j++ {
			if s[j] == '0' {
				if j-x >= 0 {
					check[j-x] = "0"
				}

				if j+x < len(s) {
					check[j+x] = "0"
				}
			}
		}

		for j := 0; j < len(s); j++ {
			if s[j] == '1' {
				if (j < x) && (j+x < len(s)) && check[j+x] == "0" {
					check = nil
					break
				}

				if (j >= len(s)-x) && (j-x >= 0) && check[j-x] == "0" {
					check = nil
					break
				}

				if (j-x >= 0) && (j+x < len(s)) && check[j-x] == "0" && check[j+x] == "0" {
					check = nil
					break
				}
			}
		}

		if check == nil {
			fmt.Println("-1")
		} else {
			fmt.Println(strings.Join(check, ""))
		}
	}
}


package main

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

func Sol1133E(reader io.Reader, writer io.Writer) {
	max := func(a, b int) int {
		if a >= b {
			return a
		}
		return b
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	const maxTeamDelta = 5

	var n, k int
	Fscan(in, &n, &k)
	arr := make([]int, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &arr[i])
	}
	sort.Ints(arr)

	deltaPos := make([][maxTeamDelta + 1]int, n+1)
	for j := 0; j <= maxTeamDelta; j++ {
		deltaPos[1][j] = 1
	}
	for i := 2; i <= n; i++ {
		for j := 0; j <= maxTeamDelta; j++ {
			deltaPos[i][j] = i
		}
		if delta := arr[i] - arr[i-1]; delta <= maxTeamDelta {
			copy(deltaPos[i][delta:], deltaPos[i-1][:maxTeamDelta+1-delta])
		}
	}

	var dp [2][5001]int
	for j := 1; j <= n; j++ {
		dp[0][j] = max(dp[0][j-1], j-deltaPos[j][maxTeamDelta]+1)
	}
	row := 0
	for i := 2; i <= k; i++ {
		row ^= 1
		for j := i; j <= n; j++ {
			posL := deltaPos[j][maxTeamDelta]
			// max(not count student j, count student j)
			dp[row][j] = max(dp[row][j-1], dp[row^1][posL-1]+j-posL+1)
		}
	}
	Fprintln(out, max(dp[row][n], dp[row^1][n]))
}

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

package main

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

type SA []int

func (s SA) Len() int {
	return len(s)
}

func (s SA) Swap(a, b int) {
	tmp := s[a]
	s[a] = s[b]
	s[b] = tmp
}
func (s SA) Less(i, j int) bool {
	if s[i] < s[j] {
		return true
	}
	return false
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n, k int
	fmt.Fscanf(buf, "%d %d\n", &n, &k)
	mat := make(SA, n)

	for i := 0; i < n; i++ {

		fmt.Fscanf(buf, "%d", &mat[i])
	}
	fmt.Fscanf(buf, "\n")
	//for i:=1;i <=k;i++{
	//	dp[i]=1
	//}
	sort.Sort(mat)
	ans := 1

	var f int
	var dp [5010][5010]int
	dp[0][1] = 1
	dp[10][10]=0
	for i := 1; i < n; i++ {
		for f <= i && mat[i]-mat[f] > 5 {
			f++
		}
		if f == 0 {
			dp[i][1] = i+1
	//		fmt.Printf("%v\n", dp[i])
			continue
		}
		for j := k - 1; j >= 0; j-- {

			if j > 0 && dp[f-1][j] == 0 {
				continue
			}
			if dp[i-1][j+1] < dp[f-1][j]+i-f+1 {
				dp[i][j+1] = dp[f-1][j] + i - f + 1
			} else {
				dp[i][j+1] = dp[i-1][j+1]
			}
		}

	//	fmt.Printf("%v\n", dp[i])
	}
	for i := 1; i <= k; i++ {
		if dp[n-1][i] > ans {
			ans = dp[n-1][i]
		}
	}
	fmt.Printf("%d\n", ans)
}

/**
0 0
0 1
3
UDD
 */

package main

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

func Sol1133E(reader io.Reader, writer io.Writer) {
	max := func(a, b int) int {
		if a >= b {
			return a
		}
		return b
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	const maxTeamDelta = 5

	var n, k int
	Fscan(in, &n, &k)
	arr := make([]int, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &arr[i])
	}
	sort.Ints(arr)

	deltaPos := make([][maxTeamDelta + 1]int, n+1)
	for j := 0; j <= maxTeamDelta; j++ {
		deltaPos[1][j] = 1
	}
	for i := 2; i <= n; i++ {
		for j := 0; j <= maxTeamDelta; j++ {
			deltaPos[i][j] = i
		}
		if delta := arr[i] - arr[i-1]; delta <= maxTeamDelta {
			copy(deltaPos[i][delta:], deltaPos[i-1][:maxTeamDelta+1-delta])
		}
	}

	var dp [2][5001]int
	for j := 1; j <= n; j++ {
		dp[0][j] = max(dp[0][j-1], j-deltaPos[j][maxTeamDelta]+1)
	}
	row := 0
	for i := 2; i <= k; i++ {
		row ^= 1
		for j := i; j <= n; j++ {
			posL := deltaPos[j][maxTeamDelta]
			// max(not count student j, count student j)
			dp[row][j] = max(dp[row][j-1], dp[row^1][posL-1]+j-posL+1)
		}
	}
	Fprintln(out, dp[row][n])
}

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


/*********************************************************************************
*     File Name           :     B.go
*     Created By          :     YIMMON, yimmon.zhuang@gmail.com
*     Creation Date       :     [2014-03-29 22:34]
*     Last Modified       :     [2014-03-29 22:52]
*     Description         :
**********************************************************************************/

package main

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

func Solve(str []byte) int {
    ans := 0
    var i, j int
    for i = 0; i < len(str); i++ {
        if str[i] != '.' {
            break
        }
    }
    if i >= len(str) {
        ans = len(str)
    } else if str[i] == 'L' {
        if i+1 < len(str) {
            ans = Solve(str[i+1:])
        }
    } else {
        ans = i
        for j = i; j < len(str); j++ {
            if str[j] == 'L' {
                break
            }
        }
        if j < len(str) && (j-i+1)&1 == 1 {
            ans++
        }
        if j+1 < len(str) {
            ans += Solve(str[j+1:])
        }
    }
    return ans
}

func main() {
    scanner.Split(bufio.ScanWords)

    scanner.NextInt()
    str := scanner.Next()
    fmt.Println(Solve([]byte(str)))
}

type Scanner struct {
    *bufio.Scanner
}

var scanner = Scanner{bufio.NewScanner(os.Stdin)}

func (self *Scanner) Next() string {
    if !self.Scan() {
        panic(self.Err())
    }
    return self.Text()
}

func (self *Scanner) NextInt() int {
    x, err := strconv.Atoi(self.Next())
    if err != nil {
        panic(err)
    }
    return x
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	_ = n

	s := next()

	i, count := 0, 0

	for i<len(s) && s[i]=='.' {
		i++
	}

	if i==len(s) {
		println(len(s))
		return
	}

	lastPush := i
	i++

	if s[lastPush]=='R' {
		count += lastPush
	}

	for i<len(s) {
		if s[i] != '.' {
			if s[i] == 'R' {
				count += i - lastPush - 1
			} else {
				if (i-lastPush)%2 == 0 {
					count++
				}
			}
			lastPush = i
		}
		i++
	}

	if s[lastPush]=='L' {
		count += len(s) - lastPush - 1
	}

	println(count)
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

import "fmt"

func main() {
    var n int
    var s string
    fmt.Scan(&n)
    fmt.Scan(&s)
    a := make([]int,n)
    for i := 0; i < n; i++ {
        if s[i] == 'L' {
            a[i] = 1
            for j := i-1; (j >= 0) && (s[j] == '.'); j-- {
                if a[j] == (i-j) {
                    a[j] = 0
                    break
                }
                a[j] = i-j
            }
        } else if s[i] == 'R' {
            a[i] = 1
            for j := i+1; (j < n) && (s[j] == '.'); j++ {
                a[j] = j-i
            }
        }
    }
    ans := 0
    for i := 0; i < n; i++ {
        if a[i] == 0 { ans++ }
    }
    fmt.Println(ans)
}

package main

import "fmt"

func main() {
    var n int					// variabel n dengan jenis int
    var s string				// variabel s dengan jenis string
    fmt.Scan(&n)				// mengambil input
    fmt.Scan(&s)				// mengambil input
    a := make([]int,n)			// membuat variabel a yang diisi slice of int ukuran n
    for i := 0; i < n; i++ {   // looping
        if s[i] == 'L' {		// jika s[i] sama dengan 'L'
            a[i] = 1			// a[i] sama dengan 1
            for j := i-1; (j >= 0) && (s[j] == '.'); j-- { // looping ke 2
                if a[j] == (i-j) {		// jika a[j] sama dengan (i-j)
                    a[j] = 0			//  a[j] sama dengan 0
                    break				// keluar dari fungsi
                }
                a[j] = i-j			//   a[j] sama dengan i-j
            }
        } else if s[i] == 'R' {		// lainnya jika s[i] sama dengan 'R'
            a[i] = 1				//   a[i] sama dengan 1
            for j := i+1; (j < n) && (s[j] == '.'); j++ { // looping ke 3
                a[j] = j-i				// a[j] sama dengan j-i
            }
        }
    }
    ans := 0					// membuat variabel ans dengan isi 0
    for i := 0; i < n; i++ {		// looping ke 4
        if a[i] == 0 { ans++ }		// jika a[i] sama dengan 0, ans ditambah terus
    }
    fmt.Println(ans)			// cetak hasil ans
}

// 405B-mic
package main

import (
    "fmt"
)

func main() {
    var n, k int
    sum := 0
    fall := false
    k = -1

    var s string
    fmt.Scan(&n, &s)

    for i := 0; i < n; i++ {
        switch s[i] {
        case 'R':
            if !fall {
                sum += i - k - 1
            }
            fall = true
            k = i
        case 'L':
            if fall {
                fall = false
                if (i-k)%2 == 0 {
                    sum += 1
                }
            }
            k = i
        }
    }
    if !fall {
        sum += n - k - 1
    }
    fmt.Println(sum)
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	_ = n

	s := next()

	i, count := 0, 0

	for i<len(s) && s[i]=='.' {
		i++
	}

	if i==len(s) {
		println(0)
		return
	}

	lastPush := i
	i++

	if s[lastPush]=='R' {
		count += lastPush
	}

	for i<len(s) {
		if s[i] != '.' {
			if s[i] == 'R' {
				count += i - lastPush - 1
			} else {
				if (i-lastPush)%2 == 0 {
					count++
				}
			}
			lastPush = i
		}
		i++
	}

	if s[lastPush]=='L' {
		count += len(s) - lastPush - 1
	}

	println(count)
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}


package main

import "fmt"

func main() {
	var q, n, x, a, b int64
	fmt.Scan(&q)
	for ; q > 0; q-- {
		fmt.Scan(&n, &x, &a, &b)
		max := b - a
		if max < 0 {
			max = -max
		}
		max += x
		if max > n-1 {
			max = n - 1
		}
		fmt.Println(max)
	}
}

package main

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

/* solution */

func solve() {
	t := readInt()
	for i := 0; i < t; i++ {
		solveOne()
	}
}

func solveOne() {
	n, x, a, b := readInt(), readInt(), readInt(), readInt()
	ans := b - a
	if ans < 0 {
		ans = -ans
	}
	ans += x
	if ans > n-1 {
		ans = n - 1
	}
	printInt(ans)
}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func read() string {
	reader.Scan()
	return reader.Text()
}

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

func print(s string) {
	writer.WriteString(s)
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}

package main

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

func main() {
	var t, n, x, a, b int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &n, &x, &a, &b)
		ans := abs(a - b)
		ans += x
		if ans >= n {
			ans = n - 1
		}
		fmt.Println(ans)
	}
}

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

// A. Two Rival Students
/*
You are the gym teacher in the school.

There are 𝑛 students in the row. And there are two rivalling students among them. The first one is in position 𝑎, the second in position 𝑏. Positions are numbered from 1 to 𝑛 from left to right.

Since they are rivals, you want to maximize the distance between them. If students are in positions 𝑝 and 𝑠 respectively, then distance between them is |𝑝−𝑠|.

You can do the following operation at most 𝑥 times: choose two adjacent (neighbouring) students and swap them.

Calculate the maximum distance between two rivalling students after at most 𝑥 swaps.

Input
The first line contains one integer 𝑡 (1≤𝑡≤100) — the number of test cases.

The only line of each test case contains four integers 𝑛, 𝑥, 𝑎 and 𝑏 (2≤𝑛≤100, 0≤𝑥≤100, 1≤𝑎,𝑏≤𝑛, 𝑎≠𝑏) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

Output
For each test case print one integer — the maximum distance between two rivaling students which you can obtain.
Example
Input
3
5 1 3 2
100 33 100 1
6 0 2 3

Output
2
99
1

Note
In the first test case you can swap students in positions 3 and 4. And then the distance between the rivals is equal to |4−2|=2.

In the second test case you don't have to swap students.

In the third test case you can't swap students.
*/
package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	input1, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(strings.TrimSpace(input1))

	for i := 0; i < t; i++ {
		input2, _ := reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(input2), " ")

		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.Atoi(arr[1])
		a, _ := strconv.Atoi(arr[2])
		b, _ := strconv.Atoi(arr[3])

		if x == 0 {
			fmt.Println(abs(a - b))
		} else if abs(a-b)+x >= (n - 1) {
			fmt.Println(n - 1)
		} else {
			fmt.Println(abs(a-b) + x)
		}
	}
}

func abs(n int) int {
	b := n >> 63
	return (n ^ b) - b
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scanln(&t)

	i := 0
	for i < t {
		var n int
		var x int
		var a int
		var b int
		fmt.Scanln(&n, &x, &a, &b)

		present := 0
		if a > b {
			present = a - b
		} else {
			present = b - a
		}
		max := n - 1
		remain := max - present

		if x >= remain {
			ans := max
			fmt.Println(ans)
		} else {
			ans := x + present
			fmt.Println(ans)
		}

		i++
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	text, _ := reader.ReadString('\n')
	t, _ := strconv.ParseInt(strings.TrimSpace(text), 10, 64)
	for i := int64(0); i < t; i++ {
		text, _ = reader.ReadString('\n')
		parts := strings.Split(text, " ")
		n, _ := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64)
		x, _ := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
		a, _ := strconv.ParseInt(strings.TrimSpace(parts[2]), 10, 64)
		b, _ := strconv.ParseInt(strings.TrimSpace(parts[3]), 10, 64)
		if a > b {
			a, b = b, a
		}
		ret := b - a + min(x, a+n-b-1)
		fmt.Println(ret)
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func readInt() int {
	var ch byte
	var err error
	for {
		ch, err = reader.ReadByte()
		if err != nil {
			return 0
		}
		if unicode.IsDigit(rune(ch)) {
			break
		}
	}
	result := int(ch & 0xf)
	for {
		ch, err = reader.ReadByte()
		if err != nil || !unicode.IsDigit(rune(ch)) {
			return result
		}
		result = result*10 + int(ch&0xf)
	}
}

func main() {
	t := readInt()

	for t > 0 {
		n, x, a, b := readInt(), readInt(), readInt(), readInt()
		fmt.Println(minInt(n-1, absInt(a-b)+x))
		t--
	}
}

func absInt(x int) int {
	if x < 0 {
		return -x
	}

	return x
}

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

	return b
}

package main

import "fmt"

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

func main() {
	var n int
	fmt.Scan(&n)
	ans := make([]int, 0)
	for i := 0; i < n; i++ {
		var num, swap, a, b, ma, mb int
		fmt.Scan(&num, &swap, &a, &b)
		if a > b {
			a, b = b, a
		}
		mb += min(swap, num-b)
		swap -= mb
		ma -= min(swap, a-1)
		b += mb
		a += ma
		// fmt.Println("i", i, "mb", mb, "ma", ma)
		ans = append(ans, b-a)
	}
	for i := range ans {
		fmt.Println(ans[i])
	}
}

package main

import (
	"fmt"
)

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

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

func main() {
	var t int
	fmt.Scanf("%d ", &t)
	for t > 0 {
		var n, x, a, b int
		fmt.Scanf("%d %d %d %d ", &n, &x, &a, &b)
		fmt.Println(min(abs(a-b)+x, n-1))
		t--
	}
}

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
)

/*********** I/O ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt64()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		// str := strconv.FormatInt(A[i], 10)  // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*******************************************************************/

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var t int
var n, x, a, b int

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n, x, a, b = ReadInt4()
		solve()
	}
}

func solve() {
	if a > b {
		a, b = b, a
	}

	for {
		if x == 0 || a == 1 {
			break
		}

		a--
		x--
	}

	for {
		if x == 0 || b == n {
			break
		}

		b++
		x--
	}

	fmt.Println(AbsInt(b - a))
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

/*******************************************************************/

package main

import "fmt"

func main() {
	var q int
	fmt.Scan(&q)

	for i := 0; i < q; i++ {
		var n, x, a, b int
		fmt.Scan(&n, &x, &a, &b)
		fmt.Println(min(n-1, dif(a, b)+x))
	}
}

func min(num1, num2 int) int {
	if num1 > num2 {
		return num2
	}

	return num1
}

func dif(num1, num2 int) int {
	if num1 > num2 {
		return num1 - num2
	}

	return num2 - num1
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		var n, x, a, b int
		t--
		fmt.Scanf("%d %d %d %d\n", &n, &x, &a, &b)
		if a > b {
			a, b = b, a
		}
		mn := a - 1 + n - b
		if x < mn {
			mn = x
		}
		fmt.Printf("%d\n", b - a + mn)
	}
}

package main

import (
	"fmt"
)

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

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	var caseNum int
	fmt.Scanf("%d\n", &caseNum)
	for i := 0; i < caseNum; i++ {
		var n, x, a, b int
		fmt.Scanf("%d %d %d %d\n", &n, &x, &a, &b)
		fmt.Println(max(a, b) - min(a, b) + min(min(a, b)-1+n-max(a, b), x))
	}
}

package main

import "fmt"

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

	return a
}

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for tc := 0; tc < t; tc++ {
		var n, swaps, a, b int
		fmt.Scanf("%d %d %d %d\n", &n, &swaps, &a, &b)

		if b < a {
			a, b = b, a
		}

		toOne := min(a-1, swaps)
		ans := toOne
		swaps -= toOne
		toLast := min(n-b, swaps)
		ans += toLast
		fmt.Println(ans + (b - a))
	}
}

package main

import "fmt"

func min(a, b int) int {
    if a < b {
        return a
    } else {
        return b
    }
}
func main() {
    var T int
    fmt.Scanf("%d\n", &T)
    for T > 0 {
        T--
        var n, x, a, b int
        fmt.Scanf("%d %d %d %d\n", &n, &x, &a, &b)
        if a > b {
            a, b = b, a
        }
        fmt.Printf("%d\n", min(n-1, b - a + x))
    }
}

package main

import "fmt"

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

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

func main(){
	var q int
	fmt.Scanln(&q)
	for i:= 0;i < q ; i++ {
		var n, x, a, b int
		fmt.Scanln(&n, &x, &a, &b)
		fmt.Println(min(n - 1, x + abs(a - b)))
	}
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		t--
		fmt.Scanf("%d %d %d %d\n", &n, &x, &a, &b)
		//fmt.Printf("%d, %d, %d, %d, %d, %v, ", n, x, a, b, num, err)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

// A. Two Rival Students
/*
You are the gym teacher in the school.

There are 𝑛 students in the row. And there are two rivalling students among them. The first one is in position 𝑎, the second in position 𝑏. Positions are numbered from 1 to 𝑛 from left to right.

Since they are rivals, you want to maximize the distance between them. If students are in positions 𝑝 and 𝑠 respectively, then distance between them is |𝑝−𝑠|.

You can do the following operation at most 𝑥 times: choose two adjacent (neighbouring) students and swap them.

Calculate the maximum distance between two rivalling students after at most 𝑥 swaps.

Input
The first line contains one integer 𝑡 (1≤𝑡≤100) — the number of test cases.

The only line of each test case contains four integers 𝑛, 𝑥, 𝑎 and 𝑏 (2≤𝑛≤100, 0≤𝑥≤100, 1≤𝑎,𝑏≤𝑛, 𝑎≠𝑏) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

Output
For each test case print one integer — the maximum distance between two rivaling students which you can obtain.
Example
Input
3
5 1 3 2
100 33 100 1
6 0 2 3

Output
2
99
1

Note
In the first test case you can swap students in positions 3 and 4. And then the distance between the rivals is equal to |4−2|=2.

In the second test case you don't have to swap students.

In the third test case you can't swap students.
*/
package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	input1, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(strings.TrimSpace(input1))

	for i := 0; i < t; i++ {
		input2, _ := reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(input2), " ")

		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.Atoi(arr[1])
		a, _ := strconv.Atoi(arr[2])
		b, _ := strconv.Atoi(arr[3])

		if x == 0 {
			fmt.Println(abs(a - b))
		} else if abs(a-b) == (n - 1) {
			fmt.Println(abs(a - b))
		} else {
			fmt.Println(abs(a-b) + x)
		}
	}
}

func abs(n int) int {
	b := n >> 63
	return (n ^ b) - b
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scanln(&t)

	i := 0
	for i < t {
		var n int
		var x int
		var a int
		var b int
		fmt.Scanln(&n, &x, &a, &b)
		fmt.Println(n, x, a, b)

		// max distance is n-1 n-length of array x-max no of swaps a,b- pos of two
		present := 0
		if a > b {
			present = a - b
		} else {
			present = b - a
		}
		max := n - 1
		remain := max - present

		if x >= remain {
			ans := max
			fmt.Println(ans)
		} else {
			ans := x + present
			fmt.Println(ans)
		}
		i++
	}
}

package main

import (
	"fmt"
)

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

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

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for t > 0 {
		var n, x, a, b int
		fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Println(min(abs(a-b)+x, n-1))
		t--
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for t > 0 {
		var n, x, a, b int
		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		t--
		if a > b {
			a, b = b, a
		}
		mn := a - 1 + n - b
		if x < mn {
			mn = x
		}
		fmt.Printf("%d\n", b - a + mn)
	}
}

package main

import "fmt"

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

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	var caseNum int
	fmt.Scanf("%d", &caseNum)
	for i := 0; i < caseNum; i++ {
		var n, x, a, b int
		fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Println(max(a, b) - min(a, b) + min(min(a, b)-1+n-max(a, b), x))
	}
}

package main

import "fmt"

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

	return a
}

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for tc := 0; tc < t; tc++ {
		var n, swaps, a, b int
		fmt.Scanf("%d %d %d %d", &n, &swaps, &a, &b)

		if b < a {
			a, b = b, a
		}

		toOne := min(a-1, swaps)
		ans := toOne
		swaps -= toOne
		toLast := min(n-b, swaps)
		ans += toLast
		fmt.Println(ans + (b - a))
	}
}

package main

import "fmt"

func min(a, b int) int {
    if a > b {
        return a
    } else {
        return b
    }
}
func main() {
    var T int
    fmt.Scanf("%d", &T)
    for T > 0 {
        T--
        var n, x, a, b int
        fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
        if a > b {
            var tmp = a;
            a = b;
            b = tmp;
        }
        fmt.Printf("%d\n", min(n-1, b - a + x))
    }
}

package main

import "fmt"

func min(a, b int) int {
    if a < b {
        return a
    } else {
        return b
    }
}
func main() {
    var T int
    fmt.Scanf("%d", &T)
    for T > 0 {
        T--
        var n, x, a, b int
        fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
        if a > b {
            var tmp = a;
            a = b;
            b = tmp;
        }
        fmt.Printf("%d\n", min(n-1, b - a + x))
    }
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		fmt.Sprintf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	num, err := fmt.Scanf("%d", &t)
	fmt.Printf("%d, %v\n", num, err)
	for t > 0 {
		t--
		num, err = fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, %d, %d, %d, %v, ", n, x, a, b, num, err)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, %d, %d, ", n, x, a, b)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, %d, %d", n, x, a, b)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, ", abs(b-a)+x, abs(a-b)+x)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	num, err := fmt.Scanf("%d\n", &t)
	for t > 0 {
		t--
		num, err = fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, %d, %d, %d, %v, ", n, x, a, b, num, err)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

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

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("&d&d&d&d", &n, &x, &a, &b)
		fmt.Sprintf("%d\n", min(n-1, abs(b-a)+x))
	}
}


package main

import (
	"container/list"
	"fmt"
)

var n int
var stra string
var strb string
var mapa [500]int
var mapb [500]int

var sa int
var sb int

func main() {
	fmt.Scan(&stra)
	fmt.Scan(&strb)
	n = len(stra)

	lista := list.New()
	listb := list.New()
	//fmt.Println(lena)

	sa = n / 2
	sb = n / 2
	if n%2 == 1 {
		sb++
	}

	for _, chr := range stra {
		mapa[chr]++
	}
	for _, chr := range strb {
		mapb[chr]++
	}

	for chr := 'z'; chr >= 'a'; chr-- {
		if sa == 0 {
			break
		}
		if mapa[chr] > 0 {
			if sa <= mapa[chr] {
				mapa[chr] -= sa
				sa = 0
				break
			} else {
				sa -= mapa[chr]
				mapa[chr] = 0
			}
		}
	}

	for chr := 'a'; chr <= 'z'; chr++ {
		if sb == 0 {
			break
		}
		if mapb[chr] > 0 {
			if sb <= mapb[chr] {
				mapb[chr] -= sb
				sb = 0
				break
			} else {
				sb -= mapb[chr]
				mapb[chr] = 0
			}
		}
	}

	for i := 0; i < n; i++ {

		var mina rune
		for chr := 'a'; chr <= 'z'; chr++ {
			if mapa[chr] > 0 {
				mina = chr
				break
			}
		}

		var maxa rune
		for chr := 'z'; chr >= 'a'; chr-- {
			if mapa[chr] > 0 {
				maxa = chr
				break
			}
		}

		var minb rune
		for chr := 'a'; chr <= 'z'; chr++ {
			if mapb[chr] > 0 {
				minb = chr
				break
			}
		}

		var maxb rune
		for chr := 'z'; chr >= 'a'; chr-- {
			if mapb[chr] > 0 {
				maxb = chr
				break
			}
		}

		if i%2 == 0 {
			if maxb <= mina {
				listb.PushFront(maxa)
				mapa[maxa]--
			} else {
				lista.PushBack(mina)
				mapa[mina]--
			}

		} else {
			if maxb <= mina {
				listb.PushFront(minb)
				mapb[minb]--
			} else {
				lista.PushBack(maxb)
				mapb[maxb]--
			}
		}
	}

	for lista.Len() > 0 {
		fmt.Printf("%c", lista.Front().Value)
		lista.Remove(lista.Front())
	}

	for listb.Len() > 0 {
		fmt.Printf("%c", listb.Front().Value)
		listb.Remove(listb.Front())
	}

}
//asdfasd

package main

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

func findMin(letter []int) int {
	for i := 0;i < 26;i ++ {
		if letter[i] != 0 {
			return i
		}
	}
	return -1
}
func findMax(letter []int) int {
	for i := 25;i >= 0;i -- {
		if letter[i] != 0 {
			return i
		}
	}
	return 26
}
func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var olegString, igorString string
	olegLetter := make([]int, 26)
	igorLetter := make([]int, 26)
	fmt.Fscanf(reader, "%s\n", &olegString)
	fmt.Fscanf(reader, "%s\n", &igorString)
	n := len(olegString)
	ans := make([]byte, n)
	for i := 0;i < n;i ++ {
		olegLetter[int(olegString[i] - 'a')] ++
		igorLetter[int(igorString[i] - 'a')] ++
		ans[i] = '?'
	}
	olegCount, igorCount := (n + 1) / 2, n / 2
	olegSum, igorSum := 0, 0
	for i := 0;i < 26;i ++ {
		if olegSum + olegLetter[i] >= olegCount {
			olegLetter[i] = olegCount - olegSum
		}
		olegSum += olegLetter[i]
	}
	for i := 25;i >= 0;i -- {
		if igorSum + igorLetter[i] >= igorCount {
			igorLetter[i] = igorCount - igorSum
		}
		igorSum += igorLetter[i]
	}
	// turn = true => oleg
	// turn = false => igor
	for left, right, turn := 0, n - 1, true;left <= right; turn = !turn {
		olegMin := findMin(olegLetter)
		igorMax := findMax(igorLetter)
		if turn {
			if olegMin < igorMax {
				ans[left] = 'a' + byte(olegMin)
				left ++
				olegLetter[olegMin] --
			} else {
				olegMax := findMax(olegLetter)
				ans[right] = 'a' + byte(olegMax)
				right --
				olegLetter[olegMax] --
			}
		} else {
			if igorMax > olegMin {
				ans[left] = 'a' + byte(igorMax)
				left ++
				igorLetter[igorMax] --
			} else {
				igorMin := findMin(igorLetter)
				ans[right] = 'a' + byte(igorMin)
				right --
				igorLetter[igorMin] --
			}
		}
	}
	fmt.Printf("%s", string(ans))
}

package main

import "fmt"

var lena int
var stra string
var strb string
var mapa [500]int
var mapb [500]int

func main() {
	fmt.Scan(&stra)
	fmt.Scan(&strb)
	lena = len(stra)

	//fmt.Println(lena)

	for _, chr := range stra {
		mapa[chr]++
	}
	for _, chr := range strb {
		mapb[chr]++
	}

	for i := 0; i < lena; i++ {
		if i%2 == 0 {
			for chr := 'a'; chr <= 'z'; chr++ {
				if mapa[chr] > 0 {
					mapa[chr]--
					fmt.Printf("%c", chr)
					break
				}
			}
		} else {
			for chr := 'z'; chr >= 'a'; chr-- {
				if mapb[chr] > 0 {
					mapb[chr]--
					fmt.Printf("%c", chr)
					break
				}

			}
		}
	}

}

package main

import (
	"container/list"
	"fmt"
)

var n int
var stra string
var strb string
var mapa [500]int
var mapb [500]int

var sa int
var sb int

func main() {
	fmt.Scan(&stra)
	fmt.Scan(&strb)
	n = len(stra)

	lista := list.New()
	listb := list.New()
	//fmt.Println(lena)

	sa = n / 2
	sb = n / 2

	for _, chr := range stra {
		mapa[chr]++
	}
	for _, chr := range strb {
		mapb[chr]++
	}

	for chr := 'z'; chr >= 'a'; chr-- {
		if sa == 0 {
			break
		}
		if mapa[chr] > 0 {
			if sa <= mapa[chr] {
				mapa[chr] -= sa
				sa = 0
				break
			} else {
				sa -= mapa[chr]
				mapa[chr] = 0
			}
		}
	}

	for chr := 'a'; chr <= 'z'; chr++ {
		if sb == 0 {
			break
		}
		if mapb[chr] > 0 {
			if sb <= mapb[chr] {
				mapb[chr] -= sb
				sb = 0
				break
			} else {
				sb -= mapb[chr]
				mapb[chr] = 0
			}
		}
	}

	for i := 0; i < n; i++ {

		var mina rune
		for chr := 'a'; chr <= 'z'; chr++ {
			if mapa[chr] > 0 {
				mina = chr
				break
			}
		}

		var maxa rune
		for chr := 'z'; chr >= 'a'; chr-- {
			if mapa[chr] > 0 {
				maxa = chr
				break
			}
		}

		var minb rune
		for chr := 'a'; chr <= 'z'; chr++ {
			if mapb[chr] > 0 {
				minb = chr
				break
			}
		}

		var maxb rune
		for chr := 'z'; chr >= 'a'; chr-- {
			if mapb[chr] > 0 {
				maxb = chr
				break
			}
		}

		if i%2 == 0 {
			if maxb <= mina {
				listb.PushFront(maxa)
				mapa[maxa]--
			} else {
				lista.PushBack(mina)
				mapa[mina]--
			}

		} else {
			if maxb <= mina {
				listb.PushFront(minb)
				mapb[minb]--
			} else {
				lista.PushBack(maxb)
				mapb[maxb]--
			}
		}
	}

	for lista.Len() > 0 {
		fmt.Printf("%c", lista.Front().Value)
		lista.Remove(lista.Front())
	}

	for listb.Len() > 0 {
		fmt.Printf("%c", listb.Front().Value)
		listb.Remove(listb.Front())
	}

}

package main

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

func findMin(letter []int) int {
	for i := 0;i < 26;i ++ {
		if letter[i] != 0 {
			return i
		}
	}
	return -1
}
func findMax(letter []int) int {
	for i := 25;i >= 0;i -- {
		if letter[i] != 0 {
			return i
		}
	}
	return 26
}
func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var olegString, igorString string
	olegLetter := make([]int, 26)
	igorLetter := make([]int, 26)
	fmt.Fscanf(reader, "%s\n", &olegString)
	fmt.Fscanf(reader, "%s\n", &igorString)
	n := len(olegString)
	ans := make([]byte, n)
	for i := 0;i < n;i ++ {
		olegLetter[int(olegString[i] - 'a')] ++
		igorLetter[int(igorString[i] - 'a')] ++
		ans[i] = '?'
	}
	olegCount, igorCount := (n + 1) / 2, n / 2
	olegSum, igorSum := 0, 0
	for i := 0;i < 26;i ++ {
		if olegSum + olegLetter[i] >= olegCount {
			olegLetter[i] = olegCount - olegSum
			olegSum += olegLetter[i]
		}
	}
	for i := 25;i >= 0;i -- {
		if igorSum + igorLetter[i] >= igorCount {
			igorLetter[i] = igorCount - igorSum
			igorSum += igorLetter[i]
		}
	}
	// turn = true => oleg
	// turn = false => igor
	for left, right, turn := 0, n - 1, true;left <= right; turn = !turn {
		olegMin := findMin(olegLetter)
		igorMax := findMax(igorLetter)
		if turn {
			if olegMin < igorMax {
				ans[left] = 'a' + byte(olegMin)
				left ++
				olegLetter[olegMin] --
			} else {
				olegMax := findMax(olegLetter)
				ans[right] = 'a' + byte(olegMax)
				right --
				olegLetter[olegMax] --
			}
		} else {
			if igorMax > olegMin {
				ans[left] = 'a' + byte(igorMax)
				left ++
				igorLetter[igorMax] --
			} else {
				igorMin := findMin(igorLetter)
				ans[right] = 'a' + byte(igorMin)
				right --
				igorLetter[igorMin] --
			}
		}
	}
	fmt.Printf("%s", string(ans))
}


package main

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

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

	var T, n, m, k, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		ans := make([]int, m)
		one := make([]int, n+1)
		pos := make([][]int, n+1)
		mx := 0
		for i := 0; i < m; i++ {
			Fscan(in, &k)
			for j := 0; j < k; j++ {
				Fscan(in, &v)
				if k == 1 {
					one[v]++
					ans[i] = v
				}
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
			}
		}
		c := one[mx]
		if c > (m+1)/2 {
			Fprintln(out, "NO")
			continue
		}
		for _, p := range pos[mx] {
			if c == (m+1)/2 {
				break
			}
			if ans[p] == 0 {
				ans[p] = mx
				c++
			}
		}
		for i, ps := range pos {
			if i != mx {
				for _, p := range ps {
					if ans[p] == 0 {
						ans[p] = i
					}
				}
			}
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}
func main() { CF1483A(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, n, m, k, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		ans := make([]int, m)
		one := make([]int, n+1)
		pos := make([][]int, n+1)
		mx := 0
		for i := 0; i < m; i++ {
			Fscan(in, &k)
			for j := 0; j < k; j++ {
				Fscan(in, &v)
				if k == 1 {
					one[v]++
					ans[i] = v
				}
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
			}
		}
		c := one[mx]
		if c > (m+1)/2 {
			Fprintln(out, "NO")
			continue
		}
		for _, p := range pos[mx] {
			if c == (m+1)/2 {
				break
			}
			if ans[p] == 0 {
				ans[p] = mx
				c++
			}
		}
		for i, ps := range pos {
			if i != mx {
				for _, p := range ps {
					if ans[p] == 0 {
						ans[p] = i
					}
				}
			}
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

package main

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

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

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

	for ; t > 0; t-- {
		fmt.Fscan(in, &n, &m)

		freeFriends := make([][]int, m)
		freeDaysCnt := make([]int, n)
		for i := 0; i < m; i++ {
			fmt.Fscan(in, &k)
			freeFriends[i] = make([]int, k)
			for j := 0; j < k; j++ {
				fmt.Fscan(in, &freeFriends[i][j])
				freeDaysCnt[freeFriends[i][j]-1]++
			}
		}

		// find most available friend
		f, maxFreeDays := 0, 0
		for i := range freeDaysCnt {
			if freeDaysCnt[i] > maxFreeDays {
				f, maxFreeDays = i+1, freeDaysCnt[i]
			}
		}

		// save his free days
		freeDays := make([]int, 0, maxFreeDays)
		for i := 0; i < m; i++ {
			for j := range freeFriends[i] {
				if freeFriends[i][j] == f {
					freeDays = append(freeDays, i)
				}
			}
		}

		schedule := make([]int, m)
		if maxFreeDays <= (m+1)/2 {
			// nobody will occur more than allowed
			for i := 0; i < m; i++ {
				schedule[i] = freeFriends[i][0]
			}
		} else {
			// count days when most available friend is only option
			cnt := 0
			for i := 0; i < m; i++ {
				if len(freeFriends[i]) == 1 && freeFriends[i][0] == f {
					schedule[i] = f
					cnt++
				}
			}
			if cnt > (m+1)/2 {
				fmt.Fprintln(out, "NO")
				out.Flush()
				continue
			}
			// schedule most available friend till count is (m+1)/2
			for i := range freeDays {
				if cnt == (m+1)/2 {
					break
				}
				if schedule[freeDays[i]] == 0 {
					schedule[freeDays[i]] = f
					cnt++
				}
			}
			// fill other days with any friend except most available
			for i := 0; i < m; i++ {
				if schedule[i] > 0 {
					continue
				}
				j := 0
				for ; freeFriends[i][j] == f; j++ {
				}
				schedule[i] = freeFriends[i][j]
			}
		}

		fmt.Fprintln(out, "YES")
		for i := range schedule {
			fmt.Fprint(out, schedule[i], " ")
		}
		fmt.Fprintln(out)
		out.Flush()
	}
}

package main
import (
	"bufio"
	. "fmt"
	"io"
	"os"
)
// github.com/EndlessCheng/codeforces-go
func CF1483A(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var T, n, m, k,v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		m2 := (m + 1) / 2
		cnt := make([]int, n+1)
		pos := make([][]int, n+1)
		mx := 0
		ans := make([]int, m)
		for i := 0; i < m; i++ {
			Fscan(in, &k)
			if k == 1 {
				Fscan(in, &v)
				cnt[v]++
				ans[i] = v
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
				continue
			}
			for ; k > 0; k-- {
				Fscan(in, &v)
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
			}
		}
		c := cnt[mx]
		if c > m2 {
			Fprintln(out, "NO")
			continue
		}
		for _, p := range pos[mx] {
			if c == m2 {
				break
			}
			if ans[p] == 0 {
				ans[p] = mx
				c++
			}
		}
		for i, ps := range pos {
			if i != mx {
				for _, p := range ps {
					if ans[p] == 0 {
						ans[p] = i
					}
				}
			}
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

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

package main

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

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

	var T, n, m, k, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		m2 := (m + 1) / 2
		cnt := make([]int, n+1)
		pos := make([][]int, n+1)
		mx := 0
		ans := make([]int, m)
		for i := 0; i < m; i++ {
			Fscan(in, &k)
			if k == 1 {
				Fscan(in, &v)
				cnt[v]++
				ans[i] = v
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
				continue
			}
			for ; k > 0; k-- {
				Fscan(in, &v)
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
			}
		}
		c := cnt[mx]
		if c > m2 {
			Fprintln(out, "NO")
			continue
		}
		for _, p := range pos[mx] {
			if c == m2 {
				break
			}
			if ans[p] == 0 {
				ans[p] = mx
				c++
			}
		}
		for i, ps := range pos {
			if i != mx {
				for _, p := range ps {
					if ans[p] == 0 {
						ans[p] = i
					}
				}
			}
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}
func main() { CF1483A(os.Stdin, os.Stdout) }

package main

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

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

	var t int
	for fmt.Fscan(reader, &t); t > 0; t-- {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		limit := int(math.Ceil(float64(m) / 2.0))
		weights := make([]int, n+1)
		avail := make([][]int, m)
		final := make([]int, m)
		canMake := true

		for i := 0; i < m; i++ {
			var a, temp int
			fmt.Fscan(reader, &a)
			for j := 0; j < a; j++ {
				fmt.Fscan(reader, &temp)
				avail[i] = append(avail[i], temp)
			}

			if a == 0 {
				canMake = false
			}
			if a == 1 {
				weights[temp]++
				final[i] = temp
				if weights[temp] > limit {
					canMake = false
				}
			}
		}

		if !canMake {
			fmt.Fprintln(writer, "NO")
			continue
		}

		for i := 0; i < m; i++ {
			if len(avail[i]) > 1 {
				minimum := avail[i][0]
				for _, val := range avail[i] {
					if weights[val] < weights[minimum] {
						minimum = val
					}
				}
				final[i] = minimum
				weights[minimum]++
				if weights[minimum] > limit {
					canMake = false
					break
				}
			}
		}

		if !canMake {
			fmt.Fprintln(writer, "NO")
			continue
		}

		fmt.Fprintln(writer, "YES")
		for i, val := range final {
			fmt.Fprint(writer, val)
			if i != len(final)-1 {
				fmt.Fprint(writer, " ")
			}
		}
		fmt.Fprintln(writer)

	}
	writer.Flush()
}

package main

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

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

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

	for ; t > 0; t-- {
		fmt.Fscan(in, &n, &m)

		freeFriends := make([][]int, m)
		freeDaysCnt := make([]int, n)
		for i := 0; i < m; i++ {
			fmt.Fscan(in, &k)
			freeFriends[i] = make([]int, k)
			for j := 0; j < k; j++ {
				fmt.Fscan(in, &freeFriends[i][j])
				freeDaysCnt[freeFriends[i][j]-1]++
			}
		}

		// find most available friend
		f, maxFreeDays := 0, 0
		for i := range freeDaysCnt {
			if freeDaysCnt[i] > maxFreeDays {
				f, maxFreeDays = i+1, freeDaysCnt[i]
			}
		}

		// save his free days
		freeDays := make([]int, 0, maxFreeDays)
		for i := 0; i < m; i++ {
			for j := range freeFriends[i] {
				if freeFriends[i][j] == f {
					freeDays = append(freeDays, i)
				}
			}
		}

		schedule := make([]int, m)
		if maxFreeDays <= (m+1)/2 {
			// nobody will occur more than allowed
			for i := 0; i < m; i++ {
				schedule[i] = freeFriends[i][0]
			}
		} else {
			// count days when most available friend is only option
			cnt := 0
			for i := 0; i < m; i++ {
				if len(freeFriends[i]) == 1 && freeFriends[i][0] == f {
					schedule[i] = f
					cnt++
				}
			}
			if cnt > (m+1)/2 {
				fmt.Fprintln(out, "NO")
				out.Flush()
				continue
			}
			// schedule most available friend till count is (m+1)/2
			for i := range freeDays {
				if schedule[freeDays[i]] == 0 {
					schedule[freeDays[i]] = f
					cnt++
				}
				if cnt == (m+1)/2 {
					break
				}
			}
			// fill other days with any friend except most available
			for i := 0; i < m; i++ {
				if schedule[i] > 0 {
					continue
				}
				j := 0
				for ; freeFriends[i][j] == f; j++ {
				}
				schedule[i] = freeFriends[i][j]
			}
		}

		fmt.Fprintln(out, "YES")
		for i := range schedule {
			fmt.Fprint(out, schedule[i], " ")
		}
		fmt.Fprintln(out)
		out.Flush()
	}
}


package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		fmt.Println(solve(n, A))
	}
}

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 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 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 solve(n int, A []int) int {
	var i int
	for i < n && i+1 == A[i] {
		i++
	}
	if i == n {
		return 0
	}

	j := n - 1
	for j >= 0 && j+1 == A[j] {
		j--
	}

	k := i
	for k <= j && k+1 != A[k] {
		k++
	}

	if k > j {
		return 1
	}

	return 2
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var t, n int
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(reader, &n)
		a := make([]int, n + 1)
		for j := 1; j <= n; j++ {
			fmt.Fscan(reader, &a[j])
		}
		var l, r, res int
		for l = 1; l <= n; l++ {
			if a[l] != l {
				break
			}
		}
		for r = n; r >= 1; r-- {
			if a[r] != r {
				break
			}
		}
		if r == 0 {
			res = 0
		} else {
			res = 1
		}
		for ; l <= r; l++ {
			if a[l] == l {
				res = 2
			}
		}
		fmt.Fprintln(writer, res)
	}
}//2020-07-29 22:20:05.502

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var T int
	con.Scan(&T)
	for testcase := 0; testcase < T; testcase++ {
		var n int
		con.Scan(&n)
		x := make([]bool, n)
		c := 0
		for i := 0; i < n; i++ {
			var a int
			con.Scan(&a)
			if a == i+1 {
				c++
				x[i] = true
			}
		}
		if c == n {
			con.Println(0)
			continue
		}
		p := 0
		for i := 0; i < n; i++ {
			if !x[i] && (i == 0 || x[i-1]) {
				p++
			}
		}
		if p == 1 {
			con.Println(1)
		} else {
			con.Println(2)
		}
	}
	return nil
}

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

type priorityQueue [][2]int

func (pq priorityQueue) Len() int {
	return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func NextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func NextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	for cases := NextInt(); cases > 0; cases-- {
		n := NextInt()
		tot := 0
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = NextInt()
			if i+1 != arr[i] {
				if i == 0 || arr[i-1] == i {
					tot++
				}
			}
		}
		if tot > 2 {
			tot = 2
		}
		printf("%d\n", tot)
	}
}

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

type priorityQueue [][2]int

func (pq priorityQueue) Len() int {
	return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func NextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func NextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}
func Euclid(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	gcd, s1, s2 := Euclid(b, a%b)
	return gcd, s2, s1 - s2*(a/b)
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	for cases := NextInt(); cases > 0; cases-- {
		n := NextInt()
		tot := 0
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = NextInt()
			if i+1 != arr[i] {
				if i == 0 || arr[i-1] == i {
					tot++
				}
			}
		}
		printf("%d\n", tot)
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	//defer writer.Flush()
	var t, n int
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(reader, &n)
		a := make([]int, n + 1)
		for j := 1; j <= n; j++ {
			fmt.Fscan(reader, &a[j])
		}
		var l, r, res int
		for l = 1; l <= n; l++ {
			if a[l] != l {
				break
			}
		}
		for r = n; r >= 1; r-- {
			if a[r] != r {
				break
			}
		}
		if r == 0 {
			res = 0
		} else {
			res = 1
		}
		for ; l <= r; l++ {
			if a[l] == l {
				res = 2
			}
		}
		fmt.Fprintln(writer, res)
	}
}

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		fmt.Println(solve(n, A))
	}
}

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 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 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 solve(n int, A []int) int {
	var i int
	for i < n && i+1 == A[i] {
		i++
	}
	if i == n {
		return 0
	}
	j := i
	for j < n && j+1 != A[j] {
		j++
	}
	if j == n {
		return 1
	}
	j = n - 1
	for j >= 0 && j+1 == A[j] {
		j--
	}
	// j won't < 0
	i = j
	for i >= 0 && i+1 != A[i] {
		i--
	}

	if i < 0 {
		return 1
	}

	return 2
}

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		fmt.Println(solve(n, A))
	}
}

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 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 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 solve(n int, A []int) int {
	var loop func(i, j int, flipped bool)

	var res int

	loop = func(i, j int, flipped bool) {
		for i < j && (A[i] == i+1) == !flipped {
			i++
		}
		for j > i && (A[j-1] == j) == !flipped {
			j--
		}
		if i < j {
			res++
			loop(i, j, !flipped)
		}
	}

	loop(0, n, false)

	return res
}