Masha meets a new friend and learns his phone number — $$$s$$$. She wants to remember it as soon as possible. The phone number — is a string of length $$$m$$$ that consists of digits from $$$0$$$ to $$$9$$$. The phone number may start with 0.Masha already knows $$$n$$$ phone numbers (all numbers have the same length $$$m$$$). It will be easier for her to remember a new number if the $$$s$$$ is represented as segments of numbers she already knows. Each such segment must be of length at least $$$2$$$, otherwise there will be too many segments and Masha will get confused.For example, Masha needs to remember the number: $$$s = $$$ '12345678' and she already knows $$$n = 4$$$ numbers: '12340219', '20215601', '56782022', '12300678'. You can represent $$$s$$$ as a $$$3$$$ segment: '1234' of number one, '56' of number two, and '78' of number three. There are other ways to represent $$$s$$$.Masha asks you for help, she asks you to break the string $$$s$$$ into segments of length $$$2$$$ or more of the numbers she already knows. If there are several possible answers, print any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases. Before each test case there is a blank line. Then there is a line containing integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^3$$$) —the number of phone numbers that Masha knows and the number of digits in each phone number. Then follow $$$n$$$ line, $$$i$$$-th of which describes the $$$i$$$-th number that Masha knows. The next line contains the phone number of her new friend $$$s$$$. Among the given $$$n+1$$$ phones, there may be duplicates (identical phones). It is guaranteed that the sum of $$$n \cdot m$$$ ($$$n$$$ multiplied by $$$m$$$) values over all input test cases does not exceed $$$10^6$$$.

You need to print the answers to $$$t$$$ test cases. The first line of the answer should contain one number $$$k$$$, corresponding to the number of segments into which you split the phone number $$$s$$$. Print -1 if you cannot get such a split. If the answer is yes, then follow $$$k$$$ lines containing triples of numbers $$$l, r, i$$$. Such triplets mean that the next $$$r-l+1$$$ digits of number $$$s$$$ are equal to a segment (substring) with boundaries $$$[l, r]$$$ of the phone under number $$$i$$$. Both the phones and the digits in them are numbered from $$$1$$$. Note that $$$r-l+1 \ge 2$$$ for all $$$k$$$ lines.

NoteThe example from the statement.In the second case, it is impossible to represent by segments of known numbers of length 2 or more.In the third case, you can get the segments '12' and '21' from the first phone number.

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer

	for tc > 0 {
		tc--
		reader.ReadString('\n')
		n, m := readTwoNums(reader)
		A := make([]string, n)
		for i := 0; i < n; i++ {
			A[i] = readString(reader)
		}
		S := readString(reader)
		res := solve(n, m, A, S)
		if len(res) == 0 {
			buf.WriteString("-1\n")
		} else {
			buf.WriteString(fmt.Sprintf("%d\n", len(res)))
			for _, cur := range res {
				buf.WriteString(fmt.Sprintf("%d %d %d\n", cur[0], cur[1], cur[2]))
			}
		}
	}

	fmt.Print(buf.String())
}

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

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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, m int, A []string, S string) [][]int {
	// 貌似只有2位或者3位的字符串才需要记录
	marks := make([][]Mark, 4)

	// at most 999
	for i := 0; i < 4; i++ {
		marks[i] = make([]Mark, 1000)
	}

	set := func(key string, l, r, i int) {
		if r == l {
			// at least length 2
			return
		}
		x := r - l + 1

		y, _ := strconv.Atoi(key)

		marks[x][y] = Mark{l, r, i}
	}

	get := func(key string) (bool, Mark) {
		if len(key) < 2 {
			return false, Mark{}
		}
		x := len(key)
		y, _ := strconv.Atoi(key)
		cur := marks[x][y]
		if cur.r-cur.l+1 == len(key) {
			return true, cur
		}
		return false, cur
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			for x := 2; x <= 3 && j+x <= m; x++ {
				set(A[i][j:j+x], j, j+x-1, i)
			}
		}
	}

	ans := make([]Mark, m)

	vis := make([]bool, m)

	var build func(i int) bool

	build = func(i int) bool {
		if i == m || ans[i].Len() > 1 {
			return true
		}
		if vis[i] {
			return false
		}
		vis[i] = true

		for x := 2; x <= 3 && i+x <= m; x++ {
			ok, mark := get(S[i : i+x])
			if ok {
				ans[i] = mark
				if build(i + mark.Len()) {
					return true
				}
				ans[i] = Mark{}
			}
		}
		return false
	}

	if build(0) {
		var res [][]int
		pos := 0
		for pos < m {
			cur := ans[pos]
			res = append(res, []int{cur.l + 1, cur.r + 1, cur.i + 1})
			pos += cur.Len()
		}
		return res
	}
	return nil
}

type Mark struct {
	l int
	r int
	i int
}

func (this Mark) Len() int {
	return this.r - this.l + 1
}

const MOD1 = 10000000000007
const MOD2 = 1000000000009

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(reader, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
// 	redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n, m int
	scan(&n, &m)
	var pos = make(map[string][2]int)
	for i := 0; i < n; i++ {
		var s string
		scan(&s)
		for j := range s {
			if j+2 <= len(s) {
				pos[s[j:j+2]] = [2]int{i, j}
			}
			if j+3 <= len(s) {
				pos[s[j:j+3]] = [2]int{i, j}
			}
		}
	}
	var s string
	scan(&s)
	var (
		dp   = make([]bool, len(s))
		prev = make([]int, len(s))
	)
	for i := range s {
		for l := 2; l <= 3; l++ {
			if i-l+1 < 0 {
				continue
			}
			_, ok1 := pos[s[i-l+1:i+1]]
			ok2 := i-l < 0 || dp[i-l]
			if ok1 && ok2 {
				dp[i] = true
				prev[i] = i - l
			}
		}
	}
	if !dp[len(s)-1] {
		printf("-1\n")
		return
	}
	var ans = [][3]int{}
	for i := len(s) - 1; i >= 0 && dp[i]; {
		j := prev[i]
		p := pos[s[j+1:i+1]]
		ans = append(ans, [3]int{p[1], p[1] + i - j - 1, p[0]})
		i = j
	}
	printf("%v\n", len(ans))
	for i := len(ans) - 1; i >= 0; i-- {
		printf("%v %v %v\n", ans[i][0]+1, ans[i][1]+1, ans[i][2]+1)
	}
}

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer

	for tc > 0 {
		tc--
		reader.ReadString('\n')
		n, m := readTwoNums(reader)
		A := make([]string, n)
		for i := 0; i < n; i++ {
			A[i] = readString(reader)
		}
		S := readString(reader)
		res := solve(n, m, A, S)
		if len(res) == 0 {
			buf.WriteString("-1\n")
		} else {
			for _, cur := range res {
				buf.WriteString(fmt.Sprintf("%d %d %d\n", cur[0], cur[1], cur[2]))
			}
		}
	}

	fmt.Print(buf.String())
}

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

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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, m int, A []string, S string) [][]int {
	// 貌似只有2位或者3位的字符串才需要记录
	marks := make([][]Mark, 4)

	// at most 999
	for i := 0; i < 4; i++ {
		marks[i] = make([]Mark, 1000)
	}

	set := func(key string, l, r, i int) {
		if r == l {
			// at least length 2
			return
		}
		x := r - l + 1

		y, _ := strconv.Atoi(key)

		marks[x][y] = Mark{l, r, i}
	}

	get := func(key string) (bool, Mark) {
		if len(key) < 2 {
			return false, Mark{}
		}
		x := len(key)
		y, _ := strconv.Atoi(key)
		cur := marks[x][y]
		if cur.r-cur.l+1 == len(key) {
			return true, cur
		}
		return false, cur
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			for x := 2; x <= 3 && j+x <= m; x++ {
				set(A[i][j:j+x], j, j+x-1, i)
			}
		}
	}

	ans := make([]Mark, m)

	var build func(i int) bool

	build = func(i int) bool {
		if i == m {
			return true
		}
		for x := 2; x <= 3 && i+x <= m; x++ {
			ok, mark := get(S[i : i+x])
			if ok {
				ans[i] = mark
				if build(i + mark.Len()) {
					return true
				}
				ans[i] = Mark{}
			}
		}
		return false
	}

	if build(0) {
		var res [][]int
		pos := 0
		for pos < m {
			cur := ans[pos]
			res = append(res, []int{cur.l + 1, cur.r + 1, cur.i + 1})
			pos += cur.Len()
		}
		return res
	}
	return nil
}

type Mark struct {
	l int
	r int
	i int
}

func (this Mark) Len() int {
	return this.r - this.l + 1
}

const MOD1 = 10000000000007
const MOD2 = 1000000000009


Consider a table of size $$$n \times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 115$$$) — the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.

Output two integers $$$r$$$ and $$$c$$$ ($$$1 \le r \le n$$$, $$$1 \le c \le m$$$) separated by a space — the row and column numbers of the center of the black square.

package main

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

func main() {
    var height, width, lines, square_left  int
    var line string

    square_top:=0
    square_width:=0

    fmt.Scanf("%d %d",&height, &width)
    for{
        lines,_=fmt.Scan(&line)
        if lines==0 {break}
        square_top++;

        for i:=0;i<width;i++{
            if line[i]=='B' {
                square_left=i;
                for x:=i;x<width;x++{
                   if line[x]=='B'{
                      square_width++
                   } else {
                       break
                   }
                }
                break
            }
        }
        if square_width>0 {
            halfwidth:=(square_width-1)/2
            fmt.Printf("%d %d",square_top+halfwidth,square_left+halfwidth+1)
            break
        }
    }
}

package main

import (
	"fmt"
)

type Point struct {
	x int
	y int
}

func main() {

	var n int
	var m int

	fmt.Scan(&n)
	fmt.Scan(&m)

	var s string
	var p1 Point
	var p2 Point
	p1.x = -1
	p1.y = -1
	p2.x = -1
	p2.y = -1
	for i := 0; i < n; i++ {
		fmt.Scan(&s)

		for j, sub := range s {

			if string(sub) == "B" && p1.x == -1 {

				p1.x = i + 1
				p1.y = j + 1

			} else if string(sub) == "B" {

				p2.x = i + 1
				p2.y = j + 1
			}
		}
	}

	if p2.x == -1 || p2.y == -1 {
		fmt.Println(p1.x, p1.y)
	} else {

		fmt.Println(((p1.x+p2.x))/2, ((p1.y+p2.y))/2)
	}

}

package main

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

func main()  {

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

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

	ch := make([][]byte, n)
	for i := 0; i < n; i++ {
		ch[i] = make([]byte, m)
	}

	for i := 0; i < n; i++ {
		var s string
		fmt.Fscan(in, &s)
		for j := 0; j < m; j++ {
			ch[i][j] = s[j]
		}
	}

	xLT, yLT, xRB, yRB := n - 1, m - 1, 0, 0
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if ch[i][j] == 'B' {
				if xLT > i {
					xLT = i
				}
				if yLT > j {
					yLT = j
				}
				if xRB < i {
					xRB = i
				}
				if yRB < j {
					yRB = j
				}
			}
		}
	}

	fmt.Fprintln(out, xLT + (xRB - xLT) / 2 + 1, yLT + (yRB - yLT) / 2 + 1)

}

package main

import "fmt"

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	arr := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&arr[i])
	}

	var fr, lr int
	var fc, lc int
	fr = -1
	lr = -1
	fc = -1
	lc = -1
	for i := 0; i < n; i++ {
		if rowBlack(arr, i) {
			if fr < 0 {
				fr = i
			}
			lr = i
		}
	}
	for i := 0; i < m; i++ {
		if columnBlack(arr, i) {
			if fc < 0 {
				fc = i
			}
			lc = i
		}
	}
	fmt.Println(fr+(lr-fr)/2+1, fc+(lc-fc)/2+1)
}

func rowBlack(arr []string, r int) bool {
	for _, ch := range arr[r] {
		if ch == 'B' {
			return true
		}
	}
	return false
}

func columnBlack(arr []string, c int) bool {
	for _, row := range arr {
		if row[c] == 'B' {
			return true
		}
	}
	return false
}

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 1024*1024)
	dims := readInts(r, 2)
	n := dims[0]
	m := dims[1]

	for i := 0; i < n; i++ {
		row := readString(r, m)
		for q, ch := range row {
			if ch == 'B' {
				l := 0
				for ; i + l < n - 1; {
					if next := readString(r, m); next[q] == 'B' {
						l++
					} else {
						break
					}
				}
				m := l/2
				fmt.Println(i+m+1,q+m+1)
				return
			}
		}
	}
}

func readInts(reader *bufio.Reader, n int) []int {
	tmpInts := strings.Split(readLine(reader), " ")

	var result []int
	for i := 0; i < n; i++ {
		tmpInt, err := strconv.ParseInt(tmpInts[i], 10, 64)
		checkError(err)
		result = append(result, int(tmpInt))
	}
	return result
}

func readString(reader *bufio.Reader, l int) string {
	sTemp := readLine(reader)
	if len(sTemp) < l {
		l = len(sTemp)
	}
	return sTemp[:l]
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

package main

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

func main() {
    var height, width, lines, square_left  int
    var line string

    square_top:=0
    square_width:=0

    fmt.Scanf("%d %d",&height, &width)
    for{
        lines,_=fmt.Scan(&line)
        if lines==0 {break}

        for i:=0;i<width;i++{
            if line[i]=='B' {
                square_left=i;
                for x:=i;x<width;x++{
                   if line[i]=='B'{
                      square_width++
                   } else {
                       break
                   }
                }
                break
            }
        }

        if square_width>0 {
            fmt.Printf("%d %d",square_top+square_width/2,square_left+square_width/2)
            break
        }
        square_top++;
    }
}

package main

import "fmt"

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	arr := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&arr[i])
		fmt.Println(arr[i])
	}

	var fr, lr int
	var fc, lc int
	fr = -1
	lr = -1
	fc = -1
	lc = -1
	for i := 0; i < n; i++ {
		if rowBlack(arr, i) {
			if fr < 0 {
				fr = i
			}
			lr = i
		}
	}
	for i := 0; i < m; i++ {
		if columnBlack(arr, i) {
			if fc < 0 {
				fc = i
			}
			lc = i
		}
	}
	fmt.Println(fr+(lr-fr)/2+1, fc+(lc-fc)/2+1)
}

func rowBlack(arr []string, r int) bool {
	for _, ch := range arr[r] {
		if ch == 'B' {
			return true
		}
	}
	return false
}

func columnBlack(arr []string, c int) bool {
	for _, row := range arr {
		if row[c] == 'B' {
			return true
		}
	}
	return false
}


You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$ — the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.

The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$) — elements of given array.

In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.

// 78 ms	8500 KB
package main

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

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

	var n, x int
	fmt.Fscanf(in, "%d %d\n", &n, &x)
	counter := map[int]int{}
	for ; n > 0; n-- {
		var tmp int
		fmt.Fscan(in, &tmp)
		if tmp < x {
			counter[tmp]++
			for counter[tmp] > tmp {
				quotient := counter[tmp] / (tmp + 1)
				remainder := counter[tmp] % (tmp + 1)
				if remainder == 0 {
					delete(counter, tmp)
				} else {
					counter[tmp] = remainder
				}
				if tmp+1 < x {
					counter[tmp+1] += quotient
					tmp++
				}
			}
		}
	}
	if len(counter) > 0 {
		fmt.Fprintln(out, "No")
	} else {
		fmt.Fprintln(out, "Yes")
	}
}

// 109 ms	22000 KB
package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n, x, tmp int
	fmt.Fscanf(in, "%d %d\n", &n, &x)
	counter := map[int]int{}
	for ; n > 0; n-- {
		fmt.Fscan(in, &tmp)
		if tmp >= x {
			continue
		}
		counter[tmp]++
		for counter[tmp] > tmp {
			q := counter[tmp] / (tmp + 1)
			if r := counter[tmp] % (tmp + 1); r > 0 {
				counter[tmp] = r
			} else {
				delete(counter, tmp)
			}
			if tmp+1 < x {
				counter[tmp+1] += q
				tmp++
			}
		}
	}
	if len(counter) > 0 {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}
}

package main

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

func main() {
	var n, x int
	fmt.Scanf("%d %d\n", &n, &x)
	counter := make([]int, x)
	distinct := 0
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for ; n > 0 && scanner.Scan(); n-- {
		tmp, _ := strconv.Atoi(scanner.Text())
		if tmp >= x {
			continue
		}
		if counter[tmp] == 0 {
			distinct++
		}
		counter[tmp]++
		for counter[tmp] > tmp {
			increase := counter[tmp] / (tmp + 1)
			counter[tmp] = counter[tmp] % (tmp + 1)
			if counter[tmp] == 0 {
				distinct--
			}
			tmp++
			if tmp < x {
				if counter[tmp] == 0 {
					distinct++
				}
				counter[tmp] += increase
			} else {
				break
			}
		}
	}
	if distinct > 0 {
		fmt.Println("No")
		return
	}
	fmt.Println("Yes")
}

package main

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

func main() {
	var n, x int
	fmt.Scanf("%d %d\n", &n, &x)
	counter := map[int]int{}
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for ; n > 0 && scanner.Scan(); n-- {
		tmp, _ := strconv.Atoi(scanner.Text())
		if tmp >= x {
			continue
		}
		counter[tmp]++
		for counter[tmp] > tmp {
			q := counter[tmp] / (tmp + 1)
			if r := counter[tmp] % (tmp + 1); r > 0 {
				counter[tmp] = r
			} else {
				delete(counter, tmp)
			}
			if tmp+1 < x {
				counter[tmp+1] += q
				tmp++
			}
		}
	}
	if len(counter) > 0 {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}
}

package main

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

func main() {
	var n, x int
	fmt.Scanf("%d %d\n", &n, &x)
	counter := map[int]int{}
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for ; n > 0 && scanner.Scan(); n-- {
		if tmp, _ := strconv.Atoi(scanner.Text()); tmp < x {
			counter[tmp]++
			for counter[tmp] > tmp {
				quotient := counter[tmp] / (tmp + 1)
				remainder := counter[tmp] % (tmp + 1)
				if remainder == 0 {
					delete(counter, tmp)
				} else {
					counter[tmp] = remainder
				}
				if tmp+1 < x {
					counter[tmp+1] += quotient
					tmp++
				}
			}
		}
	}
	if len(counter) > 0 {
		fmt.Println("No")
		return
	}
	fmt.Println("Yes")
}

package main

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

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

	var n, x int
	fmt.Fscan(r, &n, &x)
	cnt := make([]int, x+1)

	for i := 0; i < n; i++ {
		var t int
		fmt.Fscan(r, &t)
		cnt[t]++
	}

	res := "YES"
	for i := 1; i < x; i++ {
		cnt[i+1] += cnt[i]/(i+1)
		cnt[i] %= (i+1)

		if cnt[i] > 0 {
			res = "NO"
			break
		}
	}

	fmt.Fprintln(w, res)
}

package main

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

const mod = 998244353

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n, k int
	Fscan(in, &n, &k)
	arr := make([]int, k+1)
	for i := 0; i < n; i++ {
		var idx int
		Fscan(in, &idx)
		arr[idx]++
	}
	for i := 1; i < len(arr)-1; i++ {
		if arr[i]%(i+1) != 0 {
			Fprintln(out, "No")
			return
		}
		arr[i+1] += arr[i] / (i + 1)
	}
	Fprintln(out, "Yes")
}

func max(i, j int) int {
	if i > j {
		return i
	}
	return j
}
func lcm(a, b int) int {
	return a * b / gcd(a, b)
}
func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

func main() {

	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	//Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

func main() {
	var n, x int
	fmt.Scanf("%d %d\n", &n, &x)
	counter := make([]int, x)
	distinct := 0
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for ; n > 0 && scanner.Scan(); n-- {
		tmp, _ := strconv.Atoi(scanner.Text())
		if tmp >= x {
			continue
		}
		if counter[tmp] == 0 {
			distinct++
		}
		counter[tmp]++
		for counter[tmp] > tmp {
			increase := counter[tmp] / (tmp + 1)
			counter[tmp] = counter[tmp] % (tmp + 1)
			if counter[tmp] == 0 {
				distinct--
			}
			tmp++
			if tmp < x {
				counter[tmp] += increase
			} else {
				break
			}
		}
	}
	if distinct > 0 {
		fmt.Println("No")
		return
	}
	fmt.Println("Yes")
}

package main

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

func main() {
	var tmp, x int
	fmt.Scanf("%d %d\n", &tmp, &x)
	counter := map[int]int{}
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	nums := strings.Fields(scanner.Text())
	for i := range nums {
		tmp, _ = strconv.Atoi(nums[i])
		if tmp >= x {
			continue
		}
		counter[tmp]++
		for counter[tmp] >= tmp+1 {
			quotient := counter[tmp] / (tmp + 1)
			remainder := counter[tmp] % (tmp + 1)
			if remainder == 0 {
				delete(counter, tmp)
			} else {
				counter[tmp] = remainder
			}
			if tmp+1 < x {
				counter[tmp+1] += quotient
				tmp++
			}
		}
	}
	if len(counter) > 0 {
		fmt.Println("No")
		return
	}
	fmt.Println("Yes")
}

package main

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

func main() {
	var tmp, x int
	fmt.Scanf("%d %d\n", &tmp, &x)
	counter := map[int]int{}
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	nums := strings.Fields(scanner.Text())
	for i := range nums {
		tmp, _ = strconv.Atoi(nums[i])
		if tmp >= x {
			continue
		}
		counter[tmp]++
		for counter[tmp] >= tmp+1 {
			increase := counter[tmp] / (tmp + 1)
			counter[tmp] = counter[tmp] % (tmp + 1)
			tmp++
			if tmp < x {
				counter[tmp] += increase
			}
		}
	}
	for k, v := range counter {
		if v > 0 && k < x {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

package main

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

func main() {
	var tmp, x int
	fmt.Scanf("%d %d\n", &tmp, &x)
	counter := map[int]int{}
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	nums := strings.Fields(scanner.Text())

	for i := range nums {
		tmp, _ = strconv.Atoi(nums[i])
		if tmp >= x {
			continue
		}
		if _, ok := counter[tmp]; !ok {
			counter[tmp] = 1
		} else {
			counter[tmp]++
			j := tmp
			for counter[j] >= j+1 {
				increase := counter[j] / (j + 1)
				counter[j] = counter[j] % (j + 1)
				if counter[j] == 0 {
					delete(counter, j)
				}
				j++
				if j < x {
					counter[j] += increase
				}
			}
		}
	}
	if len(counter) > 0 {
		fmt.Println("No")
		return
	}
	fmt.Println("Yes")
}

package main

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

func main() {
	var num, x int
	fmt.Scanf("%d %d\n", &num, &x)
	counter := make([]int, 500001)
	distinct := 0
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	line := scanner.Text()
	nums := strings.Fields(line)

	for i := range nums {
		tmp, _ := strconv.Atoi(nums[i])
		if tmp >= x {
			continue
		}
		if counter[tmp] == 0 {
			distinct++
		}
		counter[tmp]++
		for counter[tmp] >= tmp+1 {
			increase := counter[tmp] / (tmp + 1)
			counter[tmp] = counter[tmp] % (tmp + 1)
			if counter[tmp] == 0 {
				distinct--
			}
			tmp++
			if tmp < x {
				counter[tmp] += increase
			}
		}
	}
	if distinct > 0 {
		fmt.Println("No")
		return
	}
	fmt.Println("Yes")
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var num, x int
	fmt.Scanf("%d %d\n", &num, &x)
	a := make([]int, num)
	for i := 0; i < num; i++ {
		fmt.Scanf("%d", &a[i])
	}
	sort.Ints(a)

	// combine
	for i := 0; i < num; {
		j := i
		for ; j < num-1 && a[j] == a[j+1]; j++ {
		}
		if i != j {
			nextI := a[i] + i
			if j-i+1 >= a[i]+1 {
				// reset
				for k := i; k < i+a[j]; k++ {
					a[k] = 0
				}
				a[j]++
			}
			i = nextI
		} else {
			i++
		}
		fmt.Println(a)
	}

	count := 0
	for _, n := range a {
		if n < x && n > 0 {
			count++
			break
		}
	}
	if count > 0 {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}
}


Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.

The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000).

On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.

NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana".

package main

import (
	"bufio"
	"bytes"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

type countedChar struct {
	char  byte
	count float64
}

type charHeap []countedChar

func (c charHeap) Len() int           { return len(c) }
func (c charHeap) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c charHeap) Less(i, j int) bool { return c[i].count < c[j].count }

func (c *charHeap) Push(x interface{}) {
	*c = append(*c, x.(countedChar))
}

func (c *charHeap) Pop() interface{} {
	old := *c
	n := len(old)
	x := old[n-1]
	*c = old[:n-1]
	return x
}

func stripNLandR(s string) string {
	if s == "" {
		return s
	}
	last := s[len(s)-1]
	if last == '\n' || last == '\r' {
		return stripNLandR(s[:len(s)-1])
	}
	return s
}

func main() {
	b := bufio.NewReader(os.Stdin)
	text, err := b.ReadString('\n')
	if err != nil {
		panic(err)
	}
	text = stripNLandR(text)
	nStr, err := b.ReadString('\n')
	if err != nil {
		panic(err)
	}
	nStr = stripNLandR(nStr)
	n, err := strconv.Atoi(nStr)
	if err != nil {
		panic(err)
	}

	histo := make(map[byte]int)
	for _, b := range []byte(text) {
		if count, ok := histo[b]; ok {
			histo[b] = count + 1
		} else {
			histo[b] = 1
		}
	}

	extra := n - len(histo)
	if extra < 0 {
		fmt.Println(-1)
		return
	}

	ordered := make(charHeap, 0, len(histo))
	for k, v := range histo {
		ordered = append(ordered, countedChar{k, 1 / float64(v)})
	}
	heap.Init(&ordered)

	choiceHisto := make(map[byte]int, len(histo))
	for k := range histo {
		choiceHisto[k] = 1
	}
	for i := 0; i < extra; i++ {
		char := ordered[0]
		old := choiceHisto[char.char]
		new := old + 1
		char.count *= float64(new) / float64(old)
		ordered[0] = char
		heap.Fix(&ordered, 0)
		choiceHisto[char.char] = new
	}

	worstChar := ordered[0].char
	num := choiceHisto[worstChar]
	wantNum := histo[worstChar]
	needed := wantNum / num
	if wantNum%num > 0 {
		needed++
	}
	fmt.Println(needed)

	var buf bytes.Buffer
	for k, v := range choiceHisto {
		for i := 0; i < v; i++ {
			buf.WriteByte(k)
		}
	}
	fmt.Println(buf.String())
}

package main

import (
	"bufio"
	"bytes"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

type countedChar struct {
	char  byte
	count float64
}

type charHeap []countedChar

func (c charHeap) Len() int           { return len(c) }
func (c charHeap) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c charHeap) Less(i, j int) bool { return c[i].count < c[j].count }

func (c *charHeap) Push(x interface{}) {
	*c = append(*c, x.(countedChar))
}

func (c *charHeap) Pop() interface{} {
	old := *c
	n := len(old)
	x := old[n-1]
	*c = old[:n-1]
	return x
}

func stripNLandR(s string) string {
	if s == "" {
		return s
	}
	last := s[len(s)-1]
	if last == '\n' || last == '\r' {
		return stripNLandR(s[:len(s)-1])
	}
	return s
}

func main() {
	b := bufio.NewReader(os.Stdin)
	text, err := b.ReadString('\n')
	if err != nil {
		panic(err)
	}
	text = stripNLandR(text)
	nStr, err := b.ReadString('\n')
	if err != nil {
		panic(err)
	}
	nStr = stripNLandR(nStr)
	n, err := strconv.Atoi(nStr)
	if err != nil {
		panic(err)
	}

	histo := make(map[byte]int)
	for _, b := range []byte(text) {
		if count, ok := histo[b]; ok {
			histo[b] = count + 1
		} else {
			histo[b] = 1
		}
	}

	extra := n - len(histo)
	if extra < 0 {
		fmt.Println(-1)
		return
	}

	ordered := make(charHeap, 0, len(histo))
	for k, v := range histo {
		ordered = append(ordered, countedChar{k, 1 / float64(v)})
	}
	heap.Init(&ordered)

	choiceHisto := make(map[byte]int, len(histo))
	for k := range histo {
		choiceHisto[k] = 1
	}
	for i := 0; i < extra; i++ {
		char := ordered[0]
		old := choiceHisto[char.char]
		new := old + 1
		char.count *= float64(new) / float64(old)
		heap.Fix(&ordered, 0)
		choiceHisto[char.char] = new
	}

	worstChar := ordered[0].char
	num := choiceHisto[worstChar]
	wantNum := histo[worstChar]
	needed := wantNum / num
	if wantNum%num > 0 {
		needed++
	}
	fmt.Println(needed)

	var buf bytes.Buffer
	for k, v := range choiceHisto {
		for i := 0; i < v; i++ {
			buf.WriteByte(k)
		}
	}
	fmt.Println(buf.String())
}


Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:  on both diagonals of the square paper all letters are the same;  all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.

The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.

Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.

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

	startIndex, endIndex := 0, n-1
	line := next()
	var xLetter, otherLetter uint8 = line[0], line[1]

	if xLetter == otherLetter {
		println("NO")
		return
	}

	if line[startIndex]!=xLetter || line[startIndex] != line[endIndex] {
		println("NO")
		return
	}

	for j:=0; j<n; j++ {
		if j!=startIndex && j!=endIndex && line[j]!=otherLetter {
			println("NO")
			return
		}
	}
	startIndex++
	endIndex--

	for i:=1; i<n; i++ {
		line = next()

		if line[startIndex]!=xLetter || line[startIndex] != line[endIndex] {
			println("NO")
			return
		}

		for j:=0; j<n; j++ {
			if j!=startIndex && j!=endIndex && line[j]!=otherLetter {
				println("NO")
				return
			}
		}
		startIndex++
		endIndex--
	}

	println("YES")
}

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 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 [305]string
    var x,y byte
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&s[i])
    }
    ans := true
    for i := 0; (i < n) && ans; i++ {
        for j := 0; j < n; j++ {
            if (i == j) || (i == (n-j-1)) {
                if x != 0 {
                    if x != s[i][j] { ans = false; break }
                } else {
                    x = s[i][j]
                }
            } else {
                if y != 0 {
                    if y != s[i][j] { ans = false; break }
                } else {
                    y = s[i][j]
                }
            }
        }
    }
    if ans && (x != y) { fmt.Println("YES") } else { fmt.Println("NO") }
}

package main

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

func main() {
	var n int // Odd
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	var is_x bool = true
	var diagonal rune
	var blank rune

	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < n; i++ {
		for j := 0; j <= n; j++ {
			if c, _, err := reader.ReadRune(); err != nil {
				if err == io.EOF {
					break
				} else {
					return
				}
			} else {
				if '\n' == c {
					continue
				} else if '\r' == c { // Read the following '\n'
					if _, _, err := reader.ReadRune(); err != nil {
						if err == io.EOF {
							break
						} else {
							return
						}
					}
					continue
				}

				if i == 0 && j == 0 {
					diagonal = c
				} else if i == 0 && j == 1 {
					blank = c
					if blank == diagonal {
						is_x = false
					}
				} else {
					if j == i || j == n-i-1 {
						if c != diagonal {
							is_x = false
						}
					} else {
						if c != blank {
							is_x = false
						}
					}
				}
			}
		}
	}

	if is_x {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

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

func main() {
	var n int // Odd
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	var is_x bool = true
	var diagonal byte
	var blank byte

	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < n; i++ {
		if s, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			} else {
				return
			}
		} else {
			for j := 0; j < n; j++ {
				if i == 0 && j == 0 {
					diagonal = s[j]
				} else if i == 0 && j == 1 {
					blank = s[j]
					if blank == diagonal {
						is_x = false
					}
				} else {
					if j == i || j == n-i-1 {
						if s[j] != diagonal {
							is_x = false
						}
					} else {
						if s[j] != blank {
							is_x = false
						}
					}
				}
			}
		}
	}

	if is_x {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import (
	"fmt"
)

func main() {
	var n, pos int
	var str string
	var charX, charR byte
	var set, valid bool

	fmt.Scan(&n)

	pos = 0
	set = false
	valid = true
	for i:=0; i<n; i++ {
		fmt.Scan(&str)

		if !set {
			charX = str[0]
			charR = str[1]
			if charX == charR {
				valid = false
			}
			set = true
		}

		for j:=0; j<len(str); j++ {
			if (j==pos || j == (len(str)-pos-1)) && str[j] != charX {
				valid = false
			}
			if (j != pos && j != (len(str)-pos-1)) && str[j] != charR {
				valid = false
			}
		}

		pos++
	}

	if valid {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

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

const maxn = 310

var s [maxn]string

func main() {
    scanner.Split(bufio.ScanWords)
    n := scanner.NextInt()
    ans := true
    for i := 0; i < n; i++ {
        s[i] = scanner.Next()
        for j := 0; j < n; j++ {
            if i == j || i+j == n-1 {
                if s[i][j] != s[0][0] {
                    ans = false
                }
            } else {
                if s[i][j] == s[0][0] {
                    ans = false
                }
                if s[i][j] != s[0][1] {
                    ans = false
                }
            }
        }
    }
    if ans {
        fmt.Println("YES")
    } else {
        fmt.Println("NO")
    }
}

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
}

func (self *Scanner) NextInt64() int64 {
    x, err := strconv.ParseInt(self.Next(), 10, 64)
    if err != nil {
        panic(err)
    }
    return x
}

func (self *Scanner) NextDouble() float64 {
    x, err := strconv.ParseFloat(self.Next(), 64)
    if err != nil {
        panic(err)
    }
    return x
}

// cf404a project main.go
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var s []string
	for i := 0; i < n; i++ {
		var t string
		fmt.Scan(&t)
		s = append(s, t)
	}
	x := s[0][0]
	o := s[0][1]
	flag := x != o
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if (i == j || i == n-j-1) && s[i][j] != x {

				flag = false
				break
			}
			if i != j && i != n-j-1 && s[i][j] != o {
				flag = false
				break
			}

		}
		if !flag {
			break
		}
	}
	if flag {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

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

	startIndex, endIndex := 0, n-1
	var otherLetter uint8

	for i:=0; i<n; i++ {
		line := next()

		if line[startIndex] != line[endIndex] {
			println("NO")
			return
		}

		if i==0 {
			if line[0] == line[1] {
				println("NO")
				return
			}

			otherLetter = line[1]
		}

		for j:=0; j<n; j++ {
			if j!=startIndex && j!=endIndex && line[j]!=otherLetter {
				println("NO")
				return
			}
		}
		startIndex++
		endIndex--
	}

	println("YES")
}

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 println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

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

package main

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

func main() {
	var n int // Odd
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	var is_x bool = true
	var diagonal rune
	var blank rune

	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < n; i++ {
		for j := 0; j <= n; j++ {
			if c, _, err := reader.ReadRune(); err != nil {
				if err == io.EOF {
					break
				} else {
					return
				}
			} else {
				if '\n' == c {
					continue
				} else if '\r' == c { // Read the following '\n'
					if _, _, err := reader.ReadRune(); err != nil {
						if err == io.EOF {
							break
						} else {
							return
						}
					}
					continue
				}

				if i == 0 && j == 0 {
					diagonal = c
				} else if i == 0 && j == 1 {
					blank = c
				} else {
					if j == i || j == n-i-1 {
						if c != diagonal {
							is_x = false
						}
					} else {
						if c != blank {
							is_x = false
						}
					}
				}
			}
		}
	}

	if is_x {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

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

func main() {
	var n int // Odd
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	var is_x bool = true
	var diagonal rune
	var blank rune

	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < n; i++ {
		for j := 0; j <= n; j++ {
			if c, _, err := reader.ReadRune(); err != nil {
				if err == io.EOF {
					break
				} else {
					return
				}
			} else {
				if '\n' != c {
					if i == 0 && j == 0 {
						diagonal = c
					} else if i == 0 && j == 1 {
						blank = c
					} else {
						if j == i || j == n-i-1 {
							if c != diagonal {
								is_x = false
							}
						} else {
							if c != blank {
								is_x = false
							}
						}
					}
				}
			}
		}
	}

	if is_x {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

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

func main() {
	var n int // Odd
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	var is_x bool = true
	var diagonal rune
	var blank rune

	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < n; i++ {
		for j := 0; j <= n; j++ {
			if c, _, err := reader.ReadRune(); err != nil {
				if err == io.EOF {
					break
				} else {
					return
				}
			} else {
				if '\n' != c && '\r' != c {
					if i == 0 && j == 0 {
						diagonal = c
					} else if i == 0 && j == 1 {
						blank = c
					} else {
						if j == i || j == n-i-1 {
							if c != diagonal {
								is_x = false
							}
						} else {
							if c != blank {
								is_x = false
							}
						}
					}
				}
			}
		}
	}

	if is_x {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

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

func main() {
	var n int // Odd
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	var is_x bool = true
	var diagonal rune
	var blank rune

	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < n; i++ {
		for j := 0; j <= n; j++ {
			if c, _, err := reader.ReadRune(); err != nil {
				if err == io.EOF {
					break
				} else {
					return
				}
			} else {
				if '\n' == c {
					continue
				} else if '\r' == c { // Read the following '\n'
					if _, _, err := reader.ReadRune(); err != nil {
						if err == io.EOF {
							break
						} else {
							return
						}
					}
				}

				if i == 0 && j == 0 {
					diagonal = c
				} else if i == 0 && j == 1 {
					blank = c
				} else {
					if j == i || j == n-i-1 {
						if c != diagonal {
							is_x = false
						}
					} else {
						if c != blank {
							is_x = false
						}
					}
				}
			}
		}
	}

	if is_x {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import "fmt"

func main() {
    var n int
    var s [305]string
    var x,y byte
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&s[i])
    }
    ans := true
    for i := 0; (i < n) && ans; i++ {
        for j := 0; j < n; j++ {
            if (i == j) || (i == (n-j-1)) {
                if x != 0 {
                    if x != s[i][j] { ans = false; break }
                } else {
                    x = s[i][j]
                }
            } else {
                if y != 0 {
                    if y != s[i][j] { ans = false; break }
                } else {
                    y = s[i][j]
                }
            }
        }
    }
    if ans { fmt.Println("YES") } else { fmt.Println("NO") }
}

// cf404a project main.go
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var s []string
	for i := 0; i < n; i++ {
		var t string
		fmt.Scan(&t)
		s = append(s, t)
	}
	x := s[0][0]
	o := s[0][1]
	flag := true
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if (i == j || i == n-j-1) && s[i][j] != x {

				flag = false
				break
			}
			if i != j && i != n-j-1 && s[i][j] != o {
				flag = false
				break
			}

		}
		if !flag {
			break
		}
	}
	if flag {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.

For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.

NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.

package main

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

func main () {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t, n, s, k, x int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &n, &s, &k)
		a := make(map[int]bool, n)
		for j := 0; j < k; j++ {
			fmt.Fscan(in, &x)
			a[x - 1] = true
		}
		for j := 0; j <= n; j++ {
			if (s - j - 1 >= 0 && !a[s - j - 1]) || (s + j - 1 < n && !a[s + j - 1]) {
				fmt.Fprintln(out, j)
				break
			}
		}
	}
}

package main

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

//=====I/O=====

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

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

func scanInt64() int64 {
	sc.Scan()
	a,_ := strconv.ParseInt(sc.Text(),10,64)
	return a
}

func scanFloat64() float64 {
	sc.Scan()
	a,_ := strconv.Atoi(sc.Text())
	return float64(a)
}

func scanInts(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ { res[i] = scanInt() }
	return res
}

func scanText() string {
	sc.Scan()
	return sc.Text()
}

func printInts(a ...int) {
	for i, e := range a {
		fmt.Fprint(wr, e)
		if i != len(a)-1 { fmt.Fprint(wr, " ") }
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

//•*¨*•.¸¸♪func•*¨*•.¸¸♪

//•*¨*•.¸¸♪main•*¨*•.¸¸♪

func main() {
	sc.Split(bufio.ScanWords)
	// sc.Buffer(make([]byte, 10000), 100000000)

	t := scanInt()

	for i := 0; i < t; i++ {
		n := scanInt()
		s := scanInt()-1
		k := scanInt()

		f := make(map[int]bool, n)
		for i := 0; i < k; i++ {
			a := scanInt()-1
			f[a] = true
		}

		// fmt.Println(f,s)

		p := 0
		for (s+p>=n||f[s+p]) && (s-p<0||f[s-p]) {
			p++
		}
		fmt.Println(p)
	}
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var n, s, k int
		fmt.Scan(&n, &s, &k)
		closed := make([]bool, 2000+100) // 上下1000階分調べれば十分
		now := len(closed) / 2           // 真ん中あたりにいるとする
		for j := 0; j < k; j++ {
			var v int
			fmt.Scan(&v) // v階のレストランは閉じている
			// 自分のフロアから見てどれだけ離れいてるか？
			d := v - s
			if 0 <= now+d && now+d < len(closed) {
				closed[now+d] = true
			}
		}
		// fmt.Println("n", n, "s", s, "k", k, "closed", closed)
		const inf = int(1e9) + 1
		mind := inf
		for j := 0; j < len(closed); j++ {
			if !closed[j] && 1 <= j-now+s && j-now+s <= n { // j階は空いている
				mind = min(mind, abs(j-now))
			}
		}
		fmt.Println(mind)
	}
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

package main

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

type Int64 []int64

func (u Int64) Len() int { return len(u) }

func (u Int64) Less(i, j int) bool { return u[i] < u[j] }

func (u Int64) Swap(i, j int) {
	u[i], u[j] = u[j], u[i]
}

func binSearch(a []int64, lo, hi int, key int64) bool {
	if lo > hi {
		return false
	}
	mid := lo + (hi-lo)/2
	if a[mid] == key {
		return true
	}
	if a[mid] > key {
		return binSearch(a, lo, mid-1, key)
	}
	return binSearch(a, mid+1, hi, key)
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var t, s, k int
	fmt.Fscanln(reader, &t)
	var n int64
	for i := 0; i < t; i++ {
		fmt.Fscanln(reader, &n, &s, &k)
		not_av := make([]int64, k)
		for j := 0; j < k-1; j++ {
			fmt.Fscanf(reader, "%d ", &not_av[j])
		}
		fmt.Fscanf(reader, "%d\n", &not_av[k-1])
		sort.Sort(Int64(not_av))
		if !binSearch(not_av, 0, k-1, int64(s)) {
			fmt.Fprintln(writer, 0)
			continue
		}
		ji := int64(s - 1)
		jj := int64(s + 1)
		for {
			if ji >= 1 && !binSearch(not_av, 0, k-1, ji) {
				fmt.Fprintln(writer, int64(s)-ji)
				break
			}
			if jj <= n && !binSearch(not_av, 0, k-1, jj) {
				fmt.Fprintln(writer, jj-int64(s))
				break
			}
			ji -= 1
			jj += 1
		}
	}
}

package main

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

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

	var t int
	fmt.Fscan(r, &t)
	for ; t > 0; t-- {
		var n int
		var s int
		var k int
		fmt.Fscan(r, &n, &s, &k)
		blocked := make(map[int]bool)
		for i := 0; i < k; i++ {
			var tmp int
			fmt.Fscan(r, &tmp)
			blocked[tmp] = true
		}
		for i := 0; i <= n; i++ {
			_, ok1 := blocked[s-i]
			_, ok2 := blocked[s+i]
			if (!ok1 && s-i > 0) || (!ok2 && s+i <= n) {
				fmt.Fprintln(w, i)
				break
			}
		}
	}
}

package main

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

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

	var t int
	fmt.Fscan(r, &t)
	for ; t > 0; t-- {
		var n int
		var s int
		var k int
		fmt.Fscan(r, &n, &s, &k)
		blocked := make(map[int]bool)
		for i := 0; i < k; i++ {
			var tmp int
			fmt.Fscan(r, &tmp)
			blocked[tmp] = true
		}
		for i := 0; i <= n; i++ {
			_, ok1 := blocked[s-i]
			_, ok2 := blocked[s+i]
			if (!ok1 && s-i > 0) || (!ok2 && s+i <= n) {
				fmt.Println(i)
				break
			}
		}
	}
}

package main

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

const (
	MAX_INT int64 = math.MaxInt64
	MIN_INT int64 = math.MinInt64
)

func main() {
	for t := ScanInt64(); t > 0; t-- {
		n, s, k := ScanInt64(), ScanInt64(), ScanInt64()
		a := ScanInt64Slice(int(k))

		m := make(map[int64]bool)
		for i := 0; i < int(k); i++ {
			m[a[i]] = true
		}

		minDiff := MAX_INT

		highFloor := MAX_INT
		lowFloor := MIN_INT
		for i := int64(0); s+i <= n; i++ {
			if _, ok := m[s+i]; !ok {
				highFloor = s + i
				break
			}
		}
		for i := int64(0); s-i > 0; i++ {
			if _, ok := m[s-i]; !ok {
				lowFloor = s - i
				break
			}
		}
		minDiff = Min(abs(s-lowFloor), abs(highFloor-s))
		fmt.Println(minDiff)
	}
	close(out)
	outWg.Wait()
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}
	return -a
}
func contains(a []int64, num int64) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == num {
			return true
		}
	}
	return false
}

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

var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(writer *bufio.Writer) {
		defer outWg.Done()
		defer writer.Flush()

		for line := range out {
			writer.WriteString(line + "\n")
		}
	}(writer)
}

func ScanWord() string {
	in.Scan()
	return in.Text()
}

func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}

func ScanInt64() int64 {
	intStr := ScanWord()
	i, err := strconv.ParseInt(intStr, 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

/*********************** Utils ***********************/

func Max(args ...int64) int64 {
	maxVal := MIN_INT
	for _, v := range args {
		if v > maxVal {
			maxVal = v
		}
	}
	return maxVal
}

func Min(args ...int64) int64 {
	minVal := MAX_INT
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
	}
	return minVal
}

func LCM(a, b int64) int64 {
	return a / GCD(a, b) * b
}

func GCD(a, b int64) int64 {
	if (a == 0) {
		return b
	}
	return GCD(b%a, a)
}

func iToS(v int64) string {
	return strconv.FormatInt(v, 10)
}

package main

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

var reader *bufio.Reader=bufio.NewReader(os.Stdin)
var writer *bufio.Writer=bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}){fmt.Fprintf(writer,f,a...)}
func scanf(f string,a...interface{}){fmt.Fscanf(reader,f,a...)}

var set = make(map[int]bool)
var n int

func eat(x int)bool{
	if x>0 && x<=n{
		if _,fd := set[x];!fd{
			return true
		}
	}
	return false
}

func main(){
	defer writer.Flush()
	var t,s,k,a int
	scanf("%d\n",&t)
	for cas:=1;cas<=t;cas++{
		scanf("%d%d%d\n",&n,&s,&k)
		set = make(map[int]bool)
		for i:=0;i<k;i++{
			scanf("%d",&a)
			set[a]=true
		}
		scanf("\n")
		for d:=0;d<n;d++{
			if eat(s+d) || eat(s-d) {
				printf("%d\n",d)
				break
			}
		}
	}
}

package main

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

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

	T := readInts(reader)[0]
	// fmt.Println(T)
	for t := 0; t < T; t++ {
		inp := readInts(reader)
		N, S, K := inp[0], inp[1], inp[2]

		CS := readInts(reader)
		mmap := make(map[int]bool, K)
		for _, cs := range CS {
			mmap[cs] = true
		}

		x := findLeft(S, mmap)
		y := findRight(S, N, mmap)

		fmt.Println(minInt(absInt(S-x), absInt(y-S)))
	}
}

func findLeft(x int, mmap map[int]bool) int {
	for i := x; i >= 1; i-- {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

func findRight(x, N int, mmap map[int]bool) int {
	for i := x; i <= N; i++ {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

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

	return y
}

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

	return x
}

func readInts(reader *bufio.Reader) []int {
	// fmt.Println("readInts being called.....")
	text, err := reader.ReadString('\n')
	if err != nil {
		fmt.Println(err.Error())
	}
	// fmt.Println("~~~~~~", text)
	inputs := strings.Split(strings.TrimSuffix(strings.TrimSuffix(text, "\n"), "\r"), " ")

	temp := make([]int, len(inputs))
	for i := 0; i < len(inputs); i++ {
		temp[i], err = strconv.Atoi(inputs[i])
		if err != nil {
			fmt.Println(err.Error())
		}
	}

	// fmt.Println(temp)
	return temp
}

package main

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

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

	var t int
	fmt.Fscan(r, &t)
	ans := make([]int, t)
	for i := 0; i < t; i++ {
		var n, s, a int
		fmt.Fscan(r, &n, &s, &a)
		m := make([]int, a)
		for j := 0; j < a; j++ {
			fmt.Fscan(r, &m[j])
		}
		sort.Ints(m)
		p := sort.SearchInts(m, s)
		if p < a && m[p] == s {
			down := p
			up := p
			for ; down > 0; down-- {
				if m[down]-m[down-1] > 1 {
					break
				}
			}
			for ; up < a-1; up++ {
				if m[up+1]-m[up] > 1 {
					break
				}
			}
			l := n
			if m[up] < n {
				l = m[up] - s + 1
			}
			if m[down] > 1 && s-m[down]+1 < l {
				l = s - m[down] + 1
			}
			ans[i] = l
		} else {
			ans[i] = 0
		}

		// if p < a && m[p] != s {
		// 	ans[i] = "0"
		// } else {
		// 	flag := true
		// 	for j := 0; p-j > 0 || p+j < a-1; j++ {
		// 		if p-j > 0 && m[p-j]-m[p-j-1] > 1 {
		// 			ans[i] = strconv.Itoa(s - m[p-j])
		// 			flag = false
		// 			break
		// 		}
		// 		if p+j < a-1 && m[p+j+1]-m[p+j] > 1 {
		// 			ans[i] = strconv.Itoa(m[p+j] + 1 - s)
		// 			flag = false
		// 			break
		// 		}
		// 	}
		// 	if flag {

		// 		if m[0] > 1 && m[a-1] < n {
		// 			if s-m[0] < m[a-1]-s {
		// 				ans[i] = strconv.Itoa(s - m[0] + 1)
		// 			} else {
		// 				ans[i] = strconv.Itoa(m[a-1] - s + 1)
		// 			}
		// 		} else if m[0] > 1 {
		// 			ans[i] = strconv.Itoa(s - m[0] + 1)
		// 		} else if m[a-1] < n {
		// 			ans[i] = strconv.Itoa(m[a-1] - s + 1)
		// 		}
		// 	}
		//}
	}
	res := make([]string, t)
	for i, e := range ans {
		res[i] = strconv.Itoa(e)
	}
	fmt.Fprintln(w, strings.Join(res, "\n"))

}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var t, s, k, ip, ji, jj int
	fmt.Fscanln(reader, &t)
	var n int64
	for i := 0; i < t; i++ {
		fmt.Fscanln(reader, &n, &s, &k)
		not_av := make([]bool, 1001)
		for j := 0; j < k-1; j++ {
			fmt.Fscanf(reader, "%d ", &ip)
			not_av[ip] = true
		}
		fmt.Fscanf(reader, "%d\n", &ip)
		not_av[ip] = true
		if !not_av[s] {
			fmt.Fprintln(writer, 0)
			continue
		}
		ji = s - 1
		jj = s + 1
		for ji >= 1 || jj <= 1000 {
			if ji >= 1 && !not_av[ji] {
				fmt.Fprintln(writer, s-ji)
				break
			}
			if jj <= 1000 && !not_av[jj] {
				fmt.Fprintln(writer, jj-s)
				break
			}
			ji -= 1
			jj += 1
		}
	}
}

package main

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

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

	var t int
	fmt.Fscan(r, &t)
	for ; t > 0; t-- {
		var n int
		var s int
		var k int
		fmt.Fscan(r, &n, &s, &k)
		blocked := make(map[int]bool)
		for i := 0; i < k; i++ {
			var tmp int
			fmt.Fscan(r, &tmp)
			blocked[tmp] = true
		}
		for i := 0; i <= n; i++ {
			_, ok1 := blocked[s-i]
			_, ok2 := blocked[s+i]
			if (!ok1 && s-i > 0) || (!ok2 && s+i <= n) {
				fmt.Fprint(w, i)
				break
			}
		}
	}
}

package main

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

const (
   MAX_INT int64 = math.MaxInt64
   MIN_INT int64 = math.MinInt64
)

//func main() {
// n := ScanInt64()
// //𝐻𝑛=𝑙𝑛(𝑛)+0.5772156649
//
// hn := 0.5772156649 + math.Log2(float64(n))
// fmt.Println(hn)
//
// close(out)
// outWg.Wait()
//}

func main() {
   for t := ScanInt64(); t > 0; t-- {
      _, s1, k := ScanInt64(), ScanInt64(), ScanInt64()
      a := ScanInt64Slice(int(k))
      fmt.Println(markLand(s1, a))
   }
}

func markLand(inTheFloor int64, a []int64) int64 {
   if !contains(a, inTheFloor) {
      return 0
   }

   leftMax := make([]int64, len(a))
   for i := 1; i < len(a); i++ {
      leftMax[i] = Max(leftMax[i-1], a[i-1])
   }
   rightMin, element := MAX_INT, int64(0)
   for i := len(a) - 1; i >= 0; i-- {
      if (leftMax[i] < a[i] && rightMin > a[i]) {
         element = a[i]
         break
      }
      rightMin = Min(rightMin, a[i])
   }
   if element == 0 {
      return 0

   } else if element-1 == inTheFloor {
      return ((element + 1) - inTheFloor)
   } else {
      return (element - 1 - inTheFloor)

   }

}

func contains(a []int64, num int64) bool {
   for i := 0; i < len(a); i++ {
      if a[i] == num {
         return true
      }
   }
   return false
}

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

var in *bufio.Scanner

func init() {
   in = bufio.NewScanner(os.Stdin)
   in.Split(bufio.ScanWords)
}

func ScanWord() string {
   in.Scan()
   return in.Text()
}

func ScanStringSlice(n int) []string {
   s := make([]string, n)
   for i := 0; i < n; i++ {
      s[i] = ScanWord()
   }
   return s
}

func ScanInt64() int64 {
   intStr := ScanWord()
   i, err := strconv.ParseInt(intStr, 10, 64)
   if err != nil {
      panic(err)
   }
   return i
}

func ScanInt64Slice(n int) []int64 {
   arr := make([]int64, n)
   for i := 0; i < n; i++ {
      arr[i] = ScanInt64()
   }
   return arr
}

/*********************** Utils ***********************/

func Max(args ...int64) int64 {
   maxVal := MIN_INT
   for _, v := range args {
      if v > maxVal {
         maxVal = v
      }
   }
   return maxVal
}

func Min(args ...int64) int64 {
   minVal := MAX_INT
   for _, v := range args {
      if v < minVal {
         minVal = v
      }
   }
   return minVal
}

func s(val interface{}) string {
   return fmt.Sprintf("%v", val)
}

package main

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

var reader *bufio.Reader=bufio.NewReader(os.Stdin)
var writer *bufio.Writer=bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}){fmt.Fprintf(writer,f,a...)}
func scanf(f string,a...interface{}){fmt.Fscanf(reader,f,a...)}

var set = make(map[int]bool)

func eat(x int)bool{
	if x>0 {
		if _,fd := set[x];!fd{
			return true
		}
	}
	return false
}

func main(){
	defer writer.Flush()
	var t,n,s,k,a int
	scanf("%d\n",&t)
	for cas:=1;cas<=t;cas++{
		scanf("%d%d%d\n",&n,&s,&k)
		set = make(map[int]bool)
		for i:=0;i<k;i++{
			if i<k-1 {
				scanf("%d",&a)
			}else{
				scanf("%d\n",&a)
			}
			set[a]=true
		}
		for d:=0;d<n;d++{
			if eat(s+d) || eat(s-d) {
				printf("%d\n",d)
				break
			}
		}
	}
}

package main

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

func main() {
	T := readInts()[0]
	fmt.Println("test cases: ", T)
	for t := 0; t < T; t++ {
		inp := readInts()
		N, S, K := inp[0], inp[1], inp[2]

		CS := readInts()
		mmap := make(map[int]bool, K)
		for _, cs := range CS {
			mmap[cs] = true
		}

		x := findLeft(S, mmap)
		y := findRight(S, N, mmap)

		fmt.Println(minInt(absInt(S-x), absInt(y-S)))
	}
}

func findLeft(x int, mmap map[int]bool) int {
	for i := x; i >= 1; i-- {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

func findRight(x, N int, mmap map[int]bool) int {
	for i := x; i <= N; i++ {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

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

	return y
}

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

	return x
}

func readInts() []int {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	inputs := strings.Split(strings.TrimSuffix(text, "\n"), " ")

	temp := make([]int, len(inputs))
	for i := 0; i < len(inputs); i++ {
		temp[i], _ = strconv.Atoi(inputs[i])
	}

	return temp
}

package main

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

func main() {
	T := readInts()[0]
	for t := 0; t < T; t++ {
		inp := readInts()
		N, S, K := inp[0], inp[1], inp[2]

		CS := readInts()
		mmap := make(map[int]bool, K)
		for _, cs := range CS {
			mmap[cs] = true
		}

		x := findLeft(S, mmap)
		y := findRight(S, N, mmap)

		fmt.Println(minInt(absInt(S-x), absInt(y-S)))
	}
}

func findLeft(x int, mmap map[int]bool) int {
	for i := x; i >= 1; i-- {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

func findRight(x, N int, mmap map[int]bool) int {
	for i := x; i <= N; i++ {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

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

	return y
}

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

	return x
}

func readInts() []int {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	inputs := strings.Split(strings.TrimSuffix(text, "\n"), " ")

	temp := make([]int, len(inputs))
	for i := 0; i < len(inputs); i++ {
		temp[i], _ = strconv.Atoi(inputs[i])
	}

	return temp
}

package main

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

func main() {
	T := readInts()[0]
	fmt.Println(T)
	for t := 0; t < T; t++ {
		inp := readInts()
		N, S, K := inp[0], inp[1], inp[2]

		CS := readInts()
		mmap := make(map[int]bool, K)
		for _, cs := range CS {
			mmap[cs] = true
		}

		x := findLeft(S, mmap)
		y := findRight(S, N, mmap)

		fmt.Println(minInt(absInt(S-x), absInt(y-S)))
	}
}

func findLeft(x int, mmap map[int]bool) int {
	for i := x; i >= 1; i-- {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

func findRight(x, N int, mmap map[int]bool) int {
	for i := x; i <= N; i++ {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

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

	return y
}

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

	return x
}

func readInts() []int {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	inputs := strings.Split(strings.TrimSuffix(text, "\n"), " ")

	temp := make([]int, len(inputs))
	for i := 0; i < len(inputs); i++ {
		temp[i], _ = strconv.Atoi(inputs[i])
	}

	return temp
}

package main

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

func main() {
	T := readInts()[0]
	for t := 0; t < T; t++ {
		inp := readInts()
		N, S, K := inp[0], inp[1], inp[2]

		CS := readInts()
		mmap := make(map[int]bool, K)
		for _, cs := range CS {
			mmap[cs] = true
		}

		x := findLeft(S, mmap)
		y := findRight(S, N, mmap)

		fmt.Println(minInt(S-x, y-S))
	}
}

func findLeft(x int, mmap map[int]bool) int {
	for i := x; i >= 1; i-- {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

func findRight(x, N int, mmap map[int]bool) int {
	for i := x; i <= N; i++ {
		if _, ok := mmap[i]; !ok {
			return i
		}
	}

	return math.MaxInt32
}

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

	return y
}

func readInts() []int {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	inputs := strings.Split(text, " ")
	temp := make([]int, len(inputs))
	for i := 0; i < len(inputs); i++ {
		temp[i], _ = strconv.Atoi(inputs[i])
	}

	return temp
}


You are given two arrays of integers $$$a_1,a_2,\dots,a_n$$$ and $$$b_1,b_2,\dots,b_m$$$. Alice and Bob are going to play a game. Alice moves first and they take turns making a move.They play on a grid of size $$$n \times m$$$ (a grid with $$$n$$$ rows and $$$m$$$ columns). Initially, there is a rook positioned on the first row and first column of the grid.During her/his move, a player can do one of the following two operations:  Move the rook to a different cell on the same row or the same column of the current cell. A player cannot move the rook to a cell that has been visited $$$1000$$$ times before (i.e., the rook can stay in a certain cell at most $$$1000$$$ times during the entire game). Note that the starting cell is considered to be visited once at the beginning of the game. End the game immediately with a score of $$$a_r+b_c$$$, where $$$(r, c)$$$ is the current cell (i.e., the rook is on the $$$r$$$-th row and $$$c$$$-th column). Bob wants to maximize the score while Alice wants to minimize it. If they both play this game optimally, what is the final score of the game?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n,m \leq 2 \cdot 10^5$$$) — the length of the arrays $$$a$$$ and $$$b$$$ (which coincide with the number of rows and columns of the grid). The second line contains the $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 5 \cdot 10^8$$$). The third line contains the $$$m$$$ integers $$$b_1, b_2,\dots, b_n$$$ ($$$1 \leq b_i \leq 5 \cdot 10^8$$$).

Print a single line containing the final score of the game.

NoteIn the first test case, Alice moves the rook to $$$(2, 1)$$$ and Bob moves the rook to $$$(1, 1)$$$. This process will repeat for $$$999$$$ times until finally, after Alice moves the rook, Bob cannot move it back to $$$(1, 1)$$$ because it has been visited $$$1000$$$ times before. So the final score of the game is $$$a_2+b_1=4$$$.In the second test case, the final score of the game is $$$a_3+b_5$$$.

package main

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

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

	n, m := readTwoNums(reader)
	A := readNNums(reader, n)
	B := readNNums(reader, m)
	res := solve(A, B)
	fmt.Println(res)
}

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

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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(a []int, b []int) int {
	m := len(a)
	n := len(b)
	A := make([]int, m+1)
	B := make([]int, n+1)
	copy(A[1:], a)
	copy(B[1:], b)

	sort.Ints(A)
	sort.Ints(B)

	da := make([]int, m+1)
	db := make([]int, n+1)

	va := sort.SearchInts(A, a[0])
	vb := sort.SearchInts(B, b[0])

	check := func(x int) bool {
		var sum int64

		for j, i := n, 0; j > 0; j-- {
			for i < m && A[i+1]+B[j] <= x {
				i++
			}
			db[j] = i
			sum += int64(i)
		}

		for i, j := m, 0; i > 0; i-- {
			for j < n && A[i]+B[j+1] <= x {
				j++
			}
			da[i] = j
		}

		f1 := sum
		f2 := sum

		for i, j := m, n; i >= 1; i-- {
			sum -= int64(min(j, da[i]))
			sum += int64(n - max(j, da[i]))
			f1 = max(f1, sum)
			f2 = max(f2, sum-boolValue(i <= va)*boolValue(j < vb))
			for j > 0 && min(db[j], i-1) <= m-max(db[j], i-1) {
				sum -= int64(min(db[j], i-1))
				sum += int64(m - max(db[j], i-1))
				j--
				f1 = max(f1, sum)
				f2 = max(f2, sum-boolValue(i <= va)*boolValue(j < vb))
			}
		}

		return f1 == f2
	}

	l := A[1] + B[1]
	r := a[0] + b[0]

	for l < r {
		mid := (l + r) / 2
		if check(mid) {
			r = mid
		} else {
			l = mid + 1
		}
	}

	return r
}

type Number interface {
	int64 | int
}

func min[T Number](a T, b T) T {
	if a <= b {
		return a
	}
	return b
}

func max[T Number](a, b T) T {
	if a >= b {
		return a
	}
	return b
}

func boolValue(a bool) int64 {
	if a {
		return 1
	}
	return 0
}

package main

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

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

	n, m := readTwoNums(reader)
	A := readNNums(reader, n)
	B := readNNums(reader, m)
	res := solve(A, B)
	fmt.Println(res)
}

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

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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(a []int, b []int) int {
	m := len(a)
	n := len(b)
	A := make([]int, m+1)
	B := make([]int, n+1)
	copy(A[1:], a)
	copy(B[1:], b)

	sort.Ints(A)
	sort.Ints(B)

	da := make([]int, m+1)
	db := make([]int, n+1)

	va := sort.SearchInts(A, a[0])
	vb := sort.SearchInts(B, b[0])

	check := func(x int) bool {
		var sum int64

		for j, i := n, 0; j > 0; j-- {
			for i < m && A[i+1]+B[j] <= x {
				i++
			}
			db[j] = i
			sum += int64(i)
		}

		for i, j := m, 0; i > 0; i-- {
			for j < n && A[i]+B[j+1] <= x {
				j++
			}
			da[i] = j
		}

		f1 := sum
		f2 := sum

		for i, j := m, n; i >= 1; i-- {
			sum -= int64(min(j, da[i]))
			sum += int64(n - max(j, da[i]))
			f1 = max(f1, sum)
			f2 = max(f2, sum-boolValue(i <= va)*boolValue(j < vb))
			for j > 0 && min(db[j], i-1) <= n-max(db[j], i-1) {
				sum -= int64(min(db[j], i-1))
				sum += int64(m - max(db[j], i-1))
				j--
				f1 = max(f1, sum)
				f2 = max(f2, sum-boolValue(i <= va)*boolValue(j < vb))
			}
		}

		return f1 == f2
	}

	l := A[1] + B[1]
	r := a[0] + b[0]

	for l < r {
		mid := (l + r) / 2
		if check(mid) {
			r = mid
		} else {
			l = mid + 1
		}
	}

	return r
}

type Number interface {
	int64 | int
}

func min[T Number](a T, b T) T {
	if a <= b {
		return a
	}
	return b
}

func max[T Number](a, b T) T {
	if a >= b {
		return a
	}
	return b
}

func boolValue(a bool) int64 {
	if a {
		return 1
	}
	return 0
}

package main

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

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

	n, m := readTwoNums(reader)
	A := readNNums(reader, n)
	B := readNNums(reader, m)
	res := solve(A, B)
	fmt.Println(res)
}

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

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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(a []int, b []int) int {
	m := len(a)
	n := len(b)
	A := make([]int, m+1)
	B := make([]int, n+1)
	copy(A[1:], a)
	copy(B[1:], b)

	sort.Ints(A)
	sort.Ints(B)

	da := make([]int, m+1)
	db := make([]int, n+1)

	va := sort.SearchInts(A, a[0])
	vb := sort.SearchInts(B, b[0])

	check := func(x int) bool {
		var sum int

		for j, i := n, 0; j > 0; j-- {
			for i < m && A[i+1]+B[j] <= x {
				i++
			}
			db[j] = i
			sum += i
		}

		for i, j := m, 0; i > 0; i-- {
			for j < n && A[i]+B[j+1] <= x {
				j++
			}
			da[i] = j
		}

		f1 := sum
		f2 := sum

		for i, j := m, n; i >= 1; i-- {
			sum -= min(j, da[i])
			sum += n - max(j, da[i])
			f1 = max(f1, sum)
			f2 = max(f2, sum-boolValue(i <= va)*boolValue(j < vb))
			for j > 0 && min(db[j], i-1) <= n-max(db[j], i-1) {
				sum -= min(db[j], i-1)
				sum += m - max(db[j], i-1)
				j--
				f1 = max(f1, sum)
				f2 = max(f2, sum-boolValue(i <= va)*boolValue(j < vb))
			}
		}

		return f1 == f2
	}

	l := A[1] + B[1]
	r := a[0] + b[0]

	for l < r {
		mid := (l + r) / 2
		if check(mid) {
			r = mid
		} else {
			l = mid + 1
		}
	}

	return r
}

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

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

func boolValue(a bool) int {
	if a {
		return 1
	}
	return 0
}


You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $$$t$$$, then for each $$$i, j$$$ such that $$$t_i = t_j$$$ should be satisfied $$$|i-j|~ mod~ 3 = 0$$$. The value $$$|x|$$$ means absolute value of $$$x$$$, the operation $$$x~ mod~ y$$$ means remainder of $$$x$$$ when divided by $$$y$$$.For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' — colors of lamps in the garland.

In the first line of the output print one integer $$$r$$$ — the minimum number of recolors needed to obtain a nice garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ — a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

package main

import "fmt"
import "math"

var plans = []string{
	"RGB",
	"RBG",
	"GRB",
	"GBR",
	"BGR",
	"BRG",
}

func main() {
	var n int
	var minLamps []byte
	var lamps []byte
	fmt.Scanf("%d\n", &n)
	fmt.Scanf("%s\n", &lamps)

	var minCount int = math.MaxInt32
	for _, plan := range plans {
		count := 0
		tempLamps := make([]byte, len(lamps))
		copy(tempLamps, lamps)
		for i := 0; i < len(tempLamps); i++ {
			shouldBe := plan[i%3]
			if tempLamps[i] != shouldBe {
				tempLamps[i] = shouldBe
				count++
			}
		}

		if count < minCount {
			minCount = count
			minLamps = tempLamps
		}
	}

	fmt.Println(minCount)
	fmt.Println(string(minLamps))

}

package main

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

var (
	mod int64 = 1000000007
)

func range3(l int64) []int64 {
	ans := make([]int64, 3)
	ans[0] = l / 3
	ans[1] = (l + 2) / 3
	ans[2] = (l + 1) / 3
	return ans
}
func solve(s, t []byte, n int) ([]byte, int) {
	res := make([]byte, n)
	cnt := 0
	f := 0
	for i := 0; i < n; i++ {
		if s[i] != t[f] {
			cnt++
		}
		res[i] = t[f]
		f++
		if f > 2 {
			f = 0
		}
	}
	return res, cnt
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(buf, "%d\n", &n)
	str := make([]byte, n+1)
	fmt.Fscanf(buf, "%s\n", &str)
	cnt:=-1
	var s []byte
	loop :=make([][]byte,9)
	loop[0] = []byte("BRG")
	loop[1] = []byte("BGR")
	loop[2] = []byte("RBG")
	loop[3] = []byte("RGB")
	loop[4] = []byte("GRB")
	loop[5] = []byte("GBR")
	for i:=0;i < 6;i++{
		tmp, c := solve(str, loop[i], n)
		if cnt == -1 || cnt > c{
			cnt = c
			s = tmp
		}
	}
	fmt.Printf("%d\n",cnt)
	fmt.Printf("%s\n",s)
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var T int
	fmt.Scanf("%d\n", &T)
	var s string
	fmt.Scanf("%s\n",&s)
	var anss string
	minc := math.MaxInt32
	check("RGB", s, &anss, &minc)
	check("RBG", s, &anss, &minc)
	check("GRB", s, &anss, &minc)
	check("GBR", s, &anss, &minc)
	check("BRG", s, &anss, &minc)
	check("BGR", s, &anss, &minc)
	print(anss, minc, len(s))

}

func print(ss string, ans int, leng int){
	fmt.Printf("%d\n", ans)
	for i := 0; i < leng; i+=3 {
		if i + 3 <= leng{
			fmt.Printf("%s", ss)
		}
	}
	leng %= 3
	for i := 0; i < leng; i++ {
		fmt.Printf("%c", ss[i % 3])
	}
	fmt.Printf("\n")
}

func check(ss string, s string, anss *string, minc *int){
	ans := 0
	for e := range s {
		if s[e] != ss[e % 3] {
			ans++
		}
		if ans >= *minc{
			return
		}
	}
	if ans < *minc {
		*minc = ans
		*anss = ss
	}
}

package main

import "fmt"
import "math"

var plans = []string{
	"RGB",
	"RBG",
	"GRB",
	"GBR",
	"BGR",
	"BRG",
}

func main() {
	var n int
	var minLamps []byte
	var lamps []byte
	fmt.Scanf("%d", &n)
	fmt.Scanf("%s", &lamps)

	var minCount int = math.MaxInt32
	for _, plan := range plans {
		count := 0
		tempLamps := make([]byte, len(lamps))
		copy(tempLamps, lamps)
		for i := 0; i < len(tempLamps); i++ {
			shouldBe := plan[(i)%3]
			if tempLamps[i] != shouldBe {
				tempLamps[i] = shouldBe
				count++
			}
		}

		if count < minCount {
			minCount = count
			minLamps = tempLamps
		}
	}

	fmt.Println(minCount)
	fmt.Println(string(minLamps))

}

package main

import "fmt"
import "math"

var plans = []string{
	"RGB",
	"RBG",
	"GRB",
	"GBR",
	"BGR",
	"BRG",
}

func main() {
	var n int
	var minLamps []byte
	var lamps []byte
	fmt.Scanf("%d", &n)
	fmt.Scanf("%s", &lamps)

	var minCount int = math.MaxInt32
	for _, plan := range plans {
		count := 0
		tempLamps := make([]byte, len(lamps))
		copy(tempLamps, lamps)
		for i := 0; i < len(tempLamps); i++ {
			shouldBe := plan[(i)%3]
			if tempLamps[i] != shouldBe {
				tempLamps[i] = shouldBe
				count++
			}
		}

		if count < minCount {
			minCount = count
			minLamps = tempLamps
		}
	}

	fmt.Printf("%d\n%s", minCount, minLamps)

}

package main

import "fmt"
import "math"

var plans = []string{
	"RGB",
	"RBG",
	"GRB",
	"GBR",
	"BGR",
	"BRG",
}

func main() {
	var n int
	var minLamps []byte
	var lamps []byte
	fmt.Scanf("%d", &n)
	fmt.Scanf("%s", &lamps)

	var minCount int = math.MaxInt32
	for _, plan := range plans {
		count := 0
		tempLamps := make([]byte, len(lamps))
		copy(tempLamps, lamps)
		for i := 0; i < len(tempLamps); i++ {
			shouldBe := plan[(i)%3]
			if tempLamps[i] != shouldBe {
				tempLamps[i] = shouldBe
				count++
			}
		}

		if count < minCount {
			minCount = count
			minLamps = tempLamps
		}
	}

	fmt.Println(minCount)
	fmt.Println(minLamps)

}

package main

import (
	"fmt"
	"math"
)

func main() {
	var T int
	fmt.Scanf("%d\n", &T)
	var s string
	fmt.Scanf("%s\n",&s)
	var anss string
	minc := math.MaxInt32
	check("RGB", s, &anss, &minc)
	check("RBG", s, &anss, &minc)
	check("GRB", s, &anss, &minc)
	check("GBR", s, &anss, &minc)
	check("BRG", s, &anss, &minc)
	check("BGR", s, &anss, &minc)
	print(anss, minc, len(s))

}

func print(ss string, ans int, leng int){
	fmt.Printf("%d\n", ans)
	for i := 0; i < leng; i+=3 {
		if i + 3 < leng{
			fmt.Printf("%s", ss)
		}
	}
	leng %= 3
	for i := 0; i < leng; i++ {
		fmt.Printf("%c", ss[i % 3])
	}
	fmt.Printf("\n")
}

func check(ss string, s string, anss *string, minc *int){
	ans := 0
	for e := range s {
		if s[e] != ss[e % 3] {
			ans++
		}
		if ans >= *minc{
			return
		}
	}
	if ans < *minc {
		*minc = ans
		*anss = ss
	}
}


Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.

The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.  The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world. The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi. It is guaranteed that the graph described by the input is stable.

Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.

NoteFor the first sample test, the graph looks like this:    Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this:    We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.

package main

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

func solve() {
    n, m, k := readInt(), readInt(), readInt()
    c := readIntArray(k)
    a := make([][]int, n)
    for i := 0; i < m; i++ {
        u, v := readInt()-1, readInt()-1
        a[u] = append(a[u], v)
        a[v] = append(a[v], u)
    }

    was := make([]bool, n)
    govs := make([][]int, n)
    mxGov, mxCnt := 0, 0
    for _, gov := range c {
        gov--
        q := []int{gov}
        was[gov] = true
        for len(q) > 0 {
            cur := q[0]
            q, govs[gov] = q[1:], append(govs[gov], cur)
            for _, v := range a[cur] {
                if !was[v] {
                    was[v] = true
                    q = append(q, v)
                }
            }
        }
        if ln := len(govs[gov]); ln > mxCnt {
            mxCnt = ln
            mxGov = gov
        }
    }

    free := []int{}
    for v, b := range was {
        if !b {
            free = append(free, v)
        }
    }

    ans := 0
    for gov, l := range govs {
        if gov == mxGov {
            l = append(l, free...)
        }

        has := 0
        for _, v := range l {
            has += len(a[v])
        }
        has /= 2

        cnt := len(l)
        ans += cnt*(cnt-1)/2 - has
    }
    fmt.Println(ans)
}

// Helpers

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func main() {
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// Math

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

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

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

// IO

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

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

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

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

// Sort

type Ints64 []int64

func (a Ints64) Len() int           { return len(a) }
func (a Ints64) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a Ints64) Less(i, j int) bool { return a[i] < a[j] }

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

var v [][]int

func DFS(node int, flag *[]int) (int, int){
  (*flag)[node] = 1
  nodes := 1
  edges := 0
  for i := 0; i < len(v[node]); i++ {
    next := v[node][i]
    if (*flag)[next] == 0 {
      nn, ne := DFS(next, flag)
      nodes += nn
      edges += ne
    }
    edges++
  }
  return nodes, edges
}

func main() {
  var n, m, k int
  in := bufio.NewReader(os.Stdin)
  fmt.Fscan(in, &n, &m, &k)
  govs := make([]int, k)
  for i := 0; i < k; i++ {
    fmt.Fscan(in, &govs[i])
    govs[i]--
  }
  v = make([][]int, n)
  for i := 0; i < m; i++ {
    var from, to int
    fmt.Fscan(in, &from, &to)
    from--
    to--
    v[from] = append(v[from], to)
    v[to] = append(v[to], from)
  }
  ans := 0
  maxnode := 0
  left := n
  lefte := m
  for i := 0; i < k; i++ {
    flag := make([]int, n)
    nodes, edges := DFS(govs[i], &flag)
    if nodes > maxnode {
      maxnode = nodes
    }
    lefte -= edges / 2
    left -= nodes
    ans += (nodes * (nodes - 1) - edges) / 2
  }
  ans += (left * (left - 1)) / 2 - lefte
  ans += left * maxnode
  fmt.Println(ans)
}

package main

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

type component struct {
	nodes, edges int
}

var n, m, k int
var graph [][]int
var specials map[int]bool
var used []bool
var components []component

func bfs(v int) component {
	nodes := 0
	edges := 0
	q := []int{v}
	used[v] = true

	for len(q) > 0 {
		nodes++
		t := q[0]
		q = q[1:]
		for _, vnext := range graph[t] {
			edges++
			if !used[vnext] {
				q = append(q, vnext)
				used[vnext] = true
			}
		}
	}

	return component{
		nodes: nodes,
		edges: edges / 2,
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d %d\n", &n, &m, &k)
	specials = make(map[int]bool)
	graph = make([][]int, n + 1)
	used = make([]bool, n + 1)
	components = make([]component, n + 1)
	for i := 0; i < k; i++ {
		var tmp int
		fmt.Fscanf(buf, "%d", &tmp)
		specials[tmp] = true
	}
	fmt.Fscanf(buf, "\n")
	for i := 0; i < m; i++ {
		var v1, v2 int
		fmt.Fscanf(buf, "%d %d\n", &v1, &v2)
		graph[v1] = append(graph[v1], v2)
		graph[v2] = append(graph[v2], v1)
	}

	maxNodesInComponent := 0
	componentSpecial := 0
	ans := 0
	for v, _ := range specials {
		components[v] = bfs(v)
		if components[v].nodes > maxNodesInComponent {
			maxNodesInComponent = components[v].nodes
			componentSpecial = v
		}
		ans += components[v].nodes * (components[v].nodes - 1) / 2 - components[v].edges
	}

	for i := 1; i <= n; i++ {
		if !specials[i] && !used[i] {
			c := bfs(i)
			ans += c.nodes * (c.nodes - 1) / 2 - c.edges
			ans += c.nodes * components[componentSpecial].nodes
			components[componentSpecial].nodes += c.nodes
		}
	}
	fmt.Println(ans)
}

package main

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

func solve() {
    n, m, k := readInt(), readInt(), readInt()
    c := readIntArray(k)
    a := make([][]int, n)
    for i := 0; i < m; i++ {
        u, v := readInt()-1, readInt()-1
        a[u] = append(a[u], v)
        a[v] = append(a[v], u)
    }

    was := make([]bool, n)
    govs := make([][]int, n)
    mxGov, mxCnt := 0, 0
    for _, gov := range c {
        gov--
        q := []int{gov}
        was[gov] = true
        for len(q) > 0 {
            cur := q[0]
            q, govs[gov] = q[1:], append(govs[gov], cur)
            for _, v := range a[cur] {
                if !was[v] {
                    was[v] = true
                    q = append(q, v)
                }
            }
        }
        if ln := len(govs[gov]); ln > mxCnt {
            mxCnt = ln
            mxGov = gov
        }
    }

    free := 0
    for _, b := range was {
        if !b {
            free++
        }
    }

    ans := 0
    for gov, l := range govs {
        cnt := len(l)
        if gov == mxGov {
            cnt += free
        }

        has := 0
        for _, v := range l {
            has += len(a[v])
        }
        has /= 2

        ans += cnt*(cnt-1) / 2 - has
    }
    fmt.Println(ans)
}

// Helpers

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func main() {
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// Math

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

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

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

// IO

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

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

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

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

// Sort

type Ints64 []int64

func (a Ints64) Len() int           { return len(a) }
func (a Ints64) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a Ints64) Less(i, j int) bool { return a[i] < a[j] }

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

func DFS(node int, flag *[]int, v *[][]int) (int, int){
  (*flag)[node] = 1
  nodes := 1
  edges := 0
  for i := 0; i < len((*v)[node]); i++ {
    next := (*v)[node][i]
    if (*flag)[next] == 0 {
      nn, ne := DFS(next, flag, v)
      nodes += nn
      edges += ne
    }
    edges++
  }
  return nodes, edges
}

func main() {
  var n, m, k int
  in := bufio.NewReader(os.Stdin)
  fmt.Fscan(in, &n, &m, &k)
  govs := make([]int, k)
  for i := 0; i < k; i++ {
    fmt.Fscan(in, &govs[i])
    govs[i]--
  }
  v := make([][]int, n)
  for i := 0; i < m; i++ {
    var from, to int
    fmt.Fscan(in, &from, &to)
    from--
    to--
    v[from] = append(v[from], to)
    v[to] = append(v[to], from)
  }
  ans := 0
  maxnode := 0
  left := n
  for i := 0; i < k; i++ {
    flag := make([]int, n)
    nodes, edges := DFS(govs[i], &flag, &v)
    if nodes > maxnode {
      maxnode = nodes
    }
    left -= nodes
    ans += (nodes * (nodes - 1) - edges) / 2
  }
  ans += (left * (left - 1)) / 2
  ans += left * maxnode
  fmt.Println(ans)
}

package main

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

type component struct {
	nodes, edges int
}

var n, m, k int
var graph [][]int
var specials map[int]bool
var used []bool
var components []component

func bfs(v int) component {
	nodes := 0
	edges := 0
	q := []int{v}
	used[v] = true

	for len(q) > 0 {
		nodes++
		t := q[0]
		q = q[1:]
		for _, vnext := range graph[t] {
			edges++
			if !used[vnext] {
				q = append(q, vnext)
				used[vnext] = true
			}
		}
	}

	return component{
		nodes: nodes,
		edges: edges / 2,
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d %d\n", &n, &m, &k)
	specials = make(map[int]bool)
	graph = make([][]int, n + 1)
	used = make([]bool, n + 1)
	components = make([]component, n + 1)
	for i := 0; i < k; i++ {
		var tmp int
		fmt.Fscanf(buf, "%d", &tmp)
		specials[tmp] = true
	}
	fmt.Fscanf(buf, "\n")
	for i := 0; i < m; i++ {
		var v1, v2 int
		fmt.Fscanf(buf, "%d %d\n", &v1, &v2)
		graph[v1] = append(graph[v1], v2)
		graph[v2] = append(graph[v2], v1)
	}

	maxNodesInComponent := 0
	componentSpecial := 0
	ans := 0
	for v, _ := range specials {
		components[v] = bfs(v)
		if components[v].nodes > maxNodesInComponent {
			maxNodesInComponent = components[v].nodes
			componentSpecial = v
		}
		ans += components[v].nodes * (components[v].nodes - 1) / 2 - components[v].edges
	}

	for i := 1; i <= n; i++ {
		if !specials[i] && !used[i] {
			c := bfs(i)
			ans += c.nodes * (c.nodes - 1) / 2 - c.edges
			ans += c.nodes * components[componentSpecial].nodes
		}
	}
	fmt.Println(ans)
}