You are given a connected undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Vertices of the graph are numbered by integers from $$$1$$$ to $$$n$$$ and edges of the graph are numbered by integers from $$$1$$$ to $$$m$$$.Your task is to answer $$$q$$$ queries, each consisting of two integers $$$l$$$ and $$$r$$$. The answer to each query is the smallest non-negative integer $$$k$$$ such that the following condition holds:   For all pairs of integers $$$(a, b)$$$ such that $$$l\le a\le b\le r$$$, vertices $$$a$$$ and $$$b$$$ are reachable from one another using only the first $$$k$$$ edges (that is, edges $$$1, 2, \ldots, k$$$).

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$q$$$ ($$$2\le n\le 10^5$$$, $$$1\le m, q\le 2\cdot 10^5$$$) — the number of vertices, edges, and queries respectively. Each of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1\le u_i, v_i\le n$$$) — ends of the $$$i$$$-th edge. It is guaranteed that the graph is connected and there are no multiple edges or self-loops. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1\le l\le r\le n$$$) — descriptions of the queries. It is guaranteed that that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases does not exceed $$$2\cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print $$$q$$$ integers — the answers to the queries.

Note  Graph from the first test case. The integer near the edge is its number. In the first test case, the graph contains $$$2$$$ vertices and a single edge connecting vertices $$$1$$$ and $$$2$$$.In the first query, $$$l=1$$$ and $$$r=1$$$. It is possible to reach any vertex from itself, so the answer to this query is $$$0$$$.In the second query, $$$l=1$$$ and $$$r=2$$$. Vertices $$$1$$$ and $$$2$$$ are reachable from one another using only the first edge, through the path $$$1 \longleftrightarrow 2$$$. It is impossible to reach vertex $$$2$$$ from vertex $$$1$$$ using only the first $$$0$$$ edges. So, the answer to this query is $$$1$$$.  Graph from the second test case. The integer near the edge is its number. In the second test case, the graph contains $$$5$$$ vertices and $$$5$$$ edges.In the first query, $$$l=1$$$ and $$$r=4$$$. It is enough to use the first $$$3$$$ edges to satisfy the condition from the statement:   Vertices $$$1$$$ and $$$2$$$ are reachable from one another through the path $$$1 \longleftrightarrow 2$$$ (edge $$$1$$$).  Vertices $$$1$$$ and $$$3$$$ are reachable from one another through the path $$$1 \longleftrightarrow 3$$$ (edge $$$2$$$).  Vertices $$$1$$$ and $$$4$$$ are reachable from one another through the path $$$1 \longleftrightarrow 2 \longleftrightarrow 4$$$ (edges $$$1$$$ and $$$3$$$).  Vertices $$$2$$$ and $$$3$$$ are reachable from one another through the path $$$2 \longleftrightarrow 1 \longleftrightarrow 3$$$ (edges $$$1$$$ and $$$2$$$).  Vertices $$$2$$$ and $$$4$$$ are reachable from one another through the path $$$2 \longleftrightarrow 4$$$ (edge $$$3$$$).  Vertices $$$3$$$ and $$$4$$$ are reachable from one another through the path $$$3 \longleftrightarrow 1 \longleftrightarrow 2 \longleftrightarrow 4$$$ (edges $$$2$$$, $$$1$$$, and $$$3$$$). If we use less than $$$3$$$ of the first edges, then the condition won't be satisfied. For example, it is impossible to reach vertex $$$4$$$ from vertex $$$1$$$ using only the first $$$2$$$ edges. So, the answer to this query is $$$3$$$.In the second query, $$$l=3$$$ and $$$r=4$$$. Vertices $$$3$$$ and $$$4$$$ are reachable from one another through the path $$$3 \longleftrightarrow 1 \longleftrightarrow 2 \longleftrightarrow 4$$$ (edges $$$2$$$, $$$1$$$, and $$$3$$$). If we use any fewer of the first edges, nodes $$$3$$$ and $$$4$$$ will not be reachable from one another.

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, m, q := readThreeNums(reader)
		edges := make([][]int, m)
		for i := 0; i < m; i++ {
			edges[i] = readNNums(reader, 2)
		}
		Q := make([][]int, q)
		for i := 0; i < q; i++ {
			Q[i] = readNNums(reader, 2)
		}
		res := solve(n, edges, Q)
		for i := 0; i < q; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}

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

const H = 20

func solve(n int, edges [][]int, Q [][]int) []int {
	set := NewUF(n)

	F := make([]int, n)

	groups := make([][]int, n)
	for i := 0; i < n; i++ {
		groups[i] = make([]int, 0, 1)
		groups[i] = append(groups[i], i)
	}

	for i, edge := range edges {
		u, v := edge[0], edge[1]
		u--
		v--
		pu := set.Find(u)
		pv := set.Find(v)
		if pu == pv {
			continue
		}
		// will connect
		if set.sz[pu] < set.sz[pv] {
			pu, pv = pv, pu
		}
		// sz[pu] > sz[pv]
		for _, x := range groups[pv] {
			if x > 0 && set.Find(x-1) == pu {
				F[x] = i + 1
			}
			if x+1 < n && set.Find(x+1) == pu {
				F[x+1] = i + 1
			}
		}

		set.sz[pu] += set.sz[pv]
		set.arr[pv] = pu
		groups[pu] = append(groups[pu], groups[pv]...)
	}

	return findAns(n, F, Q)
}

func solve1(n int, edges [][]int, Q [][]int) []int {

	g := NewGraph(n, 2*(n-1))

	set := NewUF(n)

	for i, edge := range edges {
		u, v := edge[0], edge[1]
		u--
		v--
		if set.Union(u, v) {
			g.AddEdge(u, v, i+1)
			g.AddEdge(v, u, i+1)
		}
	}

	D := make([]int, n)
	P := make([][]int, n)
	C := make([][]int, n)
	var dfs func(p, u, w int)

	dfs = func(p, u, w int) {
		P[u] = make([]int, H)
		C[u] = make([]int, H)
		P[u][0] = p
		C[u][0] = w
		for i := 1; i < H; i++ {
			x := P[u][i-1]
			P[u][i] = P[x][i-1]
			C[u][i] = max(C[u][i-1], C[x][i-1])
		}

		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p != v {
				D[v] = D[u] + 1
				dfs(u, v, g.cost[i])
			}
		}
	}

	dfs(0, 0, 0)

	find_cost := func(u int, v int) int {
		if D[u] < D[v] {
			u, v = v, u
		}
		var res int
		for i := H - 1; i >= 0; i-- {
			if (D[u] - (1 << i)) >= D[v] {
				res = max(res, C[u][i])
				u = P[u][i]
			}
		}
		if u == v {
			return res
		}

		for i := H - 1; i >= 0; i-- {
			if P[u][i] != P[v][i] {
				res = max(res, C[u][i])
				res = max(res, C[v][i])
				u = P[u][i]
				v = P[v][i]
			}
		}
		return max(max(res, C[u][0]), C[v][0])
	}

	// F[i] = max_cost to connect i & i - 1
	F := make([]int, n)

	for i := 1; i < n; i++ {
		F[i] = find_cost(i-1, i)
	}

	return findAns(n, F, Q)
}

func findAns(n int, F []int, Q [][]int) []int {
	arr := make([]int, 2*n)

	copy(arr[n:], F)

	for i := n - 1; i > 0; i-- {
		arr[i] = max(arr[i*2], arr[i*2+1])
	}

	get := func(l, r int) int {
		l += n
		r += n
		var res int

		for l < r {
			if l&1 == 1 {
				res = max(res, arr[l])
				l++
			}
			if r&1 == 1 {
				r--
				res = max(res, arr[r])
			}
			l >>= 1
			r >>= 1
		}
		return res
	}

	ans := make([]int, len(Q))
	for i := 0; i < len(Q); i++ {
		l, r := Q[i][0]-1, Q[i][1]
		ans[i] = get(l+1, r)
	}
	return ans
}

type Graph struct {
	node []int
	next []int
	to   []int
	cost []int
	cur  int
}

func NewGraph(n int, e int) *Graph {
	g := new(Graph)
	g.node = make([]int, n)
	g.next = make([]int, e+1)
	g.to = make([]int, e+1)
	g.cost = make([]int, e+1)
	g.cur = 0
	return g
}

func (g *Graph) AddEdge(u, v, w int) {
	g.cur++
	g.next[g.cur] = g.node[u]
	g.node[u] = g.cur
	g.to[g.cur] = v
	g.cost[g.cur] = w
}

type UF struct {
	arr []int
	sz  []int
}

func NewUF(n int) *UF {
	arr := make([]int, n)
	sz := make([]int, n)
	for i := 0; i < n; i++ {
		sz[i]++
		arr[i] = i
	}

	return &UF{arr, sz}
}

func (uf *UF) Find(x int) int {
	if uf.arr[x] != x {
		uf.arr[x] = uf.Find(uf.arr[x])
	}
	return uf.arr[x]
}

func (uf *UF) Union(a, b int) bool {
	pa := uf.Find(a)
	pb := uf.Find(b)
	if pa == pb {
		return false
	}
	if uf.sz[pa] < uf.sz[pb] {
		pa, pb = pb, pa
	}

	uf.sz[pa] += uf.sz[pb]
	uf.arr[pb] = pa
	return true
}

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
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, m, q := readThreeNums(reader)
		edges := make([][]int, m)
		for i := 0; i < m; i++ {
			edges[i] = readNNums(reader, 2)
		}
		Q := make([][]int, q)
		for i := 0; i < q; i++ {
			Q[i] = readNNums(reader, 2)
		}
		res := solve(n, edges, Q)
		for i := 0; i < q; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}

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

const H = 20

func solve(n int, edges [][]int, Q [][]int) []int {

	g := NewGraph(n, 2*(n-1))

	set := NewUF(n)

	for i, edge := range edges {
		u, v := edge[0], edge[1]
		u--
		v--
		if set.Union(u, v) {
			g.AddEdge(u, v, i+1)
			g.AddEdge(v, u, i+1)
		}
	}

	D := make([]int, n)
	P := make([][]int, n)
	C := make([][]int, n)
	var dfs func(p, u, w int)

	dfs = func(p, u, w int) {
		P[u] = make([]int, H)
		C[u] = make([]int, H)
		P[u][0] = p
		C[u][0] = w
		for i := 1; i < H; i++ {
			x := P[u][i-1]
			P[u][i] = P[x][i-1]
			C[u][i] = max(C[u][i-1], C[x][i-1])
		}

		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p != v {
				D[v] = D[u] + 1
				dfs(u, v, g.cost[i])
			}
		}
	}

	dfs(0, 0, 0)

	find_cost := func(u int, v int) int {
		if D[u] < D[v] {
			u, v = v, u
		}
		var res int
		for i := H - 1; i >= 0; i-- {
			if (D[u] - (1 << i)) >= D[v] {
				res = max(res, C[u][i])
				u = P[u][i]
			}
		}
		if u == v {
			return res
		}

		for i := H - 1; i >= 0; i-- {
			if P[u][i] != P[v][i] {
				res = max(res, C[u][i])
				res = max(res, C[v][i])
				u = P[u][i]
				v = P[v][i]
			}
		}
		return max(max(res, C[u][0]), C[v][0])
	}

	// F[i] = max_cost to connect i & i - 1
	F := make([]int, n)

	for i := 1; i < n; i++ {
		F[i] = find_cost(i-1, i)
	}

	arr := make([]int, 2*n)

	copy(arr[n:], F)

	for i := n - 1; i > 0; i-- {
		arr[i] = max(arr[i*2], arr[i*2+1])
	}

	get := func(l, r int) int {
		l += n
		r += n
		var res int

		for l < r {
			if l&1 == 1 {
				res = max(res, arr[l])
				l++
			}
			if r&1 == 1 {
				r--
				res = max(res, arr[r])
			}
			l >>= 1
			r >>= 1
		}
		return res
	}

	ans := make([]int, len(Q))
	for i := 0; i < len(Q); i++ {
		l, r := Q[i][0]-1, Q[i][1]
		ans[i] = get(l+1, r)
	}
	return ans
}

type Graph struct {
	node []int
	next []int
	to   []int
	cost []int
	cur  int
}

func NewGraph(n int, e int) *Graph {
	g := new(Graph)
	g.node = make([]int, n)
	g.next = make([]int, e+1)
	g.to = make([]int, e+1)
	g.cost = make([]int, e+1)
	g.cur = 0
	return g
}

func (g *Graph) AddEdge(u, v, w int) {
	g.cur++
	g.next[g.cur] = g.node[u]
	g.node[u] = g.cur
	g.to[g.cur] = v
	g.cost[g.cur] = w
}

type UF struct {
	arr []int
	sz  []int
}

func NewUF(n int) *UF {
	arr := make([]int, n)
	sz := make([]int, n)
	for i := 0; i < n; i++ {
		sz[i]++
		arr[i] = i
	}

	return &UF{arr, sz}
}

func (uf *UF) Find(x int) int {
	if uf.arr[x] != x {
		uf.arr[x] = uf.Find(uf.arr[x])
	}
	return uf.arr[x]
}

func (uf *UF) Union(a, b int) bool {
	pa := uf.Find(a)
	pb := uf.Find(b)
	if pa == pb {
		return false
	}
	if uf.sz[pa] < uf.sz[pb] {
		pa, pb = pb, pa
	}

	uf.sz[pa] += uf.sz[pb]
	uf.arr[pb] = pa
	return true
}

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
}

package main

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

const MOD int64 = 1000000007

var n, m, q int

var a[][2]int

var qu [][2]int

var maxEdge[]int
var log []int

var mps []*map[int]bool

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

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

type Item struct {
	rightEnd int
	divideBy int
}

const LOCAL = false

type segmentTree struct {
	n int
	t []int64
}

func create(n int) *segmentTree {
	return &segmentTree{n : n, t : make([]int64, 4 * n)}
}

func (s *segmentTree) build(a []int64, v int, tl int, tr int) {
	if tl == tr {
		s.t[v] = a[tl]
	} else {
		tm := (tl + tr) / 2;
		s.build(a, v*2, tl, tm)
		s.build(a, v*2+1, tm+1, tr)
		s.t[v] = max(s.t[v*2], s.t[v*2+1])
	}
}

func (s *segmentTree) get(v int, tl int, tr int, l int, r int) int64 {
	if l > r {
		return 0
	}
	if l == tl && r == tr {
		return s.t[v]
	}

	tm := (tl + tr) / 2
	return max(s.get(v*2, tl, tm, l, minInt(r, tm)), s.get(v*2+1, tm+1, tr, maxInt(l, tm+1), r))
}

func (s *segmentTree) update(v int, tl int, tr int, pos int, newVal int64) {
	if tl == tr {
		s.t[v] = newVal
	} else {
		tm := (tl + tr) / 2
		if pos <= tm {
			s.update(v*2, tl, tm, pos, newVal)
		} else {
			s.update(v*2+1, tm+1, tr, pos, newVal)
		}

		s.t[v] = max(s.t[v*2], s.t[v*2+1])
	}
}

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

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

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

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

func main() {

	read := bufio.NewReader(os.Stdin)

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

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

		fmt.Fscan(read, &n, &m, &q)

		a = make([][2]int, m)

		for j := 0; j < m; j++ {
			fmt.Fscan(read, &a[j][0], &a[j][1])
		}

		qu = make([][2]int, q)

		for j := 0; j < q; j++ {
			fmt.Fscan(read, &qu[j][0], &qu[j][1])
		}

		solve()
		fmt.Println()
	}
}

type pair struct {
	v int
	idx []int
}

func solve()  {
	maxEdge = make([]int, n + 1)
	log = make([]int, n + 1)

	mps = make([]*map[int]bool, n + 1)

	for i := 0; i < m; i++ {
		from, to := a[i][0], a[i][1]

		if mps[from] != nil {

			if mps[to] == nil {
				(*mps[from])[to] = true
				mps[to] = mps[from]
				check(to, i + 1)

			} else {
				if mps[from] == mps[to] {
					continue
				}

				if len(*mps[from]) > len(*mps[to]) {

					m := *mps[to]

					for k, _ := range *mps[to] {
						(*mps[from])[k] = true
						mps[k] = mps[from]
						check(k, i + 1)

						delete(m, k)
					}

				} else {

					m := *mps[from]

					for k, _ := range *mps[from] {
						(*mps[to])[k] = true
						mps[k] = mps[to]
						check(k, i + 1)

						delete(m, k)
					}
				}
			}

		} else {

			if mps[to] == nil {

				mp := make(map[int]bool)
				mp[from] = true
				mp[to] = true
				mps[from] = &mp
				mps[to] = &mp

				check(from, i + 1)

			} else {
				(*mps[to])[from] = true
				mps[from] = mps[to]
				check(from, i + 1)
			}
		}
	}

	//123456789

	const LOG = 18
	st := make([][LOG]int, n + 1)

	for i := 1; i < n ; i ++ {
		st[i][1] = maxEdge[i]
	}

	for j := 2; j < 18; j++ {
		for i := 1; i + (1 << uint(j)) - 1 <= n  ; i++ {
			st[i][j] = maxInt(maxInt(st[i][j - 1], st[i + (1 << uint(j - 1)) - 1][1]), st[i + (1 << uint(j - 1)) ][j - 1])
		}
	}

	log[1] = 0

	for i := 2; i <= n; i++ {
		log[i] = log[i/2] + 1
	}

	for i := 0; i < q; i++ {
		query := qu[i]

		if query[0] == query[1] {
			fmt.Print(0, " ")
			continue
		}

		L := query[0]
		R := query[1]
		l := R - L + 1

		var ans int

		pwr := log[l]

		ans = maxInt(st[L][pwr], st[R - (1 << uint(pwr)) + 1][pwr])

		fmt.Print(ans, " ")
	}

	//1 -> 2 , 2 -> 3, 3 -> 4, ...
}

func check(v int, vl int) {
	if v != 1 {
		if (*mps[v])[v - 1] {
			if maxEdge[v - 1] == 0 {
				maxEdge[v - 1] = vl
			}
		}
	}
	if v != n {
		if (*mps[v])[v + 1] {
			if maxEdge[v] == 0 {
				maxEdge[v] = vl
			}
		}
	}
}

func connected(a, b int, parent *[]int) bool {
	rootA := find(parent, a)
	rootB := find(parent, b)

	if rootA==rootB {
		return true
	}
	return false

}

func find(parent *[]int, p int) int {
	for ; p != (*parent)[p]; {
		(*parent)[p] = (*parent)[(*parent)[p]]
		p = (*parent)[p]
	}

	return p
}

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

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, m, q := readThreeNums(reader)
		edges := make([][]int, m)
		for i := 0; i < m; i++ {
			edges[i] = readNNums(reader, 2)
		}
		Q := make([][]int, q)
		for i := 0; i < q; i++ {
			Q[i] = readNNums(reader, 2)
		}
		res := solve(n, edges, Q)
		for i := 0; i < q; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}

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

const H = 20

func solve(n int, edges [][]int, Q [][]int) []int {

	g := NewGraph(n, 2*(n-1))

	set := NewUF(n)

	for i, edge := range edges {
		u, v := edge[0], edge[1]
		u--
		v--
		if set.Union(u, v) {
			g.AddEdge(u, v, i+1)
			g.AddEdge(v, u, i+1)
		}
	}

	D := make([]int, n)
	P := make([][]int, n)
	C := make([][]int, n)
	var dfs func(p, u, w int)

	dfs = func(p, u, w int) {
		P[u] = make([]int, H)
		C[u] = make([]int, H)
		P[u][0] = p
		C[u][0] = w
		for i := 1; i < H; i++ {
			x := P[u][i-1]
			P[u][i] = P[x][i-1]
			C[u][i] = max(C[u][i-1], C[x][i-1])
		}

		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p != v {
				D[v] = D[u] + 1
				dfs(u, v, g.cost[i])
			}
		}
	}

	dfs(0, 0, 0)

	find_cost := func(u int, v int) int {
		if D[u] < D[v] {
			u, v = v, u
		}
		var res int
		for i := H - 1; i >= 0; i-- {
			if (D[u] - (1 << i)) >= D[v] {
				res = max(res, C[u][i])
				u = P[u][i]
			}
		}
		if u == v {
			return res
		}

		for i := H - 1; i >= 0; i-- {
			if P[u][i] != P[v][i] {
				res = max(res, C[u][i])
				res = max(res, C[v][i])
				u = P[u][i]
				v = P[v][i]
			}
		}
		return max(res, C[u][0])
	}

	// F[i] = max_cost to connect i & i - 1
	F := make([]int, n)

	for i := 1; i < n; i++ {
		F[i] = find_cost(i-1, i)
	}

	arr := make([]int, 2*n)

	copy(arr[n:], F)

	for i := n - 1; i > 0; i-- {
		arr[i] = max(arr[i*2], arr[i*2+1])
	}

	get := func(l, r int) int {
		l += n
		r += n
		var res int

		for l < r {
			if l&1 == 1 {
				res = max(res, arr[l])
				l++
			}
			if r&1 == 1 {
				r--
				res = max(res, arr[r])
			}
			l >>= 1
			r >>= 1
		}
		return res
	}

	ans := make([]int, len(Q))
	for i := 0; i < len(Q); i++ {
		l, r := Q[i][0]-1, Q[i][1]
		ans[i] = get(l+1, r)
	}
	return ans
}

type Graph struct {
	node []int
	next []int
	to   []int
	cost []int
	cur  int
}

func NewGraph(n int, e int) *Graph {
	g := new(Graph)
	g.node = make([]int, n)
	g.next = make([]int, e+1)
	g.to = make([]int, e+1)
	g.cost = make([]int, e+1)
	g.cur = 0
	return g
}

func (g *Graph) AddEdge(u, v, w int) {
	g.cur++
	g.next[g.cur] = g.node[u]
	g.node[u] = g.cur
	g.to[g.cur] = v
	g.cost[g.cur] = w
}

type UF struct {
	arr []int
	sz  []int
}

func NewUF(n int) *UF {
	arr := make([]int, n)
	sz := make([]int, n)
	for i := 0; i < n; i++ {
		sz[i]++
		arr[i] = i
	}

	return &UF{arr, sz}
}

func (uf *UF) Find(x int) int {
	if uf.arr[x] != x {
		uf.arr[x] = uf.Find(uf.arr[x])
	}
	return uf.arr[x]
}

func (uf *UF) Union(a, b int) bool {
	pa := uf.Find(a)
	pb := uf.Find(b)
	if pa == pb {
		return false
	}
	if uf.sz[pa] < uf.sz[pb] {
		pa, pb = pb, pa
	}

	uf.sz[pa] += uf.sz[pb]
	uf.arr[pb] = pa
	return true
}

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
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, m, q := readThreeNums(reader)
		edges := make([][]int, m)
		for i := 0; i < m; i++ {
			edges[i] = readNNums(reader, 2)
		}
		Q := make([][]int, q)
		for i := 0; i < q; i++ {
			Q[i] = readNNums(reader, 2)
		}
		res := solve(n, edges, Q)
		for i := 0; i < q; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}

	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' || 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(n int, edges [][]int, Q [][]int) []int {
	qs := make([]Query, len(Q))

	for i := 0; i < len(Q); i++ {
		qs[i] = Query{Q[i][0] - 1, Q[i][1] - 1, i}
	}

	sort.Slice(qs, func(i, j int) bool {
		return qs[i].r < qs[j].r
	})

	set := NewUF(n)

	var events []Event

	for i := 0; i < len(edges); i++ {
		cur := edges[i]
		a, b := cur[0], cur[1]
		a--
		b--
		if set.Union(a, b) {
			pa := set.Find(a)
			x, y := set.mn[pa], set.mx[pa]
			sz := set.sz[pa]
			if y-x+1 == sz {
				// this ia a full connection
				// 前i条边，使得 [x..y]全联通
				events = append(events, Event{x, y, i})
			}
		}
	}

	sort.Slice(events, func(i, j int) bool {
		return events[i].Less(events[j])
	})

	ans := make([]int, len(qs))

	// 希望知道的是 events[i].l <= qs[j].l && qs[j].r <= events[i].r

	pq := make(PQ, 0, len(qs))

	for i, j := 0, 0; i < len(events); i++ {

		for j < len(qs) && qs[j].r <= events[i].r {
			heap.Push(&pq, qs[j])
			j++
		}
		for pq.Len() > 0 && pq[0].l >= events[i].l {
			cur := heap.Pop(&pq).(Query)
			ans[cur.id] = events[i].k + 1
		}
	}

	for i := 0; i < len(Q); i++ {
		if Q[i][0] == Q[i][1] {
			ans[i] = 0
		}
	}

	return ans
}

type Event struct {
	l int
	r int
	k int
}

func (this Event) Less(that Event) bool {
	if this.r < that.r {
		return true
	}
	if this.r == that.r {
		return this.l > that.l
	}
	return false
}

type Query struct {
	l  int
	r  int
	id int
}

type PQ []Query

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

func (pq PQ) Less(i, j int) bool {
	return pq[i].l > pq[j].l
}

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

func (pq *PQ) Push(x interface{}) {
	*pq = append(*pq, x.(Query))
}

func (pq *PQ) Pop() interface{} {
	old := *pq
	n := len(old)
	ret := old[n-1]
	*pq = old[:n-1]
	return ret
}

type UF struct {
	arr []int
	sz  []int
	mn  []int
	mx  []int
}

func NewUF(n int) *UF {
	arr := make([]int, n)
	sz := make([]int, n)
	mx := make([]int, n)
	mn := make([]int, n)
	for i := 0; i < n; i++ {
		mn[i] = i
		mx[i] = i
		sz[i]++
		arr[i] = i
	}

	return &UF{arr, sz, mn, mx}
}

func (uf *UF) Find(x int) int {
	if uf.arr[x] != x {
		uf.arr[x] = uf.Find(uf.arr[x])
	}
	return uf.arr[x]
}

func (uf *UF) Union(a, b int) bool {
	pa := uf.Find(a)
	pb := uf.Find(b)
	if pa == pb {
		return false
	}
	if uf.sz[pa] < uf.sz[pb] {
		pa, pb = pb, pa
	}

	uf.mn[pa] = min(uf.mn[pa], uf.mn[pb])
	uf.mx[pa] = max(uf.mx[pa], uf.mx[pb])

	uf.sz[pa] += uf.sz[pb]
	uf.arr[pb] = pa
	return true
}

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
}

package main

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

const MOD int64 = 1000000007

var n, m, q int

var a[][2]int

var qu [][2]int

var maxEdge[]int
var log []int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

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

type Item struct {
	rightEnd int
	divideBy int
}

const LOCAL = false

type segmentTree struct {
	n int
	t []int64
}

func create(n int) *segmentTree {
	return &segmentTree{n : n, t : make([]int64, 4 * n)}
}

func (s *segmentTree) build(a []int64, v int, tl int, tr int) {
	if tl == tr {
		s.t[v] = a[tl]
	} else {
		tm := (tl + tr) / 2;
		s.build(a, v*2, tl, tm)
		s.build(a, v*2+1, tm+1, tr)
		s.t[v] = max(s.t[v*2], s.t[v*2+1])
	}
}

func (s *segmentTree) get(v int, tl int, tr int, l int, r int) int64 {
	if l > r {
		return 0
	}
	if l == tl && r == tr {
		return s.t[v]
	}

	tm := (tl + tr) / 2
	return max(s.get(v*2, tl, tm, l, minInt(r, tm)), s.get(v*2+1, tm+1, tr, maxInt(l, tm+1), r))
}

func (s *segmentTree) update(v int, tl int, tr int, pos int, newVal int64) {
	if tl == tr {
		s.t[v] = newVal
	} else {
		tm := (tl + tr) / 2
		if pos <= tm {
			s.update(v*2, tl, tm, pos, newVal)
		} else {
			s.update(v*2+1, tm+1, tr, pos, newVal)
		}

		s.t[v] = max(s.t[v*2], s.t[v*2+1])
	}
}

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

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

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

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

func main() {

	read := bufio.NewReader(os.Stdin)

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

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

		fmt.Fscan(read, &n, &m, &q)

		a = make([][2]int, m)

		for j := 0; j < m; j++ {
			fmt.Fscan(read, &a[j][0], &a[j][1])
		}

		qu = make([][2]int, q)

		for j := 0; j < q; j++ {
			fmt.Fscan(read, &qu[j][0], &qu[j][1])
		}

		solve()
		fmt.Println()
	}
}

type pair struct {
	v int
	idx []int
}

func solve()  {
	parent := make([]int, n + 1)
	rank := make([]int, n + 1)
	maxEdge = make([]int, n + 1)
	log = make([]int, n + 1)

	for i := 0; i < n; i++ {
		parent[i] = i
		rank[i] = 0
	}

	for i := 0; i < m;  i++ {
		ed := a[i]

		from := ed[0]
		to := ed[1]

		rootA := find(&parent, from)
		rootB := find(&parent, to)

		if rootA==rootB {
			continue
		}

		if  (rank)[rootA] < (rank)[rootB]{
			(parent)[rootA] = rootB

		} else if (rank)[rootA] > (rank)[rootB] {
			(parent)[rootB] = rootA

		} else {
			(parent)[rootB] = rootA
			(rank)[rootA]++
		}

		//maxEdge[1] = 5,  max edge on path from 1 to 2 is 5
		//maxEdge[n - 1] = 10  max edge on path from n - 1 to n is 10

		//from - 1, from
		//from, from + 1
		//to - 1, to
		//to, to + 1

		if from != 1 {
			if connected(from - 1, from, &parent) {
				if maxEdge[from - 1] == 0 {
					maxEdge[from - 1] = i + 1
				}
			}
		}
		if from != n {
			if connected(from, from + 1, &parent) {
				if maxEdge[from] == 0 {
					maxEdge[from] = i + 1
				}
			}
		}

		if to != 1 {
			if connected(to - 1, to, &parent) {
				if maxEdge[to - 1] == 0 {
					maxEdge[to - 1] = i + 1
				}
			}
		}
		if to != n {
			if connected(to, to + 1, &parent) {
				if maxEdge[to] == 0 {
					maxEdge[to] = i + 1
				}
			}
		}
	}

	//123456789

	const LOG = 18
	st := make([][LOG]int, n + 1)

	for i := 1; i < n ; i ++ {
		st[i][1] = maxEdge[i]
	}

	for j := 2; j < 18; j++ {
		for i := 1; i + (1 << uint(j)) - 1 <= n  ; i++ {
			st[i][j] = maxInt(maxInt(st[i][j - 1], st[i + (1 << uint(j - 1)) - 1][1]), st[i + (1 << uint(j - 1)) ][j - 1])
		}
	}

	log[1] = 0

	for i := 2; i <= n; i++ {
		log[i] = log[i/2] + 1
	}

	for i := 0; i < q; i++ {
		query := qu[i]

		if query[0] == query[1] {
			fmt.Print(0, " ")
			continue
		}

		L := query[0]
		R := query[1]
		l := R - L + 1

		var ans int

		pwr := log[l]

		ans = maxInt(st[L][pwr], st[R - (1 << uint(pwr)) + 1][pwr])

		fmt.Print(ans, " ")
	}

	//1 -> 2 , 2 -> 3, 3 -> 4, ...
}

func connected(a, b int, parent *[]int) bool {
	rootA := find(parent, a)
	rootB := find(parent, b)

	if rootA==rootB {
		return true
	}
	return false

}

func find(parent *[]int, p int) int {
	for ; p != (*parent)[p]; {
		(*parent)[p] = (*parent)[(*parent)[p]]
		p = (*parent)[p]
	}

	return p
}

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


Casimir has a rectangular piece of paper with a checkered field of size $$$n \times m$$$. Initially, all cells of the field are white.Let us denote the cell with coordinates $$$i$$$ vertically and $$$j$$$ horizontally by $$$(i, j)$$$. The upper left cell will be referred to as $$$(1, 1)$$$ and the lower right cell as $$$(n, m)$$$.Casimir draws ticks of different sizes on the field. A tick of size $$$d$$$ ($$$d > 0$$$) with its center in cell $$$(i, j)$$$ is drawn as follows:   First, the center cell $$$(i, j)$$$ is painted black.  Then exactly $$$d$$$ cells on the top-left diagonally to the center and exactly $$$d$$$ cells on the top-right diagonally to the center are also painted black.  That is all the cells with coordinates $$$(i - h, j \pm h)$$$ for all $$$h$$$ between $$$0$$$ and $$$d$$$ are painted. In particular, a tick consists of $$$2d + 1$$$ black cells. An already painted cell will remain black if painted again. Below you can find an example of the $$$4 \times 9$$$ box, with two ticks of sizes $$$2$$$ and $$$3$$$.  You are given a description of a checkered field of size $$$n \times m$$$. Casimir claims that this field came about after he drew some (possibly $$$0$$$) ticks on it. The ticks could be of different sizes, but the size of each tick is at least $$$k$$$ (that is, $$$d \ge k$$$ for all the ticks).Determine whether this field can indeed be obtained by drawing some (possibly none) ticks of sizes $$$d \ge k$$$ or not.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number test cases. The following lines contain the descriptions of the test cases.  The first line of the test case description contains the integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le k \le n \le 10$$$; $$$1 \le m \le 19$$$) — the field size and the minimum size of the ticks that Casimir drew. The following $$$n$$$ lines describe the field: each line consists of $$$m$$$ characters either being '.' if the corresponding cell is not yet painted or '*' otherwise.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if the given field can be obtained by drawing ticks of at least the given size and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).

NoteThe first sample test case consists of two asterisks neither of which can be independent ticks since ticks of size $$$0$$$ don't exist.The second sample test case is already described in the statement (check the picture in the statement). This field can be obtained by drawing ticks of sizes $$$2$$$ and $$$3$$$, as shown in the figure.The field in the third sample test case corresponds to three ticks of size $$$1$$$. Their center cells are marked with $$$\color{blue}{\text{blue}}$$$, $$$\color{red}{\text{red}}$$$ and $$$\color{green}{\text{green}}$$$ colors: *.*.*$$$\color{blue}{\textbf{*}}$$$**.$$$\color{green}{\textbf{*}}\color{red}{\textbf{*}}$$$.....The field in the fourth sample test case could have been obtained by drawing two ticks of sizes $$$1$$$ and $$$2$$$. Their vertices are marked below with $$$\color{blue}{\text{blue}}$$$ and $$$\color{red}{\text{red}}$$$ colors respectively: .....*...*.*.*...$$$\color{red}{\textbf{*}}$$$.*...$$$\color{blue}{\textbf{*}}$$$.The field in the fifth sample test case can not be obtained because $$$k = 2$$$, and the last asterisk in the fourth row from the top with coordinates $$$(4, 5)$$$ can only be a part of a tick of size $$$1$$$.The field in the sixth sample test case can not be obtained because the top left asterisk $$$(1, 1)$$$ can't be an independent tick, since the sizes of the ticks must be positive, and cannot be part of a tick with the center cell in the last row, since it is separated from it by a gap (a point, '.') in $$$(2, 2)$$$.In the seventh sample test case, similarly, the field can not be obtained by the described process because the asterisks with coordinates $$$(1, 2)$$$ (second cell in the first row), $$$(3, 1)$$$ and $$$(3, 3)$$$ (leftmost and rightmost cells in the bottom) can not be parts of any ticks.

package main

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

var n, m , k int

var f []string

func main() {

	read := bufio.NewReader(os.Stdin)

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

	for i := 0; i < t; i++ {
		fmt.Fscan(read, &n, &m, &k)

		f = make([]string, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &f[j])
		}

		fmt.Println(solve())
	}
}

func solve() string {

	for  i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if f[i][j] == '*' {

				leftCountUp := 0
				for d := 1; d <= min(i, j); d ++ {
					if f [i - d][j - d] == '*' {
						leftCountUp++
					} else {
						break
					}
				}

				rightCountUp := 0
				for d := 1; d <= i && d < (m - j); d ++ {
					if f [i - d][j + d] == '*' {
						rightCountUp++
					} else {
						break
					}
				}

				if min(leftCountUp, rightCountUp) >= k {
					continue
				}

				can := false
				downCount := 0

				for d := 0; d < min(n - i, m - j); d++ {
					if f [i + d][j + d] == '*' {

						x := i + d
						y := j + d

						c := 0

						for k := 1; k <= x && k < (m - y); k++ {
							if f[x - k][y + k] == '*' {
								c++
							} else {
								break
							}
						}

						if c >= downCount && min(leftCountUp, c) >= k {
							can = true
							break
						}

						leftCountUp++
						downCount++

					} else {
						break
					}
				}
				if can {
					continue
				}

				downCount = 0
				can = false
				for d := 0; d <= j && d < (n - i); d ++ {
					if f[i + d][j - d] == '*' {

						x := i + d
						y := j - d

						c := 0

						for k := 1; k <= min(x, y); k++ {
							if f[x - k][y - k] == '*' {
								c++
							} else {
								break
							}
						}

						if c >= downCount && min(rightCountUp, c) >= k {
							can = true
							break
						}

						downCount++
						rightCountUp++
					} else {
						break
					}

				}

				if !can {
					return "NO"
				}
			}
		}
	}

	return "YES"
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	dots := ".................................................................."
	var test int
	fmt.Fscan(in, &test)
	for ; test > 0; test-- {
		var n, m, kk int
		fmt.Fscan(in, &n, &m, &kk)

		grid := make([][]byte, n)
		used := make([][]byte, n)
		var s string
		for i := range grid {
			fmt.Fscan(in, &s)
			grid[i] = []byte(s)
			used[i] = []byte(dots[:m])
		}

		for i := range grid {
			for j := range grid[i] {
				if grid[i][j] == '*' && isRoot(i, j, grid) {
					c := 0
					for k := 1; k <= i; k++ {
						left := j - k
						right := j + k
						if left >= 0 && right < m &&
							grid[i-k][left] == '*' && grid[i-k][right] == '*' {
							c++
						} else {
							break
						}
					}
					if c >= kk {
						for k := 1; k <= c; k++ {
							left := j - k
							right := j + k
							used[i-k][left] = '*'
							used[i-k][right] = '*'
						}
						used[i][j] = '*'
					}
				}
			}
		}

		isPossible := true
		for i := range used {
			for j := range used[i] {
				if grid[i][j] != used[i][j] {
					isPossible = false
				}
			}
		}
		if isPossible {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

func isRoot(i, j int, grid [][]byte) bool {
	if i == 0 || j == 0 || j == len(grid[0])-1 {
		return false
	}
	return grid[i-1][j-1] == '*' && grid[i-1][j+1] == '*'
}

package main

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

//problem C

type problem struct {
	N, M, K int
	data    [][]byte
}

func (p *problem) Scanf(reader *bufio.Reader) {
	for i := 0; i < p.N; i++ {
		fmt.Fscanf(reader, "%s\n", &p.data[i])
	}
}

func (p *problem) printf() {
	for i := 0; i < p.N; i++ {
		fmt.Printf("%s\n", p.data[i])
	}
}

func (p *problem) dfs(i, j int) int {
	var d int = 0
	for d = 0; ; d++ {

		if (p.data[i-d][j-d] == '*' || p.data[i-d][j-d] == 'M') &&
			(p.data[i-d][j+d] == '*' || p.data[i-d][j+d] == 'M') {
		} else {
			d--
			break
		}

		if i-d == 0 || j-d == 0 || j+d == p.M-1 {
			break
		}

	}
	return d
}

func (p *problem) mark(i, j, d int) {
	for k := 0; k <= d; k++ {
		p.data[i-k][j-k] = 'M'
		p.data[i-k][j+k] = 'M'
	}
}

func (p *problem) Run() bool {
	for i := p.N - 1; i >= 0; i-- {
		for j := p.M - 1; j >= 0; j-- {
			if p.data[i][j] == '*' || p.data[i][j] == 'M' {
				d := p.dfs(i, j)
				if d >= p.K {
					p.mark(i, j, d)
				} else if p.data[i][j] == 'M' {

				} else {
					return false
				}
			}
		}
	}
	return true
}

func NewProblem(n, m, k int) *problem {
	p := &problem{
		N:    n,
		M:    m,
		K:    k,
		data: make([][]byte, n),
	}

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

	return p
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var t, n, m, k int
	fmt.Fscanf(reader, "%d\n", &t)
	for ; t > 0; t-- {
		fmt.Fscanf(reader, "%d %d %d\n", &n, &m, &k)
		p := NewProblem(n, m, k)
		p.Scanf(reader)
		// p.printf()
		if p.Run() {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

var in = bufio.NewReader(os.Stdin)

func findMaxTickSize(y, x int, grid [][]byte) int {
	if grid[y][x] == '.' {
		return -1
	}
	m := len(grid[0])

	i := 0
	for ; ; i++ {
		if y-i < 0 {
			break
		}
		if x-i < 0 || x+i >= m {
			break
		}
		if grid[y-i][x-i] == '.' || grid[y-i][x+i] == '.' {
			break
		}
	}
	return i - 1
}

func paintTick(y, x int, grid [][]byte, size int) {
	for i := 0; i <= size; i++ {
		grid[y-i][x-i] = 'v'
		grid[y-i][x+i] = 'v'
	}
}

func solve() {
	var n, m, k int
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	fmt.Fscan(in, &k)

	grid := make([][]byte, n)
	for i := range grid {
		var tmp string
		fmt.Fscan(in, &tmp)
		grid[i] = []byte(tmp)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			size := findMaxTickSize(i, j, grid)
			if size >= k {
				paintTick(i, j, grid, size)
			}
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if grid[i][j] == '*' {
				fmt.Println("NO")
				return
			}
		}
	}
	fmt.Println("YES")
}

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

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1579C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var T, n, m, k int
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m, &k)
		a := make([][]byte, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		for i := n - 1; i >= k; i-- {
			for j, b := range a[i] {
				if b != '.' {
					l, r := 1, 1
					for ; i >= l && j >= l && a[i-l][j-l] != '.'; l++ {
					}
					for ; i >= r && j+r < m && a[i-r][j+r] != '.'; r++ {
					}
					if r < l {
						l = r
					}
					if l > k {
						for l--; l >= 0; l-- {
							a[i-l][j-l] = 0
							a[i-l][j+l] = 0
						}
					}
				}
			}
		}
		for _, r := range a {
			for _, v := range r {
				if v == '*' {
					Fprintln(out, "NO")
					continue o
				}
			}
		}
		Fprintln(out, "YES")
	}
}

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

package main

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

type shift struct {
	b, e, d int
}

func main() {
	r := bufio.NewReaderSize(os.Stdin, 1024*1024)

	var T int
	fmt.Fscanf(r, "%d\n", &T)

	for t := 0; t < T; t++ {
		var n, m, k int
		fmt.Fscanf(r, "%d %d %d\n", &n, &m, &k)

		arr := make([]string, n)
		used := make([][]bool, n)

		for i := 0; i < n; i++ {
			used[i] = make([]bool, m)
			fmt.Fscanf(r, "%s\n", &arr[i])
		}

		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				if arr[i][j] == '*' {
					l := 1
					for i-l >= 0 && j-l >= 0 && j+l < m && arr[i-l][j-l] == '*' && arr[i-l][j+l] == '*' {
						l++
					}
					if l > k {
						used[i][j] = true
						for l--; l > 0; l-- {
							used[i-l][j-l] = true
							used[i-l][j+l] = true
						}
					}
				}
			}
		}

		fail := false
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				if !used[i][j] && arr[i][j] == '*' {
					fail = true
				}
			}
		}

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

package main

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

var n, m , k int

var f []string

func main() {

	read := bufio.NewReader(os.Stdin)

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

	for i := 0; i < t; i++ {
		fmt.Fscan(read, &n, &m, &k)

		f = make([]string, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &f[j])
		}

		fmt.Println(solve())
	}
}

func solve() string {

	for  i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if f[i][j] == '*' {

				leftCountUp := 0
				for d := 1; d <= min(i, j); d ++ {
					if f [i - d][j - d] == '*' {
						leftCountUp++
					} else {
						break
					}
				}

				rightCountUp := 0
				for d := 1; d <= i && d < (m - j); d ++ {
					if f [i - d][j + d] == '*' {
						rightCountUp++
					} else {
						break
					}
				}

				if min(leftCountUp, rightCountUp) >= k {
					continue
				}

				leftCountUp = 0
				rightCountUp = 0

				can := false

				for d := 0; d < min(n - i, m - j); d++ {
					if f [i + d][j + d] == '*' {

						x := i + d
						y := j + d

						c := 0

						for k := 1; k <= x && k < (m - y); k++ {
							if f[x - k][y + k] == '*' {
								c++
							} else {
								break
							}
						}

						if min(leftCountUp, c) >= k {
							can = true
							break
						}

						leftCountUp++
					} else {
						break
					}
				}
				if can {
					continue
				}

				can = false
				for d := 0; d <= j && d < (n - i); d ++ {
					if f[i + d][j - d] == '*' {

						x := i + d
						y := j - d

						c := 0

						for k := 1; k <= min(x, y); k++ {
							if f[x - k][y - k] == '*' {
								c++
							} else {
								break
							}
						}

						if min(rightCountUp, c) >= k {
							can = true
							break
						}

						rightCountUp++
					} else {
						break
					}

				}

				if !can {
					return "NO"
				}
			}
		}
	}

	return "YES"
}

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

package main

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

var n, m , k int

var f []string

func main() {

	read := bufio.NewReader(os.Stdin)

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

	for i := 0; i < t; i++ {
		fmt.Fscan(read, &n, &m, &k)

		f = make([]string, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &f[j])
		}

		fmt.Println(solve())
	}
}

func solve() string {

	for  i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if f[i][j] == '*' {

				leftCountUp := 0
				for d := 1; d <= min(i, j); d ++ {
					if f [i - d][j - d] == '*' {
						leftCountUp++
					} else {
						break
					}
				}

				rightCountUp := 0
				for d := 1; d <= i && d < (m - j); d ++ {
					if f [i - d][j + d] == '*' {
						rightCountUp++
					} else {
						break
					}
				}

				can := false

				for d := 0; d < min(n - i, m - j); d++ {
					if f [i + d][j + d] == '*' {

						x := i + d
						y := j + d

						c := 0

						for k := 1; k <= x && k < (m - y); k++ {
							if f[x - k][y + k] == '*' {
								c++
							} else {
								break
							}
						}

						if min(leftCountUp, c) >= k {
							can = true
							break
						}

						leftCountUp++
					} else {
						break
					}
				}
				if can {
					continue
				}

				can = false
				for d := 0; d <= j && d < (n- i); d ++ {
					if f[i + d][j - d] == '*' {

						x := i + d
						y := j - d

						c := 0

						for k := 1; k <= min(x, y); k++ {
							if f[x - k][y - k] == '*' {
								c++
							} else {
								break
							}
						}

						if min(rightCountUp, c) >= k {
							can = true
							break
						}

						rightCountUp++
					} else {
						break
					}

				}

				if !can {
					return "NO"
				}
			}
		}
	}

	return "YES"
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	dots := ".................................................................."
	var test int
	fmt.Fscan(in, &test)
	for ; test > 0; test-- {
		var n, m, kk int
		fmt.Fscan(in, &n, &m, &kk)

		grid := make([][]byte, n)
		used := make([][]byte, n)
		var s string
		for i := range grid {
			fmt.Fscan(in, &s)
			grid[i] = []byte(s)
			used[i] = []byte(dots[:m])
		}

		for i := range grid {
			for j := range grid[i] {
				if grid[i][j] == '*' && isRoot(i, j, grid) {
					c := 0
					for k := 1; k <= i; k++ {
						left := j - k
						right := j + k
						if left >= 0 && right < m &&
							grid[i-k][left] == '*' && grid[i-k][right] == '*' {
							c++
						} else {
							break
						}
					}
					if c >= kk {
						for k := 1; k <= c; k++ {
							left := j - k
							right := j + k
							used[i-k][left] = '*'
							used[i-k][right] = '*'
						}
						used[i][j] = '*'
					}
				}
			}
		}

		isPossible := true
		for i := range used {
			for j := range used[i] {
				if grid[i][j] != used[i][j] {
					isPossible = false
				}
			}
		}
		if isPossible {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

func isRoot(i, j int, grid [][]byte) bool {
	if i == 0 || j == 0 || j == len(grid[0])-1 {
		return false
	}
	fmt.Println(i, j)
	return grid[i-1][j-1] == '*' && grid[i-1][j+1] == '*'
}

package main

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

//problem C

type problem struct {
	N, M, K int
	data    [][]byte
}

func (p *problem) Scanf(reader *bufio.Reader) {
	for i := 0; i < p.N; i++ {
		fmt.Fscanf(reader, "%s\n", &p.data[i])
	}
}

func (p *problem) printf() {
	for i := 0; i < p.N; i++ {
		fmt.Printf("%s\n", p.data[i])
	}
}

func (p *problem) dfs(i, j int) int {
	var d int = 0
	for d = 0; i-d >= 0 && j-d >= 0 && j+d < p.M; d++ {

		if (p.data[i-d][j-d] == '*' || p.data[i-d][j-d] == 'M') &&
			(p.data[i-d][j+d] == '*' || p.data[i-d][j+d] == 'M') {
		} else {
			d--
			break
		}
	}
	return d - 1
}

func (p *problem) mark(i, j, d int) {
	for k := 0; k <= d; k++ {
		p.data[i-k][j-k] = 'M'
		p.data[i-k][j+k] = 'M'
	}
}

func (p *problem) Run() bool {
	for i := p.N - 1; i >= 0; i-- {
		for j := p.M - 1; j >= 0; j-- {
			if p.data[i][j] == '*' || p.data[i][j] == 'M' {
				d := p.dfs(i, j)
				if d >= p.K {
					p.mark(i, j, d)
				} else if p.data[i][j] == 'M' {

				} else {
					return false
				}
			}
		}
	}
	return true
}

func NewProblem(n, m, k int) *problem {
	p := &problem{
		N:    n,
		M:    m,
		K:    k,
		data: make([][]byte, n),
	}

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

	return p
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var t, n, m, k int
	fmt.Fscanf(reader, "%d\n", &t)
	for ; t > 0; t-- {
		fmt.Fscanf(reader, "%d %d %d\n", &n, &m, &k)
		p := NewProblem(n, m, k)
		p.Scanf(reader)
		//p.printf()
		if p.Run() {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}


Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1, a2, ..., an, where ai denotes the distance of the i-th mark from the origin (a1 = 0, an = l).Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 ≤ i ≤ j ≤ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj - ai = d). Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y. Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.

The first line contains four positive space-separated integers n, l, x, y (2 ≤ n ≤ 105, 2 ≤ l ≤ 109, 1 ≤ x < y ≤ l) — the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly. The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance from the i-th mark to the origin.

In the first line print a single non-negative integer v — the minimum number of marks that you need to add on the ruler. In the second line print v space-separated integers p1, p2, ..., pv (0 ≤ pi ≤ l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them.

NoteIn the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark.In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks.In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills.

package main

import (
	"bufio"
	"bytes"
	"errors"
	"io"
	"math/rand"
	"os"
	"strconv"
	"time"
	"unicode/utf8"
)

// ******************************** CODE STARTS ********************************

const (
)

var (
)

func solve() {
	n := readInt()
	l := readInt()
	x := readInt()
	y := readInt()
	array := make([]int, n)
	point := make(map[int]bool)
	for i := 0; i < n; i++ {
		array[i] = readInt()
		point[array[i]] = true
	}

	fx := false
	fy := false
	for i := 0; i < n; i++ {
		_, ok := point[array[i] + x];
		if array[i] + x <= l && ok {
			fx = true
		}
		_, ok = point[array[i] + y];
		if array[i] + y <= l && ok {
			fy = true
		}
	}

	if fx && fy {
		printInt(0)
		printLine()
		return
	}

	if fx {
		printInt(1)
		printLine()
		printInt(y)
		printLine()
		return
	}
	if fy {
		printInt(1)
		printLine()
		printInt(x)
		printLine()
		return
	}

	mark := make(map[int]bool)
	for i := 0; i < n; i++ {
		if array[i] + x <= l {
			mark[array[i] + x] = true
		}
		if array[i] - x >= 0 {
			mark[array[i] - x] = true
		}
	}
	for i := 0; i < n; i++ {
		_, ok := mark[array[i] + y];
		if ok {
			printInt(1)
			printLine()
			printInt(array[i] + y)
			printLine()
			return
		}
		_, ok = mark[array[i] - y];
		if ok {
			printInt(1)
			printLine()
			printInt(array[i] - y)
			printLine()
			return
		}
	}

	printInt(2)
	printLine()
	printInt(x)
	printSpace()
	printInt(y)
	printLine()
	return
}

// ********************************* CODE ENDS *********************************

// IO.

var (
	scanner *Scanner
	writer  *bufio.Writer
)

func main() {
	input := os.Stdin
	output := os.Stdout
	//	input, _ := os.Open("")
	//	output, _ := os.Create("")

	defer input.Close()
	defer output.Close()

	scanner = NewScanner(input)
	scanner.Split(bufio.ScanWords)

	writer = bufio.NewWriter(output)
	defer writer.Flush()

	rand.Seed(int64(time.Now().Nanosecond()))
	solve()
}

// Read.

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

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

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

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

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

func printLine() {
	printString("\n")
}

func printSpace() {
	printString(" ")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFloat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Tuple

type Tuple struct {
	a, b int
}

func (p Tuple) Equals(key Key) bool {
	return p.a == key.(Tuple).a
}

func (p Tuple) Less(key Key) bool {
	return p.a < key.(Tuple).a
}

// Sorting

type TupleSlice []Tuple

func (p TupleSlice) Len() int {
	return len(p)
}

func (p TupleSlice) Less(j, i int) bool {
	if p[j].a == p[i].a {
		return p[j].b < p[i].b
	} else {
		return p[j].a < p[i].a
	}
}

func (p TupleSlice) Swap(j, i int) {
	p[j], p[i] = p[i], p[j]
}

// Min, max, abs.

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

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

func absInt(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

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

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

func absInt64(a int64) int64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absFloat64(a float64) float64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

// Copied scan.go
// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
	r            io.Reader // The reader provided by the client.
	split        SplitFunc // The function to split the tokens.
	maxTokenSize int       // Maximum size of a token; modified by tests.
	token        []byte    // Last token returned by split.
	buf          []byte    // Buffer used as argument to split.
	start        int       // First non-processed byte in buf.
	end          int       // End of data in buf.
	err          error     // Sticky error.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
	ErrTooLong         = errors.New("bufio.Scanner: token too long")
	ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
	ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
	// Maximum size used to buffer a token. The actual maximum token size
	// may be smaller as the buffer may need to include, for instance, a newline.
	MaxScanTokenSize = 1 << 20
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
		buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
	}
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
	return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
	return string(s.token)
}

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
func (s *Scanner) Scan() bool {
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is neded.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0; ; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
	if n < 0 {
		s.setErr(ErrNegativeAdvance)
		return false
	}
	if n > s.end-s.start {
		s.setErr(ErrAdvanceTooFar)
		return false
	}
	s.start += n
	return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
	if s.err == nil || s.err == io.EOF {
		s.err = err
	}
}

// Split sets the split function for the Scanner. If called, it must be
// called before Scan. The default split function is ScanLines.
func (s *Scanner) Split(split SplitFunc) {
	s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	// Fast path 1: ASCII.
	if data[0] < utf8.RuneSelf {
		return 1, data[0:1], nil
	}

	// Fast path 2: Correct UTF-8 decode without error.
	_, width := utf8.DecodeRune(data)
	if width > 1 {
		// It's a valid encoding. Width cannot be one for a correctly encoded
		// non-ASCII rune.
		return width, data[0:width], nil
	}

	// We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
	// Is the error because there wasn't a full rune to be decoded?
	// FullRune distinguishes correctly between erroneous and incomplete encodings.
	if !atEOF && !utf8.FullRune(data) {
		// Incomplete; get more bytes.
		return 0, nil, nil
	}

	// We have a real UTF-8 encoding error. Return a properly encoded error rune
	// but advance only one byte. This matches the behavior of a range loop over
	// an incorrectly encoded string.
	return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[0 : len(data)-1]
	}
	return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, dropCR(data[0:i]), nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), dropCR(data), nil
	}
	// Request more data.
	return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
	if r <= '\u00FF' {
		// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
		switch r {
		case ' ', '\t', '\n', '\v', '\f', '\r':
			return true
		case '\u0085', '\u00A0':
			return true
		}
		return false
	}
	// High-valued ones.
	if '\u2000' <= r && r <= '\u200a' {
		return true
	}
	switch r {
	case '\u1680', '\u180e', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
		return true
	}
	return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	// Skip leading spaces.
	start := 0
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSpace(r) {
			break
		}
	}
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSpace(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return 0, nil, nil
}


You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.You have to determine the length of the longest balanced substring of s.

The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.

If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.

NoteIn the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.In the second example it's impossible to find a non-empty balanced substring.

package main
import(
	"fmt"
)
func main() {
	var str string
	var n int
	var pos map[int](int)
	pos = make(map[int]int)
	pos[0] = 0
	var dp []int
	fmt.Scanf("%d\n", &n)
	fmt.Scanf("%s\n", &str)
	res := 0
	for i := 0; i < len(str); i++{
		now := 0
		if i != 0{
			now = dp[i - 1]
		}
		if str[i] == '0'{
			dp = append(dp, now - 1)
		}else{
			dp = append(dp, now + 1)
		}
		_, ok := pos[dp[i]]
		if ok{
			len := i - pos[dp[i]] + 1
			res = Max873(res, len)
		}else{
			pos[dp[i]] = i + 1
		}
	}
	fmt.Println(res)
}

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

package main

import (
    "fmt"
)

func main () {
    var size int
    fmt.Scanf("%d\n", &size)
    var str string
    fmt.Scanf("%s", &str)
    first := make(map[int]int)
    first[0] = -1
    max := 0
    sum := 0
    bb := []byte(str)
    for i :=0 ; i < size; i++ {
        var t = int(bb[i] - '0')
        if t == 0 {
            sum--
        } else {
            sum++
        }
        if v, ok := first[sum]; ok {
            max = getmax(max, i-v)
        } else {
            first[sum] = i
        }
    }

    fmt.Println(max)
}

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

    return b
}

package main

import (
	"fmt"
)

func main() {
	var s string
	var tot, ans, n int
	fmt.Scanf("%d\n%s", &n, &s)
	m := make(map[int]int)
	m[0], tot, ans = 0, 0, 0
	for i, b := range s {
	    tot = tot + 2 * int(b&1) -1
		v, ok := m[tot]
		if !ok {
			m[tot] = i+1
		} else if i-v+1 > ans {
			ans = i - v+1
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

var index[200020] int

const seek = 100010

func main(){
	var n int
	fmt.Scan( &n)
	var str string
	fmt.Scan(&str)
	total := 0
	ans := 0
	for idx, c := range str{
		if c == '1'{
			total++
		}else{
			total--
		}
		if index[seek + total] > 0{
			if idx - index[seek + total] > ans{
				ans = idx + 1 - index[seek + total]
			}
		}else{
			index[seek + total] = idx + 1
		}
		if 0 == total{
			ans = idx + 1
		}
	}
	fmt.Println(ans)

}

package main

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

func main() {
	var n int
	var s string
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n%s", &n, &s)
	aa, r := make([]int, n*2+1), 0
	for i := range aa {
		aa[i] = -2
	}
	aa[n] = -1
	for i, c := range s {
		if c == '1' {
			n++
		} else {
			n--
		}
		if aa[n] == -2 {
			aa[n] = i
		} else {
			i -= aa[n]
			if r < i {
				r = i
			}
		}
	}
	fmt.Println(r)
}

package main

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

const INF = 1 << 20

func main() {
	var n int
	var s string
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n%s", &n, &s)
	aa, bb, r := make([]int, n*2+1), make([]int, n*2+1), 0
	for i := range aa {
		aa[i] = INF
	}
	aa[n] = -1
	for i, c := range s {
		if c == '1' {
			n++
		} else {
			n--
		}
		if aa[n] == INF {
			aa[n] = i
		} else {
			bb[n] = i
		}
	}
	for i, b := range bb {
		if b != 0 {
			b -= aa[i]
			if r < b {
				r = b
			}
		}
	}
	fmt.Println(r)
}

package main

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

func key(c int) int {
	return c + 100001
}

func main() {
	var n int
	var s string
	var first [200004] int

	stdin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(stdin, "%d\n", &n)
	fmt.Fscanf(stdin,"%s", &s)

	c := 0
	ans := -1
	for i := 0; i < n; i++ {
		if s[i] == '0' {
			c--
		} else {
			c++
		}
		if first[key(c)] != 0 && i - first[key(c)] > ans {
			ans = i - first[key(c)]
		}
		if c == 0 && i > ans {
			ans = i
		}
		if first[key(c)] == 0 {
			first[key(c)] = i + 1
		}
	}

	fmt.Printf("%d\n", ans + 1)
}

package main

import (
    "fmt"
)

func main () {
    var size int
    fmt.Scanf("%d\n", &size)

    first := make(map[int]int)
    first[0] = -1
    max := 0
    sum := 0
    for i :=0 ; i < size; i++ {
        var t = 0
        fmt.Scanf("%d", &t)
        if t == 0 {
            sum--
        } else {
            sum++
        }
        if v, ok := first[sum]; ok {
            max = getmax(max, i-v)
        } else {
            first[sum] = i
        }
    }

    fmt.Println(max)
}

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

    return b
}

package main

import (
	"fmt"
)

var index[200010] int

const seek = 100010

func main(){
	var n int
	fmt.Scan( &n)
	var str string
	fmt.Scan(&str)
	total := 0
	ans := 0
	for idx, c := range str{
		if c == '1'{
			total++
		}else{
			total--
		}
		if index[seek + total] > 0{
			if idx - index[seek + total] > ans{
				ans = idx - index[seek + total]
			}
		}else{
			index[seek + total] = idx
		}
		if 0 == total{
			ans = idx
		}
	}
	fmt.Println(ans)

}

package main

import (
	"fmt"
)

var index[200020] int

const seek = 100010

func main(){
	var n int
	fmt.Scan( &n)
	var str string
	fmt.Scan(&str)
	total := 0
	ans := 0
	for idx, c := range str{
		if c == '1'{
			total++
		}else{
			total--
		}
		if index[seek + total] > 0{
			if idx - index[seek + total] > ans{
				ans = idx - index[seek + total]
			}
		}else{
			index[seek + total] = idx
		}
		if 0 == total{
			ans = idx + 1
		}
	}
	fmt.Println(ans)

}

package main

import "fmt"

const INF = 1 << 20

func main() {
	var n int
	var s string
	fmt.Scan(&n)
	fmt.Scanln(&s)
	aa, bb, r := make([]int, n*2+1), make([]int, n*2+1), 0
	for i := range aa {
		aa[i] = INF
	}
	aa[n] = -1
	for i, c := range s {
		if c == '1' {
			n++
		} else {
			n--
		}
		if aa[n] == INF {
			aa[n] = i
		} else {
			bb[n] = i
		}
	}
	for i, b := range bb {
		if b != 0 {
			b -= aa[i]
			if r < b {
				r = b
			}
		}
	}
	fmt.Println(r)
}

package main

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

func key(c int) int {
	return c + 100001
}

func main() {
	var n int
	var s string
	var first [200004] int

	stdin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(stdin, "%d\n", &n)
	fmt.Fscanf(stdin,"%s", &s)

	c := 0
	ans := -1
	for i := 0; i < n; i++ {
		if s[i] == '0' {
			c--
		} else {
			c++
		}
		if first[key(c)] != 0 && i - first[key(c)] > ans {
			ans = i - first[key(c)]
		}
		if first[key(c)] == 0 {
			first[key(c)] = i + 1
		}
	}

	fmt.Printf("%d\n", ans + 1)
}


$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.

The first line contains two integers $$$n$$$ and $$$m$$$, separated with space — the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spaces — $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spaces — $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).

If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.

NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.

// Author: sighduck
// URL: https://codeforces.com/contest/1159/problem/C

package main

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

func readArray(size int64, reader *bufio.Reader) []int64 {
	arr := make([]int64, size)
	for i := int64(0); i < size; i++ {
		fmt.Fscanf(reader, "%d", &arr[i])
	}
	fmt.Fscanf(reader, "\n")
	return arr
}

func sum(arr []int64) int64 {
	sum := int64(0)
	for _, elem := range arr {
		sum += elem
	}
	return sum
}

func Solve(n int64, m int64, b []int64, g []int64) int64 {
	sort.Slice(b, func(i, j int) bool { return b[i] < b[j] })
	sort.Slice(g, func(i, j int) bool { return g[i] < g[j] })
	maxB1 := b[n-1]
	maxB2 := b[n-2]
	minG := g[0]
	if maxB1 > minG {
		return -1
	} else if maxB1 == minG {
		return sum(g) + m*(sum(b)-maxB1)
	}
	return sum(g) + m*(sum(b)-maxB1-maxB2) + maxB1 + (m-1)*maxB2
}

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

	var n, m int64
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	b := readArray(n, reader)
	g := readArray(m, reader)

	fmt.Fprintf(writer, "%d\n", Solve(n, m, b, g))
}