You are a programmer and you have a New Year Tree (not the traditional fur tree, though) — a tree of four vertices: one vertex of degree three (has number 1), connected with three leaves (their numbers are from 2 to 4).On the New Year, programmers usually have fun. You decided to have fun as well by adding vertices to the tree. One adding operation looks as follows:  First we choose some leaf of the tree with number v.  Let's mark the number of vertices on the tree at this moment by variable n, then two vertexes are added to the tree, their numbers are n + 1 and n + 2, also you get new edges, one between vertices v and n + 1 and one between vertices v and n + 2. Your task is not just to model the process of adding vertices to the tree, but after each adding operation print the diameter of the current tree. Come on, let's solve the New Year problem!

The first line contains integer q (1 ≤ q ≤ 5·105) — the number of operations. Each of the next q lines contains integer vi (1 ≤ vi ≤ n) — the operation of adding leaves to vertex vi. Variable n represents the number of vertices in the current tree. It is guaranteed that all given operations are correct.

Print q integers — the diameter of the current tree after each operation.

package main

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

const (
	ancLevel = 18
	maxN     = 1000000 + 10
)

var (
	anc [maxN][ancLevel]int
	dep [maxN]int
)

func getLca(x int, y int) int {
	a, b := x, y
	if dep[x] < dep[y] {
		a, b = b, a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if dep[a]-(1<<uint(lv)) >= dep[b] {
			a = anc[a][lv]
		}
	}
	if a == b {
		return a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if anc[a][lv] != anc[b][lv] {
			a = anc[a][lv]
			b = anc[b][lv]
		}
	}
	return anc[a][0]
}

var (
	d = 2
)

func check(cur int, far int) bool {
	lca := getLca(cur, far)
	curD := dep[cur] - dep[lca] + dep[far] - dep[lca]
	if curD > d {
		d = curD
		return true
	} else {
		return false
	}
}

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

	var (
		p1, p2 = 2, 3
		n      = 4
		q      int
	)

	fmt.Fscanf(reader, "%d\n", &q)
	for i := 2; i <= 4; i++ {
		anc[i][0] = 1
		dep[i] = 1
	}

	for i := 0; i < q; i++ {
		var x int
		fmt.Fscanf(reader, "%d\n", &x)
		anc[n+1][0] = x
		anc[n+2][0] = x
		n += 2
	}

	for p := 5; p <= n; p++ {
		dep[p] = dep[anc[p][0]] + 1
		for lv := 1; lv < ancLevel; lv++ {
			anc[p][lv] = anc[anc[p][lv-1]][lv-1]
		}
	}

	n = 4
	for i := 0; i < q; i++ {
		if check(n+1, p1) {
			p2 = n + 1
		} else if check(n+1, p2) {
			p1 = n + 1
		}
		fmt.Fprintln(writer, d)
		n += 2
	}
}

package main

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

const (
	ancLevel = 18
	maxN     = 1000000 + 10
)

var (
	anc [maxN][ancLevel]int
	dep [maxN]int
)

func getLca(x int, y int) int {
	a, b := x, y
	if dep[x] < dep[y] {
		a, b = b, a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if dep[a]-(1<<uint(lv)) >= dep[b] {
			a = anc[a][lv]
		}
	}
	if a == b {
		return a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if anc[a][lv] != anc[b][lv] {
			a = anc[a][lv]
			b = anc[b][lv]
		}
	}
	return anc[a][0]
}

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

func check(cur int, far int) bool {
	lca := getLca(cur, far)
	curD := dep[cur] - dep[lca] + dep[far] - dep[lca]
	if curD > d {
		d = curD
		return true
	} else {
		return false
	}
}

func main() {
	defer writer.Flush()

	var (
		p1, p2 = 2, 3
		n      = 4
		q      int
	)

	fmt.Fscanf(reader, "%d\n", &q)
	for i := 2; i <= 4; i++ {
		anc[i][0] = 1
		dep[i] = 1
	}

	for i := 0; i < q; i++ {
		var x int
		fmt.Fscanf(reader, "%d\n", &x)
		anc[n+1][0] = x
		anc[n+2][0] = x
		n += 2
	}

	for p := 5; p <= n; p++ {
		dep[p] = dep[anc[p][0]] + 1
		for lv := 1; lv < ancLevel; lv++ {
			anc[p][lv] = anc[anc[p][lv-1]][lv-1]
		}
	}

	n = 4
	for i := 0; i < q; i++ {
		if check(n+1, p1) {
			p2 = n + 1
		} else if check(n+1, p2) {
			p1 = n + 1
		}
		fmt.Fprintln(writer, d)
		n += 2
	}
}

package main

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

type Tree struct {
	n  int
	lg int
	ns []node
}

type node struct {
	dep int
	parent *node
	pnt []*node
}

func New(n int) *Tree {
	t := &Tree{
		n:  n,
		ns: make([]node, n),
	}
	for i := range t.ns {
		x := &t.ns[i]
		x.pnt = make([]*node, 1)
	}
	r := &t.ns[0]
	r.parent = r
	return t
}

func (t *Tree) Link(u, v int) {
	x := &t.ns[u]
	y := &t.ns[v]
	y.dep = x.dep + 1
	y.parent = x
}

func (t *Tree) Build() {
	dmax := 0
	for _, x := range t.ns {
		if x.dep > dmax {
			dmax = x.dep
		}
	}
	t.lg = 1
	for d := 1; d <= dmax; d <<= 1 {
		t.lg++
	}
	alloc := make([]*node, t.lg * t.n)
	for i := range t.ns {
		x := &t.ns[i]
		x.pnt = alloc[i*t.lg: (i+1)*t.lg]
		x.pnt[0] = x.parent
	}
	for d := 1; d < t.lg; d++ {
		for i := range t.ns {
			x := &t.ns[i]
			x.pnt[d] = x.pnt[d-1].pnt[d-1]
		}
	}
}

func (t *Tree) lca(x, y *node) *node {
	if x.dep < y.dep {
		x, y = y, x
	}
	d := x.dep - y.dep
	for i := 0; i < t.lg; i++ {
		if d&(1<<uint(i)) > 0 {
			x = x.pnt[i]
		}
	}
	for i := t.lg - 1; i >= 0; i-- {
		x1 := x.pnt[i]
		y1 := y.pnt[i]
		if x1 != y1 {
			x, y = x1, y1
		}
	}
	if x != y {
		x = x.pnt[0]
	}
	return x
}

func (t *Tree) Dist(u, v int) int {
	x := &t.ns[u]
	y := &t.ns[v]
	z := t.lca(x, y)
	return x.dep + y.dep - 2*z.dep
}

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

	var q int
	fmt.Fscanf(reader, "%d\n", &q)
	t := New(4 + 2 * q)
	t.Link(0, 1)
	t.Link(0, 2)
	t.Link(0, 3)
	k := 4
	for i := 0; i < q; i++ {
		var v int
		fmt.Fscanf(reader, "%d\n", &v)
		v--
		t.Link(v, k)
		k++
		t.Link(v, k)
		k++
	}
	t.Build()

	k = 4
	ans := 2
	x, y := 1, 2
	for i := 0; i < q; i++ {
		f := func() {
			d1 := t.Dist(x, k)
			d2 := t.Dist(y, k)
			if d1 >= d2 && d1 > ans {
				ans, x, y = d1, x, k
			} else if d2 > d1 && d2 > ans {
				ans, x, y = d2, y, k
			}
//			fmt.Println("k", k, d1, d2, ans, x, y)
			k++
		}
		f()
		f()
		fmt.Fprintln(writer, ans)
	}
}

package main

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

const (
	ancLevel = 18
	maxN     = 1000000 + 2
)

var (
	anc [maxN][ancLevel]int
	dep [maxN]int
)

func setAncestors(p int) {
	dep[p] = dep[anc[p][0]] + 1
	for lv := 1; lv < ancLevel; lv++ {
		anc[p][lv] = anc[anc[p][lv-1]][lv-1]
	}
}

func getLca(x int, y int) int {
	a, b := x, y
	if dep[x] < dep[y] {
		a, b = b, a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if dep[a]-(1<<uint(lv)) >= dep[b] {
			a = anc[a][lv]
		}
	}
	if a == b {
		return a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if anc[a][lv] != anc[b][lv] {
			a = anc[a][lv]
			b = anc[b][lv]
		}
	}
	return anc[a][0]
}

var (
	reader = bufio.NewReader(os.Stdin)
	n      = 4
	d      = 2
)

func check(cur int, far int) bool {
	lca := getLca(cur, far)
	curD := dep[cur] - dep[lca] + dep[far] - dep[lca]
	if curD > d {
		d = curD
		return true
	} else {
		return false
	}
}

func main() {
	var (
		p1, p2 = 2, 3
		q      int
	)

	fmt.Fscan(reader, &q)
	for i := 2; i <= 4; i++ {
		anc[i][0] = 1
		dep[i] = 1
	}

	add := func(u int, f int) {
		anc[u][0] = f
		setAncestors(u)
	}

	for i := 0; i < q; i++ {
		var x int
		fmt.Fscanf(reader, "%d", &x)
		add(n+1, x)
		add(n+2, x)

		if check(n+1, p1) {
			p2 = n + 1
		} else if check(n+1, p2) {
			p1 = n + 1
		}
		fmt.Println(d)
		n += 2
	}
}

package main

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

const (
	ancLevel = 17
	maxN     = 500000 + 2
)

var (
	anc [maxN][ancLevel]int
	dep [maxN]int
)

func setAncestors(p int) {
	a := anc[p]
	dep[p] = dep[a[0]] + 1
	for lv := 1; lv < ancLevel; lv++ {
		a[lv] = anc[a[lv-1]][lv-1]
	}
}

func getLca(x int, y int) int {
	var a, b int
	if dep[x] >= dep[y] {
		a, b = x, y
	} else {
		a, b = y, x
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if dep[a]-(1<<uint(lv)) >= dep[b] {
			a = anc[a][lv]
		}
	}

	if a == b {
		return a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if anc[a][lv] != anc[b][lv] {
			a = anc[a][lv]
			b = anc[b][lv]
		}
	}
	return anc[a][0]
}

var (
	reader = bufio.NewReader(os.Stdin)
	n      = 4
	d      = 2
)

func check(cur int, far int) bool {
	lca := getLca(cur, far)
	curD := dep[cur] - dep[lca] + dep[far] - dep[lca]
	if curD > d {
		d = curD
		return true
	} else {
		return false
	}
}

func main() {
	var (
		p1 = 2
		p2 = 3
		q  int
		x  int
	)

	fmt.Fscan(reader, &q)
	for i := 2; i <= 4; i++ {
		anc[i][0] = 1
		dep[i] = 1
	}

	add := func(u int, f int) {
		anc[u][0] = f
		setAncestors(u)
	}

	for i := 0; i < q; i++ {
		fmt.Fscan(reader, &x)
		add(n+1, x)
		add(n+2, x)

		if check(n+1, p1) {
			p2 = n + 1
		} else if check(n+1, p2) {
			p1 = n + 1
		}
		fmt.Println(d)
		n += 2
	}
}

package main

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

const (
	ancLevel = 18
	maxN     = 1000000 + 2
)

var (
	anc [maxN][ancLevel]int
	dep [maxN]int
)

func setAncestors(p int) {
	dep[p] = dep[anc[p][0]] + 1
	for lv := 1; lv < ancLevel; lv++ {
		anc[p][lv] = anc[anc[p][lv-1]][lv-1]
	}
}

func getLca(x int, y int) int {
	a, b := x, y
	if dep[x] < dep[y] {
		a, b = b, a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if dep[a]-(1<<uint(lv)) >= dep[b] {
			a = anc[a][lv]
		}
	}
	if a == b {
		return a
	}

	for lv := ancLevel - 1; lv >= 0; lv-- {
		if anc[a][lv] != anc[b][lv] {
			a = anc[a][lv]
			b = anc[b][lv]
		}
	}
	return anc[a][0]
}

var (
	reader = bufio.NewReader(os.Stdin)
	n      = 4
	d      = 2
)

func check(cur int, far int) bool {
	lca := getLca(cur, far)
	curD := dep[cur] - dep[lca] + dep[far] - dep[lca]
	if curD > d {
		d = curD
		return true
	} else {
		return false
	}
}

func main() {
	var (
		p1, p2 = 2, 3
		q      int
	)

	fmt.Fscanf(reader, "%d", &q)
	for i := 2; i <= 4; i++ {
		anc[i][0] = 1
		dep[i] = 1
	}

	add := func(u int, f int) {
		anc[u][0] = f
		setAncestors(u)
	}

	for i := 0; i < q; i++ {
		var x int
		fmt.Fscanf(reader, "%d", &x)
		add(n+1, x)
		add(n+2, x)

		if check(n+1, p1) {
			p2 = n + 1
		} else if check(n+1, p2) {
			p1 = n + 1
		}
		fmt.Println(d)
		n += 2
	}
}

package main

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

type Tree struct {
	n  int
	lg int
	ns []node
}

type node struct {
	dep int
	pnt []*node
	adj []*node
}

func New(n int) *Tree {
	lg := 1
	for d := 1; d < n; d <<= 1 {
		lg++
	}
	t := &Tree{
		n:  n,
		lg: lg,
		ns: make([]node, n),
	}
	for i := range t.ns {
		x := &t.ns[i]
		x.dep = -1
		x.pnt = make([]*node, lg)
	}
	return t
}

func (t *Tree) Link(u, v int) {
	x := &t.ns[u]
	y := &t.ns[v]
	x.adj = append(x.adj, y)
}

func (t *Tree) Build() {
	t.build(&t.ns[0], &t.ns[0], 0)
	for d := 1; d < t.lg; d++ {
		for i := range t.ns {
			x := &t.ns[i]
			x.pnt[d] = x.pnt[d-1].pnt[d-1]
		}
	}
}

func (t *Tree) build(u, p *node, d int) {
	u.pnt[0] = p
	u.dep = d
	for _, v := range u.adj {
		if v.dep == -1 {
			t.build(v, u, d+1)
		}
	}
}

func (t *Tree) Lca(u, v int) int {
	x := &t.ns[u]
	y := &t.ns[v]
	z := t.lca(x, y)
	return int((uintptr(unsafe.Pointer(z)) - uintptr(unsafe.Pointer(&t.ns[0]))) / unsafe.Sizeof(t.ns[0]))
}

func (t *Tree) lca(x, y *node) *node {
	if x.dep < y.dep {
		x, y = y, x
	}
	d := x.dep - y.dep
	for i := 0; i < t.lg; i++ {
		if d&(1<<uint(i)) > 0 {
			x = x.pnt[i]
		}
	}
	for i := t.lg - 1; i >= 0; i-- {
		x1 := x.pnt[i]
		y1 := y.pnt[i]
		if x1 != y1 {
			x, y = x1, y1
		}
	}
	if x != y {
		x = x.pnt[0]
	}
	return x
}

func (t *Tree) Dist(u, v int) int {
	x := &t.ns[u]
	y := &t.ns[v]
	z := t.lca(x, y)
	return x.dep + y.dep - 2*z.dep
}

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

	var q int
	fmt.Fscanf(reader, "%d\n", &q)
	qs := make([]int, q)
	t := New(4 + 2 * q)
	t.Link(0, 1)
	t.Link(0, 2)
	t.Link(0, 3)
	k := 4
	for i := 0; i < q; i++ {
		fmt.Fscanf(reader, "%d\n", &qs[i])
		qs[i]--
		t.Link(qs[i], k)
		k++
		t.Link(qs[i], k)
		k++
	}
	t.Build()

	k = 4
	ans := 2
	x, y := 1, 2
	for _ = range qs {
		f := func() {
			d1 := t.Dist(x, k)
			d2 := t.Dist(y, k)
			if d1 > d2 && d1 > ans {
				ans, x, y = d1, x, k
			} else if d2 > d1 && d2 > ans {
				ans, x, y = d2, y, k
			}
//			fmt.Println("k", k, d1, d2, ans, x, y)
			k++
		}
		f()
		f()
		fmt.Fprintln(writer, ans)
	}
}


Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked $$$p^{k_i}$$$ problems from $$$i$$$-th category ($$$p$$$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.Formally, given $$$n$$$ numbers $$$p^{k_i}$$$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $$$10^{9}+7$$$.

Input consists of multiple test cases. The first line contains one integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$ — the number of test cases. Each test case is described as follows: The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. The second line contains $$$n$$$ integers $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$. The sum of $$$n$$$ over all test cases doesn't exceed $$$10^6$$$.

Output one integer — the reminder of division the answer by $$$1\,000\,000\,007$$$.

NoteYou have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $$$2$$$, but there is also a distribution where the difference is $$$10^9 + 8$$$, then the answer is $$$2$$$, not $$$1$$$.In the first test case of the example, there're the following numbers: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$, and $$$8$$$. We can divide them into such two sets: $$${4, 8, 16}$$$ and $$${8, 16}$$$. Then the difference between the sums of numbers in sets would be $$$4$$$.

package main

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

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 main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, p := readTwoNums(reader)
		K := readNNums(reader, n)
		fmt.Println(solve(n, p, K))
	}
}

const MOD = 1000000007
const INF = 1000010

func solve(n, p int, K []int) int {
	sort.Ints(K)
	E := make([]int, n)
	copy(E, K)

	var cur int64
	var res int64
	var infy bool
	var prevExp = 1000010

	var i, j = n - 1, n - 1

	for i >= 0 {
		k := E[i]
		i--

		delta := prevExp - k
		prevExp = k

		res = res * pow(p, delta) % MOD

		for x := 0; x < delta && x < 20; x++ {
			cur *= int64(p)
			if cur > INF {
				infy = true
			}
		}

		for j >= 0 && K[j] == k {
			j--
			if infy || cur > 0 {
				cur--
				res += MOD - 1
			} else {
				cur++
				res++
			}
			res %= MOD
		}
	}

	res = res * pow(p, prevExp) % MOD

	return int(res)
}

func pow(a, b int) int64 {
	A := int64(a)
	var R int64 = 1

	for b > 0 {
		if b&1 == 1 {
			R *= A
			R %= MOD
		}
		A = A * A % MOD
		b >>= 1
	}
	return R
}


Pak Chanek, a renowned scholar, invented a card puzzle using his knowledge. In the puzzle, you are given a board with $$$n$$$ rows and $$$m$$$ columns. Let $$$(r, c)$$$ represent the cell in the $$$r$$$-th row and the $$$c$$$-th column.Initially, there are $$$k$$$ cards stacked in cell $$$(1, 1)$$$. Each card has an integer from $$$1$$$ to $$$k$$$ written on it. More specifically, the $$$i$$$-th card from the top of the stack in cell $$$(1, 1)$$$ has the number $$$a_i$$$ written on it. It is known that no two cards have the same number written on them. In other words, the numbers written on the cards are a permutation of integers from $$$1$$$ to $$$k$$$. All other cells are empty.You need to move the $$$k$$$ cards to cell $$$(n, m)$$$ to create another stack of cards. Let $$$b_i$$$ be the number written on the $$$i$$$-th card from the top of the stack in cell $$$(n, m)$$$. You should create the stack in cell $$$(n, m)$$$ in such a way so that $$$b_i = i$$$ for all $$$1 \leq i \leq k$$$.In one move, you can remove the top card from a cell and place it onto an adjacent cell (a cell that shares a common side). If the target cell already contains one or more cards, you place your card on the top of the stack. You must do each operation while satisfying the following restrictions:   Each cell other than $$$(1,1)$$$ and $$$(n,m)$$$ must not have more than one card on it.  You cannot move a card onto cell $$$(1,1)$$$.  You cannot move a card from cell $$$(n,m)$$$. Given the values of $$$n$$$, $$$m$$$, $$$k$$$ and the array $$$a$$$, determine if the puzzle is solvable.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$3 \leq n, m \leq 10^6$$$, $$$nm \leq 10^6$$$, $$$1 \leq k \leq 10^5$$$) — the size of the board and the number of cards. The second line of the test case contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ — the array $$$a$$$, representing the numbers written on the cards. The values of $$$a$$$ are a permutation of integers from $$$1$$$ to $$$k$$$. It is guaranteed that the sum of $$$nm$$$ and $$$k$$$ over all test cases do not exceed $$$10^6$$$ and $$$10^5$$$ respectively.

For each test case, output "YA" (without quotes) if it is possible and "TIDAK" (without quotes) otherwise, which mean yes and no in Indonesian respectively. You can output "YA" and "TIDAK" in any case (for example, strings "tiDAk", "tidak", and "Tidak" will be recognised as a negative response).

NoteIn the first test case, the following is one way the puzzle can be done:   Move the card with $$$3$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(1, 2)$$$, then cell $$$(1, 3)$$$.  Move the card with $$$6$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(2, 1)$$$, then cell $$$(3, 1)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$4$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(1, 2)$$$.  Move the card with $$$1$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(2, 1)$$$, then cell $$$(2, 2)$$$, then cell $$$(2, 3)$$$.  Move the card with $$$2$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(2, 1)$$$, then cell $$$(2, 2)$$$.  Move the card with $$$5$$$ written on it from cell $$$(1, 1)$$$ to cell $$$(2, 1)$$$, then cell $$$(3, 1)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$2$$$ written on it from cell $$$(2, 2)$$$ to cell $$$(2, 1)$$$.  Move the card with $$$4$$$ written on it from cell $$$(1, 2)$$$ to cell $$$(2, 2)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$3$$$ written on it from cell $$$(1, 3)$$$ to cell $$$(1, 2)$$$, then cell $$$(2, 2)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$2$$$ written on it from cell $$$(2, 1)$$$ to cell $$$(3, 1)$$$, then cell $$$(3, 2)$$$, then cell $$$(3, 3)$$$.  Move the card with $$$1$$$ written on it from cell $$$(2, 3)$$$ to cell $$$(3, 3)$$$. An animated illustration regarding the process mentioned above is as follows:

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		n, m, k := readThreeInt(reader)
		ka := readArrayInt(reader)
		var queue = make(map[int]bool)

		top := k
		sizeQueue := 0
		fail := false
		for i := 0; i < k; i++ {
			queue[ka[i]] = true
			sizeQueue++
			if _, ok := queue[top]; ok {
				if sizeQueue > n*m-3 {
					fail = true
					break
				}
				sizeQueue--
				delete(queue, top)
				top--
			}
		}

		if !fail {
			fmt.Fprintln(writer, "YA")
		} else {
			fmt.Fprintln(writer, "TIDAK")
		}

		t--
	}

	writer.Flush()
}

func max(a int, b int) int {
	return int(maxInt64(int64(a), int64(b)))
}

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

	return b
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

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

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, m, k, st, nisc int
		fmt.Fscan(r, &n, &m, &k)

		a := make([]int, k)
		v := make([]bool, k+1)
		for i := range a { fmt.Fscan(r, &a[i]) }

		res := "YA"
		for i := k ; i >= 1 ; i-- {
			if v[i] {
				nisc--
			} else {
				for ; st < k && a[st] != i ; st++ {
					v[a[st]] = true
					nisc++
				}

				if n*m - nisc < 4 {
					res = "TIDAK"
					break
				}
				st++
			}
		}

		fmt.Fprintln(w, res)
	}
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, m, k, st, nisc int
		fmt.Fscan(r, &n, &m, &k)

		a := make([]int, k)
		v := make([]bool, k+1)
		for i := range a { fmt.Fscan(r, &a[i]) }

		res := "YA"
		for i := k ; i >= 1 ; i-- {
			// fmt.Fprintln(w, "IIIIIIIIIIIIIIIII i ", i)
			if v[i] {
				nisc--
			} else {
				// fmt.Fprintln(w, "iiii st ", st)
				for ; st < k && a[st] != i ; st++ {
					v[a[st]] = true
					nisc++
				}

				if n*m - nisc < 4 {
					res = "TIDAK"
					break
				}
				// fmt.Fprintln(w, "iiii st nisc ", st, nisc)
				st++
			}
		}

		fmt.Fprintln(w, res)
	}
}

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

const (
	DEBUG = false
)

func debug(a ...interface{}) {
	if !DEBUG {
		return
	}
	for _, e := range a {
		printf("%v ", e)
	}
	printf("\n")
	writer.Flush()
}

func debugCondn(condn bool, a ...interface{}) {
	if !DEBUG || !condn {
		return
	}
	for _, e := range a {
		printf("%v ", e)
	}
	printf("\n")
	writer.Flush()
}

func assert(condn bool) {
	if !condn {
		panic("assertion error")
	}
}

func solve(tt int) {
	var n,m,k int
	scanf("%d %d %d\n", &n, &m, &k)
	a := make([]int, k)
	for i:=0; i<k; i++ {
		scanf("%d ", &a[i])
	}
	scanf("\n")

	nm := n*m
	moved := make([]bool, k+1)
	cnt := 0
	nxt := k

	res := true
	for i:=0; i<k; i++ {
		moved[a[i]] = true
		cnt++
		if cnt == nm - 2 {
			res = false
			break
		}
		for nxt > 0 && moved[nxt] {
			nxt--
			cnt--
		}
	}

	if res && nxt == 0 {
		assert(cnt == 0)
		printf("YA\n")
		return
	}
	printf("TIDAK\n")
}

func main() {
	defer writer.Flush()

	var T int
	scanf("%d\n", &T)
	for tt:=1; tt<=T; tt++ {
		solve(tt)
	}
}

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		n, m, k := readThreeInt(reader)
		ka := readArrayInt(reader)
		var queue = make(map[int]bool)

		top := k
		sizeQueue := 0
		fail := false
		for i := 0; i < k; i++ {
			if ka[i] == top {
				top--
			} else {
				if _, ok := queue[top]; ok {
					sizeQueue--
					delete(queue, top)
					top--
				} else if sizeQueue < n*m {
					queue[ka[i]] = true
					sizeQueue++
				} else {
					fail = true
					break
				}
			}
		}

		if !fail {
			fmt.Fprintln(writer, "YA")
		} else {
			fmt.Fprintln(writer, "TIDAK")
		}

		t--
	}

	writer.Flush()
}

func max(a int, b int) int {
	return int(maxInt64(int64(a), int64(b)))
}

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

	return b
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

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

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		n, m, k := readThreeInt(reader)
		ka := readArrayInt(reader)
		var queue = make(map[int]bool)

		top := k
		sizeQueue := 0
		fail := false
		for i := 0; i < k; i++ {
			if ka[i] == top {
				top--
			} else {
				if _, ok := queue[top]; ok {
					sizeQueue--
					delete(queue, top)
					top--
				} else if sizeQueue < n*m-1 {
					queue[ka[i]] = true
					sizeQueue++
				} else {
					fail = true
					break
				}
			}
		}

		if !fail {
			fmt.Fprintln(writer, "YA")
		} else {
			fmt.Fprintln(writer, "TIDAK")
		}

		t--
	}

	writer.Flush()
}

func max(a int, b int) int {
	return int(maxInt64(int64(a), int64(b)))
}

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

	return b
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

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

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		n, m, k := readThreeInt(reader)
		ka := readArrayInt(reader)
		var queue = make(map[int]bool)

		top := k
		sizeQueue := 0
		fail := false
		for i := 0; i < k; i++ {
			if ka[i] == top {
				top--
			} else {
				if _, ok := queue[top]; ok {
					sizeQueue--
					delete(queue, top)
					top--
				} else if sizeQueue < n*m-2 {
					queue[ka[i]] = true
					sizeQueue++
				} else {
					fail = true
					break
				}
			}
		}

		if !fail {
			fmt.Fprintln(writer, "YA")
		} else {
			fmt.Fprintln(writer, "TIDAK")
		}

		t--
	}

	writer.Flush()
}

func max(a int, b int) int {
	return int(maxInt64(int64(a), int64(b)))
}

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

	return b
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

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

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		n, m, k := readThreeInt(reader)
		ka := readArrayInt(reader)
		var queue = make(map[int]bool)

		top := k
		sizeQueue := 0
		fail := false
		for i := 0; i < k; i++ {
			if ka[i] == top {
				top--
			} else {
				if _, ok := queue[top]; ok {
					sizeQueue--
					delete(queue, top)
					top--
				} else if sizeQueue < n*m-3 {
					queue[ka[i]] = true
					sizeQueue++
				} else {
					fail = true
					break
				}
			}
		}

		if !fail {
			fmt.Fprintln(writer, "YA")
		} else {
			fmt.Fprintln(writer, "TIDAK")
		}

		t--
	}

	writer.Flush()
}

func max(a int, b int) int {
	return int(maxInt64(int64(a), int64(b)))
}

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

	return b
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

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

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		n, m, k := readThreeInt(reader)
		ka := readArrayInt(reader)
		var queue = make(map[int]bool)

		top := k
		sizeQueue := 0
		fail := false
		for i := 0; i < k; i++ {
			if ka[i] == top {
				top--
			} else {
				if _, ok := queue[top]; ok {
					sizeQueue--
					delete(queue, top)
					top--
				} else if sizeQueue < n*m-4 {
					queue[ka[i]] = true
					sizeQueue++
				} else {
					fail = true
					break
				}
			}
		}

		if !fail {
			fmt.Fprintln(writer, "YA")
		} else {
			fmt.Fprintln(writer, "TIDAK")
		}

		t--
	}

	writer.Flush()
}

func max(a int, b int) int {
	return int(maxInt64(int64(a), int64(b)))
}

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

	return b
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

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

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		n, m, k := readThreeInt(reader)
		ka := readArrayInt(reader)
		var queue = make(map[int]bool)

		top := k
		sizeQueue := 0
		fail := false
		for i := 0; i < k; i++ {
			if ka[i] == top {
				top--
			} else {
				if _, ok := queue[top]; ok {
					sizeQueue--
					delete(queue, top)
					top--
				} else if sizeQueue < (n-1)*(m-1) {
					queue[ka[i]] = true
					sizeQueue++
				} else {
					fail = true
					break
				}
			}
		}

		if !fail {
			fmt.Fprintln(writer, "YA")
		} else {
			fmt.Fprintln(writer, "TIDAK")
		}

		t--
	}

	writer.Flush()
}

func max(a int, b int) int {
	return int(maxInt64(int64(a), int64(b)))
}

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

	return b
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

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

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}


The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example  and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.

The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers.  The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.

In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.

package main

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

type Socket struct {
    s, i int
}

type SocketArr []Socket
func (a SocketArr) Len() int           { return len(a) }
func (a SocketArr) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a SocketArr) Less(i, j int) bool { return a[i].s < a[j].s }

func solve() {
    n, m := readInt(), readInt()
    mp, powers, sockets := make(map[int][]int), readIntArray(n), make(SocketArr, m)
    for i, p := range powers {
        mp[p] = append(mp[p], i)
    }
    for i := range sockets {
        sockets[i] = Socket{readInt(), i}
    }
    c, u, a, b := 0, 0, make([]int, m), make([]int, n)
    for i := range b {
        b[i] = -1
    }

    sort.Sort(sockets)
    for _, s := range sockets {
        pow, cnt := s.s, 0
        for {
            ps := mp[pow]
            if len(ps) > 0 {
                b[ps[0]], mp[pow], a[s.i] = s.i, ps[1:], cnt
                c++
                u += cnt
                break
            }
            if pow == 1 {
                break
            }
            pow = (pow + 1) / 2
            cnt++
        }
    }
    fmt.Println(c, u)
    for _, v := range a {
        fmt.Print(v, " ")
    }
    fmt.Println()

    for _, v := range b {
        fmt.Print(v+1, " ")
    }
    fmt.Println()
}

// 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 bufin *bufio.Reader
var bufout *bufio.Writer

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

	var n, m int
	fmt.Fscanf(bufin, "%d %d\n", &n, &m)

	last := make(map[int]int)
	next := make([]int, n+1)

	var p int
	for i := 1; i <= n; i++ {
		fmt.Fscanf(bufin, "%d\n", &p)
		_, ok := last[p]
		if ok {
			next[i] = last[p]
		}
		last[p] = i
	}

	s := make([]int, m+1)
	for i := 1; i <= m; i++ {
		fmt.Fscanf(bufin, "%d\n", &s[i])
	}

	c := 0
	u := 0
	a := make([]int, m+1)
	b := make([]int, n+1)

	used := make([]bool, m+1)
	for plug, one := 0, 0; one < m; plug++ {
		for i := 1; i <= m; i++ {
			if !used[i] {
				p = s[i]
				j, ok := last[p]
				if ok && (j > 0) && (b[j] == 0) {
					c++
					u += plug
					a[i] = plug
					b[j] = i
					used[i] = true
					last[p] = next[j]
				}
			}
		}

		one = 0
		for i := 1; i <= m; i++ {
			if s[i] == 1 {
				one++
			}
			s[i] = (s[i] + 1) / 2
		}
	}

	fmt.Fprintf(bufout, "%d %d\n", c, u)
	for i := 1; i <= m; i++ {
		fmt.Fprintf(bufout, "%d ", a[i])
	}
	fmt.Fprintf(bufout, "\n")
	for i := 1; i <= n; i++ {
		fmt.Fprintf(bufout, "%d ", b[i])
	}
	fmt.Fprintf(bufout, "\n")
}


Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1, ..., ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.

The first line contains 5 space-separated integers: n, k, p, x and y (1 ≤ n ≤ 999, n is odd, 0 ≤ k < n, 1 ≤ p ≤ 1000, n ≤ x ≤ n·p, 1 ≤ y ≤ p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1, ..., ak (1 ≤ ai ≤ p) — the marks that Vova got for the tests he has already written.

If Vova cannot achieve the desired result, print "-1". Otherwise, print n - k space-separated integers — the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.

NoteThe median of sequence a1, ..., an where n is odd (in this problem n is always odd) is the element staying on (n + 1) / 2 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: "4 2", "2 4", "5 1", "1 5", "4 1", "1 4" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is "-1".

package main

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

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

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

	n, k, p, x, y := nextInt(), nextInt(), nextInt(), nextInt(), nextInt()
	sum, median, cntLeast, a := 0, (n+1)/2, 0, 0
	_ = p

	for i := 0; i < k; i++ {
		a = nextInt()
		sum += a

		if a < y {
			cntLeast++
		}
	}

	if cntLeast >= median {
		println(-1)
		return
	} else {
		a = median - cntLeast - 1
		if n-k < a {
			a = n - k
		}
		sum += a*1 + (n-k-a)*y
	}
	// println(cntLeast)
	if sum > x {
		println(-1)
	} else {
		for i := 0; i < a; i++ {
			print(1, " ")
		}

		for i := 0; i < n-k-a; i++ {
			print(y, " ")
		}
		println()
	}
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

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

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

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

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

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

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

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n, k, _, maxTotal, minMedian := getI(), getI(), getI(), getI(), getI()
  m := n-k
  data := make([]int, n)
  for i := 0; i < m; i++ {
    data[i] = 1
  }
  total := m
  for i := 0; i < k; i++ {
    x := getI()
    data[m+i] = x
    total += x
  }
  sort.Ints(data)
  median := n/2
  seek := median
  for seek < n && data[seek] < minMedian {
    seek++
  }
  dist := seek-median
  total += dist*(minMedian-1)
  if dist > m || total > maxTotal {
    writer.WriteString("-1\n")
    return
  }
  result := make([]int, m)
  for i := 0; i < m; i++ {
    if i < dist {
      result[i] = minMedian
    } else {
      result[i] = 1
    }
  }
  writer.WriteString(fmt.Sprintf("%d", result[0]))
  for i := 1; i < m; i++ {
    writer.WriteString(fmt.Sprintf(" %d", result[i]))
  }
  writer.WriteString("\n")
}

package main

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

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

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

	n, k, p, x, y := nextInt(), nextInt(), nextInt(), nextInt(), nextInt()
	sum, median, cntLeast, a := 0, (n+1)/2, 0, 0
	_ = p

	for i := 0; i < k; i++ {
		a = nextInt()
		sum += a

		if a < y {
			cntLeast++
		}
	}

	if cntLeast >= median {
		println(-1)
		return
	} else {
		sum += (median-cntLeast-1)*1 + (n-k-(median-cntLeast-1))*y
	}

	if sum >= x {
		println(-1)
	} else {
		for i := 0; i < median-cntLeast-1; i++ {
			print(1, " ")
		}

		for i := 0; i < n-k-(median-cntLeast-1); i++ {
			print(y, " ")
		}
		println()
	}
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

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

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

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

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

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

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

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

	n, k, p, x, y := nextInt(), nextInt(), nextInt(), nextInt(), nextInt()
	sum, median, cntLeast, a := 0, (n+1)/2, 0, 0
	_ = p

	for i := 0; i < k; i++ {
		a = nextInt()
		sum += a

		if a < y {
			cntLeast++
		}
	}

	if cntLeast >= median {
		println(-1)
		return
	} else {
		sum += (median-cntLeast-1)*1 + (n-k-(median-cntLeast-1))*y
	}

	if sum > x {
		println(-1)
	} else {
		for i := 0; i < median-cntLeast-1; i++ {
			print(1, " ")
		}

		for i := 0; i < n-k-(median-cntLeast-1); i++ {
			print(y, " ")
		}
		println()
	}
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

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

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

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

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }


You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently.The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n, m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the field. Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells.

Print the answer as a matrix as described above. See the examples to precise the format of the output.

NoteIn first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner).

package main

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

var labyrinth []string
var n, m int
var count []int
var flood [][]int
var dr = [4]int{1, -1, 0, 0}
var dc = [4]int{0, 0, 1, -1}

func isValid(r, c int) bool {
	return r < n && r >= 0 && c < m && c >= 0
}

func floodFill(v, r, c int) int {
	if !isValid(r, c) || labyrinth[r][c] != '.' || flood[r][c] != 0 {
		return 0
	}
	flood[r][c] = v
	ans := 1
	for i := 0;i < 4; i ++ {
		ans += floodFill(v, r + dr[i], c + dc[i])
	}
	return ans
}

func main() {

	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	labyrinth = make([]string, n)
	count = make([]int, 0, n * m)
	flood = make([][]int, n)

	writer := bytes.NewBuffer(make([]byte, 0, 10000000))

	for i := 0;i < n;i ++ {
		flood[i] = make([]int, m)
		fmt.Fscanf(reader, "%s\n", &labyrinth[i])
	}
	for i := 0;i < n;i ++ {
		for j := 0;j < m;j ++ {
			if labyrinth[i][j] == '.' && flood[i][j] == 0 {
				ans := floodFill(len(count) + 1, i, j)
				count = append(count, ans)
			}
		}
	}
	for i := 0;i < n;i ++ {
		for j := 0;j < m;j ++ {
			if labyrinth[i][j] == '*' {
				region, ans := make([]int, 0, 4), 1
				for k := 0;k < 4;k ++ {
					r, c := dr[k] + i, dc[k] + j
					if isValid(r, c) && labyrinth[r][c] == '.' {
						flag := true
						for l := 0;l < len(region);l ++ {
							if region[l] == flood[r][c] {
								flag = false
								break
							}
						}
						if flag {
							region = append(region, flood[r][c])
							ans += count[flood[r][c] - 1]
						}
					}
				}
				fmt.Fprintf(writer, "%c", byte(48 + (ans % 10)))
			} else {
				fmt.Fprintf(writer, ".")
			}
		}
		fmt.Fprintf(writer, "\n")
	}
	writer.WriteTo(os.Stdout)
}


A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.

The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 109), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1 ≤ n ≤ 105), denoting the number of banknotes. The next line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.

Output a single integer: the maximum number of banknotes Oleg can take.

NoteIn the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.For the second sample, Oleg can't take any banknotes without bumping into any of the security guards.

// Codeforces helper functions
// 20 Jan 18
// samadhi

package main

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

const debug = true

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

	in := gsli(reader)
	_ = gsli(reader)
	a := in[1]
	b := in[2]

	count := 0

	safes := gsli(reader)

	for i := 0; i < len(safes); i++ {
		if safes[i] < b && safes[i] > a {
			count++
		}
	}

	fmt.Println(count)

}

// Input helpers

// If you don't pass in a reference to the reader, and just instantiate a new
// one every time, it will work locally, with IO typed at human-speed, but not
// on Codeforces.

// Get Space-separated Line as Strings
//
// Example input:
// 1 test 382.0
// Example output:
// ["1", "test", "382.0"]

func gsls(reader *bufio.Reader) (arr []string) {
	// Get a full line
	input, _ := reader.ReadString('\n')

	//Strip newline and return chars, if any
	input = strings.TrimSuffix(input, "\n")
	input = strings.TrimSuffix(input, "\r")

	// Split at the spaces into an array
	arr = strings.Split(input, " ")

	return
}

// Get Space-separated Line as Integers
// Any non-valid integers will be 0
//
// Example input:
// test 1 12.3 -117
// Example output:
// [0, 1, 0, -117]

func gsli(reader *bufio.Reader) (arr []int) {
	stringArr := gsls(reader)

	for _, e := range stringArr {
		cur, _ := strconv.Atoi(e)
		arr = append(arr, cur)
	}

	return
}

// Get Space-separated Line as 64-bit Floats
// Any non-valid floats will be 0
//
// Example input:
// test 128.328 12 -11.0
// Example output:
// [0, 128.328, 12, -11]

func gslf(reader *bufio.Reader) (arr []float64) {
	stringArr := gsls(reader)

	for _, e := range stringArr {
		cur, _ := strconv.ParseFloat(e, 64)
		arr = append(arr, cur)
	}

	return
}

// String helpers

// Is Lowercase
// Given some string[i], return whether it is lower case or not.

func isl(b byte) bool {
	var r rune
	r = rune(b)
	return unicode.IsLower(r)
}

// Math helpers

// Positve Modulo
// Returns x mod y, but always positive

func posMod(x, y int) int {
	return (x%y + y) % y
}

// Max Int
// Returns the max of two ints

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

// Distance formule
// Calculates the distance to the origin

func dist(x, y float64) float64 {
	return math.Sqrt(math.Pow(x, 2) + math.Pow(y, 2))
}

// Output helpers

func yes() {
	fmt.Println("Yes")
}

func no() {
	fmt.Println("No")
}

// Debug helpers

// From https://groups.google.com/forum/#!topic/golang-nuts/Qlxs3V77nss

func dbg(s string, a ...interface{}) {
	if debug {
		fmt.Printf(s, a...)
	}
}


You are playing a game called Slime Escape. The game takes place on a number line. Initially, there are $$$n$$$ slimes. For all positive integers $$$i$$$ where $$$1 \le i \le n$$$, the $$$i$$$-th slime is located at position $$$i$$$ and has health $$$a_i$$$. You are controlling the slime at position $$$k$$$. There are two escapes located at positions $$$0$$$ and $$$n+1$$$. Your goal is to reach any one of the two escapes by performing any number of game moves.In one game move, you move your slime to the left or right by one position. However, if there is another slime in the new position, you must absorb it. When absorbing a slime, the health of your slime would be increased by the health of the absorbed slime, then the absorbed slime would be removed from the game.Note that some slimes might have negative health, so your health would decrease when absorbing such slimes. You lose the game immediately if your slime has negative health at any moment during the game.Can you reach one of two escapes by performing any number of game moves, without ever losing the game?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 20\,000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers $$$n$$$, $$$k$$$ ($$$3 \leq n \leq 200\,000$$$, $$$1 \leq k \leq n$$$) — the number of slimes and the position of your slime. The second line of each test case contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the health of the slimes. It is guaranteed that health of your slime is non-negative ($$$a_k \geq 0$$$), and all other slimes have non-zero health ($$$a_i \ne 0$$$ for $$$i \ne k$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.

For each test case, print "YES" (without quotes) if you can escape without losing, and "NO" (without quotes) otherwise.

NoteIn the first test case, you control the slime at position $$$4$$$ with health $$$6$$$. One way to escape is to absorb the slimes at positions $$$5$$$, $$$6$$$, and $$$7$$$. Your slime escapes with $$$0$$$ health at position $$$8$$$.In the second test case, you control the slime with $$$232$$$ health at position $$$1$$$. Since your slime is already located next to the escape at position $$$0$$$, you can move to it without absorbing any slime.In the third test case, it can be shown that your slime would always have a negative health before reaching any one of two escapes.In the fourth test case, you control the slime at position $$$4$$$ with health $$$6$$$. The following describes a possible sequence of moves to win:  Absorb the slimes at positions $$$5$$$, $$$6$$$, and $$$7$$$: your health becomes $$$4$$$ after absorbing the slime with health $$$-2$$$; becomes $$$1$$$ after absorbing the slime with health $$$-3$$$; and becomes $$$7$$$ after absorbing the slime with health $$$6$$$.  Absorb the slimes at positions $$$3$$$, and $$$2$$$: your health becomes $$$7-7+10=10$$$.  Absorb the slime at position $$$8$$$: your health becomes $$$10-10=0$$$.  Use the escape at position $$$9$$$. Since your slime has maintained non-negative health at all times, you have won.

package main

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

// https://space.bilibili.com/206214
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	solve := func(curCase int)  bool {
		var n, k int
		Fscan(in, &n, &k)
		k--
		a := make([]int64, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		h := a[k]
		type pair struct{ mi, d int64 }
		f := func(a []int64) (b []pair) {
			for len(a) > 0 && a[0] > 0 {
				h += a[0]
				a = a[1:]
			}
			for i, n := 0, len(a); i < n; {
				neg := int64(0)
				mi := int64(0)
				for {
					for ; i < n && a[i] < 0; i++ {
						neg += a[i]
					}
					mi = min(mi, neg)
					if i == n {
						b = append(b, pair{mi, neg})
						break
					}
					pos := int64(0)
					for ; i < n && a[i] > 0; i++ {
						pos += a[i]
					}
					if neg+pos > 0 {
						b = append(b, pair{mi, neg+pos})
						break
					}
					neg += pos
				}
			}
			return
		}
		r := f(a[k+1:])
		tmp := a[:k]
		for i, n := 0, len(tmp); i < n/2; i++ {
			tmp[i], tmp[n-1-i] = tmp[n-1-i], tmp[i]
		}
		l := f(tmp)

		g := func() bool {
			i, j := 0, 0
			n, m := len(l), len(r)
			for i < n && j < m {
				if h + l[i].mi >= 0 {
					h += l[i].d
					i++
					continue
				}
				if h + r[j].mi >= 0 {
					h += r[j].d
					j++
					continue
				}
				return false
			}
			return true
		}
		return  g()
	}

	cases := 1
	Fscan(in, &cases)
	for curCase := 1; curCase <= cases; curCase++ {
		if solve(curCase) {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}

	leftData, _ := ioutil.ReadAll(in)
	if s := strings.TrimSpace(string(leftData)); s != "" {
		panic("有未读入的数据：\n" + s)
	}

}

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

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

package main

import (
	"bufio"
	. "fmt"
	"io"

	//"math"
	"os"
	//"sort"
)

func solve(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var T int
	Fscan(in, &T)
	for ; T > 0; T-- {
		var n, k int
		Fscan(in, &n, &k)
		a := make([]int64, n+5)
		for i := 1; i <= n; i++ {
			Fscan(in, &a[i])
		}
		var lmax, rmax, nowr, nowl int64
		lmax = int64(0)
		rmax = int64(0)
		nowl = int64(0)
		nowr = int64(0)
		l := k - 1
		r := k + 1
		for l != 0 && r != n+1 {
			if a[k]+lmax+a[r]+nowr >= 0 {
				nowr += a[r]
				r++
				rmax = max(rmax, nowr)
				continue
			}
			if a[k]+rmax+a[l]+nowl >= 0 && l >= 0 {
				nowl += a[l]
				l--
				lmax = max(lmax, nowl)
				continue
			}
			break
		}
		if l == 0 || r == n+1 {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}

}
func main() {
	solve(os.Stdin, os.Stdout)
}
func max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}

package main

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

// https://space.bilibili.com/206214
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	solve := func(curCase int)  bool {
		var n, k int
		Fscan(in, &n, &k)
		k--
		a := make([]int64, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		h := a[k]
		type pair struct{ neg, pos int64 }
		f := func(a []int64) (b []pair) {
			for len(a) > 0 && a[0] > 0 {
				h += a[0]
				a = a[1:]
			}
			for i, n := 0, len(a); i < n; {
				neg := int64(0)
				for {
					for ; i < n && a[i] < 0; i++ {
						neg += a[i]
					}
					if i == n {
						b = append(b, pair{neg, 0})
						break
					}
					pos := int64(0)
					for ; i < n && a[i] > 0; i++ {
						pos += a[i]
					}
					if neg+pos > 0 {
						b = append(b, pair{neg, pos})
						break
					}
					neg += pos
				}
			}
			return
		}
		r := f(a[k+1:])
		tmp := a[:k]
		for i, n := 0, len(tmp); i < n/2; i++ {
			tmp[i], tmp[n-1-i] = tmp[n-1-i], tmp[i]
		}
		l := f(tmp)

		g := func() bool {
			i, j := 0, 0
			n, m := len(l), len(r)
			for i < n && j < m {
				if h + l[i].neg >= 0 {
					h += l[i].neg + l[i].pos
					i++
					continue
				}
				if h + r[j].neg >= 0 {
					h += r[j].neg + r[j].pos
					j++
					continue
				}
				return false
			}
			return true
		}
		return  g()
	}

	cases := 1
	Fscan(in, &cases)
	for curCase := 1; curCase <= cases; curCase++ {
		if solve(curCase) {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}

	leftData, _ := ioutil.ReadAll(in)
	if s := strings.TrimSpace(string(leftData)); s != "" {
		panic("有未读入的数据：\n" + s)
	}

}

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


Welcome to Rockport City!It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet $$$a$$$ dollars and Ronnie has bet $$$b$$$ dollars. But the fans seem to be disappointed. The excitement of the fans is given by $$$gcd(a,b)$$$, where $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. To make the race more exciting, you can perform two types of operations:  Increase both $$$a$$$ and $$$b$$$ by $$$1$$$.  Decrease both $$$a$$$ and $$$b$$$ by $$$1$$$. This operation can only be performed if both $$$a$$$ and $$$b$$$ are greater than $$$0$$$. In one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it.Note that $$$gcd(x,0)=x$$$ for any $$$x \ge 0$$$.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^3$$$) — the number of test cases. The first and the only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0\leq a, b\leq 10^{18}$$$).

For each test case, print a single line containing two integers.  If the fans can get infinite excitement, print 0 0. Otherwise, the first integer must be the maximum excitement the fans can get, and the second integer must be the minimum number of moves required to achieve that excitement.

NoteFor the first test case, you can apply the first operation $$$1$$$ time to get $$$a=9$$$ and $$$b=6$$$. It can be shown that $$$3$$$ is the maximum excitement possible.For the second test case, no matter how many operations you apply, the fans will always have an excitement equal to $$$1$$$. Since the initial excitement is also $$$1$$$, you don't need to apply any operation.For the third case, the fans can get infinite excitement by applying the first operation an infinite amount of times.For the fourth test case, you can apply the second operation $$$3$$$ times to get $$$a=0$$$ and $$$b=6$$$. Since, $$$gcd(0,6)=6$$$, the fans will get an excitement of $$$6$$$.

package main

import (
	"fmt"
)

func main() {
	var t uint64
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	var i uint64
	for i = 0; i < t; i++ {
		var a uint64
		_, err1 := fmt.Scan(&a)
		if err1 != nil {
			panic(err)
		}

		var b uint64
		_, err2 := fmt.Scan(&b)
		if err2 != nil {
			panic(err)
		}

		fmt.Println(solve(a, b))
	}
}

func solve(a uint64, b uint64) (uint64, uint64) {
	if a == b {
		return 0, 0
	}

	if a == 0 {
		return b, 0
	}

	if b == 0 {
		return a, 0
	}

	var bigger uint64
	var lower uint64
	if a > b {
		bigger = a
		lower = b
	} else {
		bigger = b
		lower = a
	}

	var best uint64 = 0
	var minimal uint64 = 0
	if bigger % lower == 0 {
		best = lower
		minimal = 0
	}
	var probably_best = bigger - lower
	if probably_best > best {
		best = probably_best
		minimal = lower % probably_best
		var maybe_even_more_min = probably_best - lower %probably_best
		if maybe_even_more_min < minimal {
			minimal = maybe_even_more_min
		}
	}

	return best, minimal
}

package main

import ."fmt"
//import "sort"
import "bufio"
import "os"
//import ."math"

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

func main() {
    defer writer.Flush()

    var t int
    Fscan(reader, &t)
    for i := 0; i < t; i++ {
        solve()
    }
}
func solve(){
    var a, b int64
    Fscan(reader, &a)
    Fscan(reader, &b)
    Fprint(writer, abs(a - b), " ")
    if b > a {
        temp := a
        a = b
        b = temp
    }
    if a == b {
        Fprintln(writer, 0)
        return
    }
    ost1 := b % abs(a - b)
    ost2 := abs(a - b) - ost1
    if ost2 == abs(a - b) {
        ost2 = 0
    }
    Fprintln(writer, min(ost1, ost2))
}
func abs(x int64) int64 {
    if x < 0 {
        return 0 - x
    }
    return x
}
func min(x, y int64) int64 {
    if x < y {
        return x
    }
    return y
}

package main

import "fmt"

func main() {
	var n int64
	fmt.Scan(&n)
	result := make([]string, 0, n)
	for i := int64(0); i < n; i++ {
		var a,b int64
		fmt.Scan(&a)
		fmt.Scan(&b)
		resg := int64(0)
		resc := int64(0)
		if a == b {
			resg = 0
			resc = 0
		} else if a > b {
			resg = a - b
			resc = b % resg
			resc = min(resc, resg - resc)
		} else {
			resg = b - a
			resc = a % resg
			resc = min(resc, resg - resc)
		}
		result = append(result, fmt.Sprintf("%v %v\n", resg, resc))
	}
	for _, str := range result {
		fmt.Printf(str)
	}
}

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

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

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

func main() {
	defer writer.Flush()
	var t int
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		solve()
	}
}

func solve() {
	var a, b int64
	fmt.Fscan(reader, &a, &b)
	d := abs(a - b)
	if a == b {
		fmt.Fprintln(writer, "0 0")
	} else {
		fmt.Fprintln(writer, d, min( b % d, d - (b % d)))
	}

}

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

func min(nums ...int64) int64 {
	l := len(nums)
	mn := nums[0]
	for i := 0; i < l; i++ {
		if nums[i] < mn {
			mn = nums[i]
		}
	}
	return mn
}

package main

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

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

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

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

func sint64() int64 {
	s := sstring()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

func sstring() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		a := sint64()
		b := sint64()
		x, o := sol(a, b)
		printf("%d %d\n", x, o)
	}
}

func sol(a, b int64) (int64, int64) {
	diff := abs(a - b)
	if diff == 0 {
		return 0, 0
	}
	down := a / diff * diff
	up := down + diff
	return diff, min(a-down, up-a)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

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

// 1543A. Exciting Bets
package main

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

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var a, b int64
		fmt.Fscan(reader, &a, &b)
		if a < b {
			a, b = b, a
		}
		if a == b {
			fmt.Println(0, 0)
		} else {
			ans := a - b
			b = b % ans
			if b < ans-b {
				fmt.Println(ans, b)
			} else {
				fmt.Println(ans, ans-b)
			}
		}

	}
}

package main

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

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

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

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

func main() {
	defer writer.Flush()

	var T int = 0
	scanf("%d\n", &T)

	for t := 0; t < T; t++ {

        var a int64 = 0
        var b int64 = 0

        scanf("%d %d\n", &a, &b)

        if(a == b) {
            printf("0 0\n")
        } else {
            if(a < b) {
                a, b = b, a
            }

            var res_one = a - b
            var res_two = min_int64(b % res_one, res_one - b % res_one)

            printf("%d %d\n", res_one, res_two)
        }

	}

}

package main

import (
	"fmt"
)

func Min(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

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

	if a > b {
		a, b = b, a
	}

	// a < b
	score := b - a
	return score, Min(a%score, score-a%score)

}

func main() {
	t := 0
	fmt.Scan(&t)

	for i := 0; i < t; i++ {
		var a, b int64
		fmt.Scan(&a, &b)
		score, step := task(a, b)
		fmt.Printf("%v %v\n", score, step)
	}

}

package main

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

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

	var t int
	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		var a, b int64
		fmt.Fscan(r, &a, &b)

		solve(a, b)
	}
}

func solve(a, b int64) {
	//23 //17
	var diff int64

	if a == b {
		fmt.Print(0)
		fmt.Print(" ")
		fmt.Println(0)
		return
	}

	if a == 0 {
		fmt.Print(b)
		fmt.Print(" ")
		fmt.Println(0)
		return
	} else if b == 0 {
		fmt.Print(a)
		fmt.Print(" ")
		fmt.Println(0)
		return
	}

	if a > b {
		diff = a - b

		rem1A := a % diff
		rem2A := diff - rem1A

		fmt.Print(diff)
		fmt.Print(" ")
		fmt.Println(min(rem1A, rem2A))

	} else {
		diff = b -  a

		rem1B := b % diff
		rem2B := diff - rem1B

		fmt.Print(diff)
		fmt.Print(" ")
		fmt.Println(min(rem1B, rem2B))
	}
}

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

package main

import (
	"fmt"
)

func main() {
	var t uint64
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	var i uint64
	for i = 0; i < t; i++ {
		var a uint64
		_, err1 := fmt.Scan(&a)
		if err1 != nil {
			panic(err)
		}

		var b uint64
		_, err2 := fmt.Scan(&b)
		if err2 != nil {
			panic(err)
		}

		fmt.Println(solve(a, b))
	}
}

func solve(a uint64, b uint64) (uint64, uint64) {
	if a == b {
		return 0, 0
	}

	if a == 0 {
		return b, 0
	}

	if b == 0 {
		return a, 0
	}

	var bigger uint64
	var lower uint64
	if a > b {
		bigger = a
		lower = b
	} else {
		bigger = b
		lower = a
	}

	var best uint64 = 0
	var minimal uint64 = 0
	if bigger % lower == 0 {
		best = lower
		minimal = 0
	}
	var probably_best = bigger - lower
	if probably_best > best {
		best = probably_best
		minimal = lower
		var maybe_even_more_min = probably_best - lower %probably_best
		if maybe_even_more_min < minimal {
			minimal = maybe_even_more_min
		}
	}

	return best, minimal
}

package main

import (
	"fmt"
)

func main() {
	var t uint64
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	var i uint64
	for i = 0; i < t; i++ {
		var a uint64
		_, err1 := fmt.Scan(&a)
		if err1 != nil {
			panic(err)
		}

		var b uint64
		_, err2 := fmt.Scan(&b)
		if err2 != nil {
			panic(err)
		}

		fmt.Println(solve(a, b))
	}
}

func solve(a uint64, b uint64) (uint64, uint64) {
	if a == b {
		return 0, 0
	}

	if a == 0 {
		return b, 0
	}

	if b == 0 {
		return a, 0
	}

	var bigger uint64
	var lower uint64
	if a > b {
		bigger = a
		lower = b
	} else {
		bigger = b
		lower = a
	}

	var best uint64 = 0
	var minimal uint64 = 0
	if bigger % lower == 0 {
		best = lower
		minimal = 0
	}
	var probably_best = bigger - lower
	if probably_best > best {
		best = probably_best
		minimal = lower
	}
	var maybe_even_more_min = probably_best - lower %probably_best
	if maybe_even_more_min < minimal {
		minimal = maybe_even_more_min
	}
	return best, minimal
}

package main

import (
	"fmt"
)

func main() {
	var t int
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	for i := 0; i < t; i++ {
		var a int
		_, err1 := fmt.Scan(&a)
		if err1 != nil {
			panic(err)
		}

		var b int
		_, err2 := fmt.Scan(&b)
		if err2 != nil {
			panic(err)
		}

		fmt.Println(solve(a, b))
	}
}

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

	var bigger int
	var lower int
	if a > b {
		bigger = a
		lower = b
	} else {
		bigger = b
		lower = a
	}

	if bigger % lower == 0 {
		return lower, 0
	} else {
		var probably_min = bigger - lower
		var maybe_even_more_min = probably_min - lower % probably_min
		if maybe_even_more_min < lower {
			return probably_min, maybe_even_more_min
		} else {
			return probably_min, lower
		}
	}
}

package main

import ."fmt"
//import "sort"
import "bufio"
import "os"
//import ."math"

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

func main() {
    defer writer.Flush()

    var t int
    Fscan(reader, &t)
    for i := 0; i < t; i++ {
        solve()
    }
}
func solve(){
    var a, b int64
    Fscan(reader, &a)
    Fscan(reader, &b)
    Fprint(writer, abs(a - b), " ")
    if b > a {
        temp := a
        a = b
        b = temp
    }
    if a == b {
        Fprintln(writer, 0)
        return
    }
    ost := b % abs(a - b)
    ost = abs(a - b) - ost
    if ost == abs(a - b) {
        ost = 0
    }
    Fprintln(writer, ost)
}
func abs(x int64) int64 {
    if x < 0 {
        return 0 - x
    }
    return x
}

package main

import ."fmt"
//import "sort"
import "bufio"
import "os"
//import ."math"

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

func main() {
    defer writer.Flush()

    var t int
    Fscan(reader, &t)
    for i := 0; i < t; i++ {
        solve()
    }
}
func solve(){
    var a, b int
    Fscan(reader, &a)
    Fscan(reader, &b)
    Fprint(writer, abs(a - b), " ")
    if b > a {
        temp := a
        a = b
        b = temp
    }
    if a == b {
        Fprintln(writer, 0)
        return
    }
    ost := b % abs(a - b)
    ost = abs(a - b) - ost
    if ost == abs(a - b) {
        ost = 0
    }
    Fprintln(writer, ost)
}
func abs(x int) int {
    if x < 0 {
        return 0 - x
    }
    return x
}

package main

import "fmt"

func main() {
	var n int64
	fmt.Scan(&n)
	result := make([]string, 0, n)
	for i := int64(0); i < n; i++ {
		var a,b int64
		_, err := fmt.Scanf("%v %v", &a, &b)
		if err != nil {
			fmt.Printf("%v\n", err)
		}
		resg := int64(0)
		resc := int64(0)
		if a == b {
			resg = 0
			resc = 0
		} else if a > b {
			resg = a - b
			resc = b % resg
			resc = min(resc, resg - resc)
		} else {
			resg = b - a
			resc = a % resg
			resc = min(resc, resg - resc)
		}
		result = append(result, fmt.Sprintf("%v %v\n", resg, resc))
	}
	for _, str := range result {
		fmt.Printf(str)
	}
}

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

package main

import "fmt"

func main() {
	var n int64
	fmt.Scan(&n)
	result := make([]string, 0, n)
	for i := int64(0); i < n; i++ {
		var a,b int64
		fmt.Scanf("%v %v", &a, &b)
		resg := int64(0)
		resc := int64(0)
		if a == b {
			resg = 0
			resc = 0
		} else if a > b {
			resg = a - b
			resc = b % resg
			resc = min(resc, resg - resc)
		} else {
			resg = b - a
			resc = a % resg
			resc = min(resc, resg - resc)
		}
		result = append(result, fmt.Sprintf("%v %v\n", resg, resc))
	}
	for _, str := range result {
		fmt.Printf(str)
	}
}

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

package main

import "fmt"

func main() {
	var n int64
	fmt.Scan(&n)
	for i := int64(0); i < n; i++ {
		var a,b int64
		fmt.Scanf("%v %v", &a, &b)
		resg := int64(0)
		resc := int64(0)
		if a == b {
			resg = 0
			resc = 0
		} else if a > b {
			resg = a - b
			resc = b % resg
			resc = min(resc, resg - resc)
		} else {
			resg = b - a
			resc = a % resg
			resc = min(resc, resg - resc)
		}
		fmt.Printf("%v %v\n", resg, resc)
	}

}

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

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

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

func main() {
	defer writer.Flush()
	var t int
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		solve()
	}
}

func solve() {
	var a, b int
	fmt.Fscan(reader, &a, &b)
	d := abs(a - b)
	if a == b {
		fmt.Fprintln(writer, "0 0")
	} else {
		k := b % d
		kk := d - (b % d)
		fmt.Fprintln(writer, d, min( k, kk))
	}

}

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

func min(nums ...int) int {
	l := len(nums)
	mn := nums[0]
	for i := 0; i < l; i++ {
		if nums[i] < mn {
			mn = nums[i]
		}
	}
	return mn
}

package main

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

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

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

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

func sint64() int64 {
	s := sstring()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

func sstring() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		a := sint64()
		b := sint64()
		x, o := sol(a, b)
		printf("%d %d\n", x, o)
	}
}

func sol(a, b int64) (int64, int64) {
	diff := abs(a - b)
	if diff == 0 {
		return 0, 0
	}
	return diff, round(a, diff) - a
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func round(a, n int64) int64 {
	if a%n == 0 {
		return a
	}
	return a/n*n + n
}