You are given a permutation $$$a_1,a_2,\ldots,a_n$$$ of integers from $$$0$$$ to $$$n - 1$$$. Your task is to find how many permutations $$$b_1,b_2,\ldots,b_n$$$ are similar to permutation $$$a$$$. Two permutations $$$a$$$ and $$$b$$$ of size $$$n$$$ are considered similar if for all intervals $$$[l,r]$$$ ($$$1 \le l \le r \le n$$$), the following condition is satisfied: $$$$$$\operatorname{MEX}([a_l,a_{l+1},\ldots,a_r])=\operatorname{MEX}([b_l,b_{l+1},\ldots,b_r]),$$$$$$ where the $$$\operatorname{MEX}$$$ of a collection of integers $$$c_1,c_2,\ldots,c_k$$$ is defined as the smallest non-negative integer $$$x$$$ which does not occur in collection $$$c$$$. For example, $$$\operatorname{MEX}([1,2,3,4,5])=0$$$, and $$$\operatorname{MEX}([0,1,2,4,5])=3$$$.Since the total number of such permutations can be very large, you will have to print its remainder modulo $$$10^9+7$$$.In this problem, a permutation of size $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n-1$$$ in arbitrary order. For example, $$$[1,0,2,4,3]$$$ is a permutation, while $$$[0,1,1]$$$ is not, since $$$1$$$ appears twice in the array. $$$[0,1,3]$$$ is also not a permutation, since $$$n=3$$$ and there is a $$$3$$$ in the array.

Each test contains multiple test cases. The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of permutation $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0 \le a_i \lt n$$$) — the elements of permutation $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer, the number of permutations similar to permutation $$$a$$$, taken modulo $$$10^9+7$$$.

NoteFor the first test case, the only permutations similar to $$$a=[4,0,3,2,1]$$$ are $$$[4,0,3,2,1]$$$ and $$$[4,0,2,3,1]$$$.For the second and third test cases, the given permutations are only similar to themselves.For the fourth test case, there are $$$4$$$ permutations similar to $$$a=[1,2,4,0,5,3]$$$:   $$$[1,2,4,0,5,3]$$$;  $$$[1,2,5,0,4,3]$$$;  $$$[1,4,2,0,5,3]$$$;  $$$[1,5,2,0,4,3]$$$.

package main

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

const mod = 998244353
const mx = int64(1e9 + 7)

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int64
	fmt.Fscan(in, &n)
	arr := make([]int64, n)
	for i := int64(0); i < n; i++ {
		fmt.Fscan(in, &arr[i])

	}
	p := make([]int64, n+1)
	for i := int64(0); i < n; i++ {
		p[arr[i]] = i
	}
	l := p[0]
	r := p[0]
	ans := int64(1)
	for i := int64(1); i < n; i++ {
		if p[i] < l {
			l = p[i]
		} else if p[i] > r {
			r = p[i]
		} else {
			ans *= r - l + 1 - i
			ans %= int64(1e9 + 7)
		}
	}
	fmt.Fprintln(out, ans)
}

func abs(a int64) int64 {
	if a > 0 {
		return a
	}
	return -a
}
func sum(a, b int64) int64 {
	return (b + a) * (b - a + 1) / 2
}

func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

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

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int) []float64  { res := make([]float64,n); for i:=0;i<n;i++ { res[i] = gf() }; return res }
func gss(n int) []string  { res := make([]string,n); for i:=0;i<n;i++ { res[i] = gs() }; return res }
func gi64() int64     { i,e := strconv.ParseInt(gs(),10,64); if e != nil {panic(e)}; return i }
func gis64(n int) []int64  { res := make([]int64,n); for i:=0;i<n;i++ { res[i] = gi64() }; return res }

func ia(m int) []int { return make([]int,m) }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi(n int,m int,v int) [][]int {
	r := make([][]int,n); for i:=0;i<n;i++ { x := make([]int,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int) ([]int,[]int,[]int) { a,b,c := ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int) ([]int,[]int,[]int,[]int) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int) int { if a < 0 { return -a }; return a }
func rev(a []int) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max(a,b int) int { if a > b { return a }; return b }
func min(a,b int) int { if a > b { return b }; return a }
func maxarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int) int { ans := 0; for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod(a,e,mod int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int) int { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int) (int,int,int) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int) (int,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
func makefact(n int,mod int) ([]int,[]int) {
	fact,factinv := make([]int,n+1),make([]int,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}

func ia64(m int) []int64 { return make([]int64,m) }
func iai64(m int,v int64) []int64 { a := make([]int64,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi64(n int,m int,v int64) [][]int64 {
	r := make([][]int64,n); for i:=0;i<n;i++ { x := make([]int64,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill264(m int) ([]int64,[]int64) { a,b := ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i] = gi64(),gi64()}; return a,b }
func fill364(m int) ([]int64,[]int64,[]int64) { a,b,c := ia64(m),ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi64(),gi64(),gi64()}; return a,b,c }
func fill464(m int) ([]int64,[]int64,[]int64,[]int64) { a,b,c,d := ia64(m),ia64(m),ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi64(),gi64(),gi64(),gi64()}; return a,b,c,d }
func abs64(a int64) int64 { if a < 0 { return -a }; return a }
func rev64(a []int64) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max64(a,b int64) int64 { if a > b { return a }; return b }
func min64(a,b int64) int64 { if a > b { return b }; return a }
func maxarr64(a []int64) int64 { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr64(a []int64) int64 { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr64(a []int64) int64 { ans := int64(0); for _,aa := range(a) { ans += aa }; return ans }
func zeroarr64(a []int64) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod64(a,e,mod int64) int64 { res, m := int64(1), a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint64(a,e int64) int64 { res, m := int64(1), a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd64(a,b int64) int64 { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended64(a,b int64) (int64,int64,int64) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended64(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv64(a,m int64) (int64,bool) { g,x,_ := gcdExtended64(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func vecint64string(a []int64) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.FormatInt(a,10) }; return strings.Join(astr," ") }
func makefact64(n int,mod int64) ([]int64,[]int64) {
	fact,factinv := make([]int64,n+1),make([]int64,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * int64(i) % mod }
	factinv[n] = powmod64(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * int64(i+1) % mod }
	return fact,factinv
}
const MOD int64 = 1000000007
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N := gi(); A := gis(N)
		aloc := ia(N); for i,a := range A { aloc[a] = i }
		l,r := aloc[0],aloc[0]; avail := 0; mex := 1
		sb := make([]bool,N); sb[0] = true
		ans := int64(1)
		for l > 0 || r < N-1 {
			idx := aloc[mex]
			if idx > r { for i:=r+1; i<=idx; i++ { sb[A[i]] = true; avail++ }; r = idx }
			if idx < l { for i:=l-1; i>=idx; i-- { sb[A[i]] = true; avail++ }; l = idx }
			newmex := mex; for newmex < N && sb[newmex] { newmex++ }
			avail-- // for the current mex
			if newmex > mex+1 {
				numneeded := newmex-mex-1
				for i:=0;i<numneeded;i++ { ans *= int64(avail); ans %= MOD; avail-- }
			}
			mex = newmex
		}
		fmt.Fprintln(wrtr,ans)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1699C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	const mod int64 = 1e9 + 7

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		p := make([]int, n)
		for i := range p {
			Fscan(in, &v)
			p[v] = i
		}
		ans := int64(1)
		l, r := p[0], p[0]
		for i, p := range p[1:] {
			if p < l {
				l = p
			} else if p > r {
				r = p
			} else {
				ans = ans * int64(r-l-i) % mod
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1699C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	const mod int64 = 1e9 + 7

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		p := make([]int, n)
		for i := range p {
			Fscan(in, &v)
			p[v] = i
		}
		ans := int64(1)
		l, r := p[0], p[0]
		for i, p := range p[1:] {
			if p < l {
				l = p
			} else if p > r {
				r = p
			} else {
				ans = ans * int64(r-l-i) % mod
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

const (
	mod int64 = 1e9 + 7
)

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

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

func Solve(testCaseIdx int, reader io.Reader) {
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n int
	fmt.Fscan(reader, &n)

	a := make([] int, n)
	p := make([] int, n)
	for k := 0; k < n; k++ {
		var x int
		fmt.Fscan(reader, &x)
		a[k] = x
		p[x] = k
	}

	var ans int64
	ans = 1

	if n == 1 {
		fmt.Fprintln(writer, ans)
		return
	}

	l := Min(p[0], p[1])
	r := Max(p[0], p[1])
	for k := 2; k < n; k++ {
		if l < p[k] && p[k] < r {
			ans = ans * int64(r - l + 1 - k) % mod
		}
		l = Min(l, p[k])
		r = Max(r, p[k])
	}

	fmt.Fprintln(writer, ans)
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var testCaseCount int
	fmt.Fscan(reader, &testCaseCount)
	for t := 0; t < testCaseCount; t++ {
		Solve(t, reader)
	}
}

package main

import . "fmt"
import "bufio"
import "os"

func main(){
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	var cas int
	Mod := int64(1e9 + 7)
	Fscan(in,&cas)
	var solve func()
	solve = func(){
		var n int
		Fscan(in,&n)
		defer out.Flush()
		a := make([]int,n)
		p := make([]int,n)

		for i:=0;i<n;i++{
			Fscan(in,&a[i])
			p[a[i]] = i
		}
		l,r:=p[0],p[0]
		var ans = int64(1)
		for i:=1;i<n;i++{
			if p[i] > r{
				r = p[i]
			}else if p[i] < l {
				l = p[i]
			}else {
				ans *= int64(r - l + 1 - i)
				ans %= Mod
			}
		}
		Fprintln(out,ans)
	}
	for i:=0;i<cas;i++{
		solve()
	}
}

package main

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

const MOD = 1e9 + 7

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		aa := make([]int, n)
		for i := 0; i < n; i++ {
			var v int
			fmt.Fscan(in, &v)

			aa[v] = i
		}

		l, r := aa[0], aa[0]
		ans := int64(1)
		for i := 1; i < n; i++ {
			if l > aa[i] {
				l = aa[i]
			} else if r < aa[i] {
				r = aa[i]
			} else {
				ans *= int64((r - l + 1 - i))
				ans %= MOD
			}
		}
		fmt.Println(ans)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for t > 0 {
		t--
		var n int
		fmt.Fscan(in, &n)
		a := make([]int64, n+5)
		p := make([]int64, n+5)
		for i := 1; i <= n; i++ {
			fmt.Fscan(in, &a[i])
			p[a[i]] = int64(i)
		}
		mod := int64(1e9 + 7)
		var ans int64 = 1
		var l int64
		var r int64
		if p[0] > p[1] {
			l = p[1]
			r = p[0]
		} else {
			l = p[0]
			r = p[1]
		}
		for i := 2; i < n; i++ {
			if p[i] < l {
				l = p[i]
				continue
			}
			if p[i] > r {
				r = p[i]
				continue
			}
			ans = (ans % mod * ((r-l+1)%mod - int64(i)%mod) % mod) % mod
		}
		fmt.Fprintln(out, ans)
	}
}

package main

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

var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

func slove() {
	var n int
	fmt.Fscan(rr, &n)
	nums := make([]int64, n)
	index := make([]int64, n)
	for i:=int64(0);i<int64(len(nums));i++ {
		fmt.Fscan(rr, &nums[i])
		index[nums[i]] = i
	}
	l, r := index[0], index[0]
	var space int64
	var ans int64
	ans = 1
	for i:=1;i<n;i++ {
		if index[i] < l {
			space += l - index[i] - 1
			l = index[i]
		} else if index[i] > r {
			space += index[i] - r - 1
			r = index[i]
		} else {
			ans *= space
			ans %= 1e9+7
			space--
		}
	}
	fmt.Fprintln(ww, ans)
}

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

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

const mod = 998244353
const mx = int64(1e9 + 7)

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int64
	fmt.Fscan(in, &n)
	arr := make([]int64, n)
	for i := int64(0); i < n; i++ {
		fmt.Fscan(in, &arr[i])

	}
	p := make([]int64, n+1)
	for i := int64(0); i < n; i++ {
		p[arr[i]] = i
	}
	l := p[0]
	r := p[0]
	ans := int64(1)
	for i := int64(1); i < n; i++ {
		if p[i] < l {
			l = p[i]
		} else if p[i] > r {
			r = p[i]
		} else {
			ans *= r - l + 1 - i
			ans %= mod
		}
	}
	fmt.Fprintln(out, ans)
}

func abs(a int64) int64 {
	if a > 0 {
		return a
	}
	return -a
}
func sum(a, b int64) int64 {
	return (b + a) * (b - a + 1) / 2
}

func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

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

package main

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

const mod = 998244353
const mx = int64(1e9 + 7)

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int64
	fmt.Fscan(in, &n)
	arr := make([]int64, n)
	for i := int64(0); i < n; i++ {
		fmt.Fscan(in, &arr[i])

	}
	p := make([]int64, n+1)
	for i := int64(0); i < n; i++ {
		p[arr[i]] = i
	}
	l := p[0]
	r := p[0]
	ans := int64(1)
	for i := int64(1); i < n; i++ {
		if p[i] < l {
			l = p[i]
		} else if p[i] > r {
			r = p[i]
		} else {
			ans *= r - l + 1 - i
		}
	}
	fmt.Fprintln(out, ans)
}

func abs(a int64) int64 {
	if a > 0 {
		return a
	}
	return -a
}
func sum(a, b int64) int64 {
	return (b + a) * (b - a + 1) / 2
}

func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

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

package main

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

const (
	mod int = 1e9 + 7
)

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

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

func Solve(testCaseIdx int, reader io.Reader) {
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n int
	fmt.Fscan(reader, &n)

	a := make([] int, n)
	p := make([] int, n)
	for k := 0; k < n; k++ {
		var x int
		fmt.Fscan(reader, &x)
		a[k] = x
		p[x] = k
	}

	ans := 1

	if n == 1 {
		fmt.Fprintln(writer, ans)
		return
	}

	l := Min(p[0], p[1])
	r := Max(p[0], p[1])
	for k := 2; k < n; k++ {
		if l < p[k] && p[k] < r {
			ans = ans * (r - l + 1 - k) % mod
		}
		l = Min(l, p[k])
		r = Max(r, p[k])
	}

	fmt.Fprintln(writer, ans)
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var testCaseCount int
	fmt.Fscan(reader, &testCaseCount)
	for t := 0; t < testCaseCount; t++ {
		Solve(t, reader)
	}
}

package main

import . "fmt"
import "bufio"
import "os"

func main(){
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	var cas int
	Mod := int64(1e9 + 7)
	Fscan(in,&cas)
	var solve func()
	solve = func(){
		var n int
		Fscan(in,&n)
		defer out.Flush()
		a := make([]int,n)
		p := make([]int,n)

		for i:=0;i<n;i++{
			Fscan(in,&a[i])
			p[a[i]] = i
		}
		l,r:=p[0],p[0]
		var ans = int64(1)
		for i:=1;i<n;i++{
			if p[i] > r{
				r = p[i]
			}else if p[i] < l {
				l = p[i]
			}else {
				ans *= int64(r - l + 1 - i) % Mod
			}
		}
		Fprintln(out,ans)
	}
	for i:=0;i<cas;i++{
		solve()
	}
}

package main

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

const MOD = 1e9 + 7

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		aa := make([]int, n)
		for i := 0; i < n; i++ {
			var v int
			fmt.Fscan(in, &v)

			aa[v] = i
		}

		l, r := aa[0], aa[0]
		ans := int64(1)
		for i := 1; i < n; i++ {
			if l > aa[i] {
				l = aa[i]
			} else if r < aa[i] {
				r = aa[i]
			} else {
				ans *= int64((r - l + 1 - i) % MOD)
			}
		}
		fmt.Println(ans)
	}
}


At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.

Print a single integer — the number of places in queue she can move forward.

NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is   change places for pupils with numbers $$$1$$$ and $$$3$$$.  change places for pupils with numbers $$$3$$$ and $$$2$$$.  change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.

package main

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

var edges = make(map[int][]int)

func addE(v, u int) {
	if len(edges[v]) <= 0 {
		edges[v] = make([]int, 0)
	}
	edges[v] = append(edges[v], u)
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n, m int
	fmt.Fscanf(buf, "%d %d\n", &n, &m)
	mat := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i])
	}
	fmt.Fscanf(buf, "\n")
	var u, v int
	var cads = make(map[int]int)
	for i := 0; i < m; i++ {
		fmt.Fscanf(buf, "%d %d\n", &u, &v)
		if mat[n-1] == v {
			cads[u] = 1
		}
		addE(v, u)
	}
	cnt := make([]int, n+1)
	ans := 0
	exp := 0
	//fmt.Printf("%v\n",cads)
	for i := n - 1; i >= 0; i-- {
		if 0 < cads[mat[i]]{
			if cnt[mat[i]]== exp{
				ans++
				continue
			}
		}
		for _,v := range edges[mat[i]] {
		//	fmt.Printf("%d->%d\n",mat[i],v)
			cnt[v]++
		}
		exp++
	}
	fmt.Printf("%d\n",ans)
}

/**
01010101
0101010
 */

package main

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

var edges = [500009]EdgeD{}

type EdgeD struct {
	next *EdgeD
	id   int
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	var n, m int
	fmt.Fscanf(buf, "%d %d\n", &n, &m)
	mat := make([]int, n)
	header := make([]*EdgeD, n+1)

	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i])
	}
	fmt.Fscanf(buf, "\n")
	var u, v int
	var cads = make([]bool, n+1)
	ef := 0
	for i := 0; i < m; i++ {
		fmt.Fscanf(buf, "%d %d\n", &u, &v)
		edges[ef].id = u
		edges[ef].next = header[v]

		header[v] = &edges[ef]
		ef++
		if mat[n-1] == v {
			cads[u] = true
		}
		//	addE(v, u)
	}
	cnt := make([]int, n+1)
	ans := 0
	exp := 0
	//fmt.Printf("%v\n",cads)
	for i := n - 1; i >= 0; i-- {
		if cads[mat[i]] {
			if cnt[mat[i]] == exp {
				ans++
				continue
			}
		}
		nex := header[mat[i]]
		for nex != nil {
			//fmt.Printf("%d->%d\n", mat[i], v)
			cnt[nex.id]++
			nex = nex.next
		}
		exp++
	}
	fmt.Printf("%d\n", ans)
}

/**
01010101
0101010
 */

package main

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

var edges = make(map[int][]int)

func addE(v, u int) {
	if len(edges[v]) <= 0 {
		edges[v] = make([]int, 0)
	}
	edges[v] = append(edges[v], u)
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n, m int
	fmt.Fscanf(buf, "%d %d\n", &n, &m)
	mat := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i])
	}
	fmt.Fscanf(buf, "\n")
	var u, v int
	var cads = make([]bool, n+1)

	for i := 0; i < m; i++ {
		fmt.Fscanf(buf, "%d %d\n", &u, &v)
		if mat[n-1] == v {
			cads[u] = true
		}
		addE(v, u)
	}
	cnt := make([]int, n+1)
	ans := 0
	exp := 0
	//fmt.Printf("%v\n",cads)
	for i := n - 1; i >= 0; i-- {
		if cads[mat[i]] {
			if cnt[mat[i]] == exp {
				ans++
				continue
			}
		}
		for _, v := range edges[mat[i]] {
			//	fmt.Printf("%d->%d\n",mat[i],v)
			cnt[v]++
		}
		exp++
	}
	fmt.Printf("%d\n", ans)
}

/**
01010101
0101010
 */

package main

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

type input struct {
  scanner *bufio.Scanner
}

func NewInput() input {
  in := input{scanner: bufio.NewScanner(os.Stdin)}
  in.scanner.Split(bufio.ScanWords)
  return in
}

func (in* input) Token() string {
  in.scanner.Scan()
  return in.scanner.Text()
}

func (in* input) IntToken() int {
  result, _ := strconv.Atoi(in.Token())
  return result
}

func main() {
  in := NewInput()
  N := in.IntToken()
  M := in.IntToken()

  P := make([]int, N)
  for i := 0; i < N; i++ {
    P[i] = in.IntToken() - 1
  }

  G := make([][]int, N)
  for i := 0; i < M; i++ {
    u := in.IntToken() - 1
    v := in.IntToken() - 1
    G[v] = append(G[v], u)
  }

  result := 0
  max_freq := 0
  freq := make([]int, N)
  for i := N - 1; i >= 0; i-- {
    if i != N - 1 && freq[P[i]] == max_freq {
      result++
    } else {
      max_freq++
      for _, u := range G[P[i]] {
        freq[u]++
      }
    }
  }

  fmt.Println(result)
}


The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law:  For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;  For each station i there exists exactly one station j such that pj = i. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!

The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.

Print one number — the maximum possible value of convenience.

NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).In the second example the mayor can change p2 to 4 and p3 to 5.

package main

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

var local = false
var scanner *bufio.Scanner

func main() {
	setup()
	n := readInt()
	p, flags := make([]int, n), make([]bool, n)
	for i := 0; i < n; i++ {
		p[i] = readInt() - 1
		flags[i] = false
	}

	var conv uint64 = 0
	max1, max2 := 0, 0
	for i := 0; i < n; i++ {
		if flags[i] == true {
			continue
		}

		flags[i] = true
		currmax := 1
		for j := p[i]; flags[j] == false; j = p[j] {
			flags[j] = true
			currmax++
		}
		conv += uint64(currmax) * uint64(currmax)

		tmp := []int{max1, max2, currmax}
		sort.Ints(tmp)
		max1 = tmp[1]
		max2 = tmp[2]
	}

	m1, m2 := uint64(max1), uint64(max2)
	conv -= (m1 * m1) + (m2 * m2)
	conv += (m1 + m2) * (m1 + m2)
	fmt.Println(conv)
}

func setup() {
	source := os.Stdin
	if local == true {
		file, _ := os.Open("input.txt")
		source = file
	}
	scanner = bufio.NewScanner(source)
	scanner.Split(bufio.ScanWords)
}

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

package main

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

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

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

	p := make([]int, n + 1)
	for i := 0; i < n; i++ {
		fmt.Fscanf(input, "%d", &p[i])
		p[i]--
	}

	cycles := make([]int, 0, n)
	used := make([]bool, n)

	for i := 0; i < n; i++ {
		if used[i] == false {
			cycle_size := 0
			for j := i; used[j] == false; j = p[j] {
				used[j] = true
				cycle_size++
			}
			cycles = append(cycles, cycle_size)
		}
	}

	sort.Sort(sort.Reverse(sort.IntSlice(cycles)))

	var ans int64 = 0

	if len(cycles) > 1 {
		cycles_union := cycles[0] + cycles[1]
		ans += int64(cycles_union) * int64(cycles_union)

		for _, v := range cycles[2:] {
			ans += int64(v) * int64(v)
		}
	} else {
		ans += int64(cycles[0]) * int64(cycles[0])
	}

	fmt.Println(ans)
}

package main

import(
	"fmt"
	"bufio"
	"os"
	"sort"
)
func main() {
	cin := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(cin,"%d",&n)

	p := make([]int,n)
	circleLen := make([]int,0)
	visited := make([]bool,n)
	for i:= 0;i < n;i++{
		fmt.Fscan(cin,&p[i])
	}

	for i:=0;i < n;i++{
		if visited[i] == false{
			now := i
			cnt := 0
			for visited[now] == false{
				visited[now] = true
				now = p[now] - 1
				cnt++
			}

			circleLen = append(circleLen,cnt)
		}
	}

	if len(circleLen) == 1{
		fmt.Println(int64(circleLen[0]) * int64(circleLen[0]))
	} else{
		sort.Sort(sort.Reverse(sort.IntSlice(circleLen)))
		var ans int64
		ans += int64(circleLen[0] + circleLen[1]) * int64(circleLen[0] + circleLen[1])
		for i := 2;i < len(circleLen);i++{
			ans += int64(circleLen[i]) * int64(circleLen[i])
		}
		fmt.Println(ans)
	}
}

// Codeforces 884 C. Bertown Subway train
// tr
package main

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

var in *bufio.Reader

func readFive() (int, int, int, int, int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i := 0; i < len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0], a[1], a[2], a[3], a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for j := 0; j < n; j++ {
		aa, err := strconv.Atoi(ss[j])
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[j] = aa
	}
	return a
}

var n int
var p []int
var maxConv int64
var par,rank,cnt []int // arrays for disjoined sets

// readData read data for out problem.
func readData() {
	in = bufio.NewReader(os.Stdin)
	// reading string a
	n,_,_,_,_ = readFive()
	p = readLineNumbs(n)
}

// initialize point as self set
func makeSet(i int) {
	par[i] = i
	rank[i] = 0
	cnt[i] = 1
}

// find set where parent == i
func find(i int) int {
	for i != par[i] {
		io := i
		i = par[i]
		par[io] = par[i]
	}
	return i
}

func join(a int, b int) {
	a = find(a)
	b = find(b)
	if a==b {
		return
	}
	if rank[a] < rank[b] {
		par[a] = b
		cnt[b] = cnt[a] + cnt[b]
	} else {
		par[b] = a
		cnt[a] = cnt[a] + cnt[b]
		if rank[b] == rank[a] {
			rank[b] += 1
		}
	}
}

func getSetsCnts() []int {
	maxConv = 0;
	cnts := make([]int,0)
	for i,pa := range par {
		if i == pa {
			cnts = append(cnts, cnt[i])
		}
	}
	sort.Ints(cnts)
	return cnts
}

func countMaxConv(cnts []int) {
	maxConv = 0
	nn := len(cnts)
	if nn>1 {
		cnts[nn-2] = cnts[nn-1] + cnts[nn-2]
		nn -= 1
	}
	for i:=0; i<nn; i++ {
		c := int64(cnts[i])
		maxConv += c*c
	}
}

// solve func solves our problem.
func solve() {
	par = make([]int, n)
	rank = make([]int, n)
	cnt = make([]int, n)
	for i:=0; i<n; i++ {
		makeSet(i)
	}
	for i,pp := range p {
		join(i, pp-1)
	}
	cnts := getSetsCnts()
	countMaxConv(cnts)
}

// printRes print problem solution in expected format.
func printRes() {
	fmt.Println(maxConv)
}

func main() {
	readData()
	solve()
	printRes()
}

package main

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

func Init() {
}

func Solve(io *FastIO) {
    N := io.NextInt()
    P := io.NextIntArrayOffset(N, 1)

    seen := make([]bool, N + 1)
    best := make([]int, 3)
    total := int64(0)
    for i := 1; i <= N; i++ {
        if !seen[i] {
            size := 1
            seen[i] = true
            for c := P[i]; c != i; c = P[c] {
                seen[c] = true
                size++
            }
            best[0] = size
            sort.Ints(best)
            total += int64(size) * int64(size)
        }
    }

    top := int64(best[2])
    med := int64(best[1])
    sum := top + med
    total += (sum * sum) - (top * top) - (med * med)

    io.Println(total)
}

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

func IsLineBreakChar(c byte) bool {
	switch c {
		case 0, '\n', '\r':
			return true
		default:
			return false
	}
}

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

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

var local = false
var scanner *bufio.Scanner

func main() {
	setup()
	n := readInt()
	p, flags := make([]int, n), make([]bool, n)
	for i := 0; i < n; i++ {
		p[i] = readInt() - 1
		flags[i] = false
	}

	max1, max2, conv := 0, 0, 0
	for i := 0; i < n; i++ {
		if flags[i] == true {
			continue
		}

		flags[i] = true
		currmax := 1
		for j := p[i]; flags[j] == false; j = p[j] {
			flags[j] = true
			currmax++
		}
		conv += currmax * currmax

		tmp := []int{max1, max2, currmax}
		sort.Ints(tmp)
		max1 = tmp[1]
		max2 = tmp[2]
	}

	conv -= (max1 * max1) + (max2 * max2)
	conv += (max1 + max2) * (max1 + max2)
	fmt.Println(conv)
}

func setup() {
	source := os.Stdin
	if local == true {
		file, _ := os.Open("input.txt")
		source = file
	}
	scanner = bufio.NewScanner(source)
	scanner.Split(bufio.ScanWords)
}

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

package main

import(
	"fmt"
	"bufio"
	"os"
	"sort"
)
func main() {
	cin := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(cin,"%d",&n)

	p := make([]int,n)
	circleLen := make([]int,0)
	visited := make([]bool,n)
	for i:= 0;i < n;i++{
		fmt.Fscan(cin,&p[i])
	}

	for i:=0;i < n;i++{
		if visited[i] == false{
			now := i
			cnt := 0
			for visited[now] == false{
				visited[now] = true
				now = p[now] - 1
				cnt++
			}

			circleLen = append(circleLen,cnt)
		}
	}

	if len(circleLen) == 1{
		fmt.Println(circleLen[0] * circleLen[0])
	} else{
		sort.Sort(sort.Reverse(sort.IntSlice(circleLen)))
		ans := 0
		ans += (circleLen[0] + circleLen[1]) * (circleLen[0] + circleLen[1])
		for i := 2;i < len(circleLen);i++{
			ans += circleLen[i] * circleLen[i]
		}
		fmt.Println(ans)
	}
}


Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell $$$(x,y)$$$ of an infinite grid. According to Alice's theory, cat needs to move:   exactly $$$a$$$ steps left: from $$$(u,v)$$$ to $$$(u-1,v)$$$;  exactly $$$b$$$ steps right: from $$$(u,v)$$$ to $$$(u+1,v)$$$;  exactly $$$c$$$ steps down: from $$$(u,v)$$$ to $$$(u,v-1)$$$;  exactly $$$d$$$ steps up: from $$$(u,v)$$$ to $$$(u,v+1)$$$. Note that the moves can be performed in an arbitrary order. For example, if the cat has to move $$$1$$$ step left, $$$3$$$ steps right and $$$2$$$ steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area $$$[x_1,x_2]\times [y_1,y_2]$$$, i.e. for every cat's position $$$(u,v)$$$ of a walk $$$x_1 \le u \le x_2$$$ and $$$y_1 \le v \le y_2$$$ holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly $$$a+b+c+d$$$ unit moves ($$$a$$$ to the left, $$$b$$$ to the right, $$$c$$$ to the down, $$$d$$$ to the up). Alice can do the moves in any order. Her current position $$$(u, v)$$$ should always satisfy the constraints: $$$x_1 \le u \le x_2$$$, $$$y_1 \le v \le y_2$$$. The staring point is $$$(x, y)$$$.You are required to answer $$$t$$$ test cases independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases.  The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,b,c,d \le 10^8$$$, $$$a+b+c+d \ge 1$$$). The second line of the test case contains six integers $$$x$$$, $$$y$$$, $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$-10^8 \le x_1\le x \le x_2 \le 10^8$$$, $$$-10^8 \le y_1 \le y \le y_2 \le 10^8$$$).

For each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output "NO" in a separate line.  You can print each letter in any case (upper or lower).

NoteIn the first test case, one valid exercising walk is $$$$$$(0,0)\rightarrow (-1,0) \rightarrow (-2,0)\rightarrow (-2,1) \rightarrow (-2,2)\rightarrow (-1,2)\rightarrow(0,2)\rightarrow (0,1)\rightarrow (0,0) \rightarrow (-1,0)$$$$$$

package main

import (
	"fmt"
)

func main() {
	var tc int
	fmt.Scanf("%d", &tc)
	for i := 0; i < tc; i++ {
		var a, b, c, d int
		fmt.Scan(&a, &b, &c, &d)
		var x, y, x1, y1, x2, y2 int
		fmt.Scan(&x, &y, &x1, &y1, &x2, &y2)
		diffx := -1*a + b
		diffy := -1*c + d
		if (x + diffx < x1 || x + diffx > x2 || y + diffy < y1 || y + diffy > y2){
			fmt.Println("No")
		}else if (x == x1 && x1 == x2 && (a > 0 || b > 0)){
			fmt.Println("No")
		}else if (y == y1 && y1 == y2 && (c > 0 || d > 0)){
			fmt.Println("No")
		}else{
			fmt.Println("Yes")
		}
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	var t int
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		var a, b, c, d, x, y, x1, y1, x2, y2 int
		fmt.Fscan(in, &a, &b, &c, &d, &x, &y, &x1, &y1, &x2, &y2)
		if (a > 0 || b > 0) && x1 == x2 {
			fmt.Fprintln(out, "NO")
			continue
		}
		if (c > 0 || d > 0) && y1 == y2 {
			fmt.Fprintln(out, "NO")
			continue
		}
		x += b - a
		y += d - c
		if x < x1 || x > x2 || y < y1 || y > y2 {
			fmt.Fprintln(out, "NO")
			continue
		}
		fmt.Fprintln(out, "YES")
	}
	out.Flush()
}

package main

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

var reader = bufio.NewReader(os.Stdin)
var 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 main() {
	var count int16
	scanf("%d\n", &count)

	for i := int16(0); i < count; i++ {
		if calculate() {
			printf("Yes\n")
			continue
		}
		printf("No\n")
	}

	writer.Flush()
}

func calculate() bool {
	var a, b, c, d int32
	scanf("%d %d %d %d\n", &a, &b, &c, &d)

	var x, y, x1, y1, x2, y2 int32
	scanf("%d %d %d %d %d %d\n", &x, &y, &x1, &y1, &x2, &y2)

	if a > b {
		if x1 > x-(a-b) {
			return false
		}
	} else if b > a {
		if x2 < x+(b-a) {
			return false
		}
	} else if a != 0 && b != 0 {
		if x-x1 == 0 && x2-x == 0 {
			return false
		}
	}

	if c > d {
		if y1 > y-(c-d) {
			return false
		}
	} else if d > c {
		if y2 < y+(d-c) {
			return false
		}
	} else if c != 0 && d != 0 {
		if y-y1 == 0 && y2-y == 0 {
			return false
		}
	}

	return true
}

package main

import "fmt"

func problem(a, b, c, d, x, y, x1, y1, x2, y2 int) string {
	sp := b - a
	cz := d - c
	if sp >= 0 && x2-x < sp {
		return "No"
	} else if x-x1 < (-sp) {
		return "No"
	}
	if cz >= 0 && y2-y < cz {
		return "No"
	} else if y-y1 < (-cz) {
		return "No"
	}
	if ((a > 0 || b > 0) && x2-x1 == 0) || ((c > 0 || d > 0) && y2-y1 == 0) {
		return "No"
	}
	return "Yes"
}

func input() (a, b, c, d, x, y, x1, y1, x2, y2 int) {
	fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &d)
	fmt.Scanf("%d %d %d %d %d %d\n", &x, &y, &x1, &y1, &x2, &y2)
	return
}

func problemWrapper() {
	t := 0
	fmt.Scanln(&t)
	for i := 0; i < t; i++ {
		a, b, c, d, x, y, x1, y1, x2, y2 := input()
		res := problem(a, b, c, d, x, y, x1, y1, x2, y2)
		fmt.Println(res)
	}
}

func main() {
	problemWrapper()
}

package main

import (
	"fmt"
)

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

	for t := 0; t < tests; t++ {
		var a, b, c, d int
		fmt.Scan(&a, &b, &c, &d)

		var x, y, x1, y1, x2, y2 int
		fmt.Scan(&x, &y, &x1, &y1, &x2, &y2)

		ok := y-y1 >= c-d && y2-y >= d-c &&
			x-x1 >= a-b && x2-x >= b-a

		if a+b > 0 {
			ok = ok && (x2-x1 > 0)
		}

		if c+d > 0 {
			ok = ok && y2-y1 > 0
		}

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

/*
1
3 3 1 1
0 0 0 0 1 1
*/

package main

import "fmt"

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	for i := 0; i < cases; i++ {
		var a, b, c, d int64
		fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &d)
		left := a - b
		down := c - d
		var x, y, x1, y1, x2, y2 int64
		fmt.Scanf("%d %d %d %d %d %d\n", &x, &y, &x1, &y1, &x2, &y2)
		if x > x2 || x < x1 || y > y2 || y < y1 {
			fmt.Println("NO")
			continue
		}
		if left > 0 {
			if x-left < x1 {
				fmt.Println("NO")
				continue
			}
		} else if left < 0 {
			if x-left > x2 {
				fmt.Println("NO")
				continue
			}
		} else {
			if x==x1 && x==x2 && a >0 {
				fmt.Println("NO")
				continue
			}
		}

		if down > 0 {
			if y-down < y1 {
				fmt.Println("NO")
				continue
			}
		} else if down < 0 {
			if y-down >y2 {
				fmt.Println("NO")
				continue
			}
		} else {
			if y==y1 && y== y2 && c>0{
				fmt.Println("NO")
				continue
			}
		}
		fmt.Println("YES")
	}
}

package main

import (
	"fmt"
)

var (
	testCases                                 int64
	leftSteps, rightSteps, upSteps, downSteps int64
	startX, startY, x1, y1, x2, y2            int64
)

func canStayInside() bool {
	endX := startX - leftSteps + rightSteps
	endY := startY - downSteps + upSteps

	if x1 == x2 && x1 == startX && (leftSteps != 0 || rightSteps != 0) {
		return false
	}

	if y1 == y2 && y1 == startY && (upSteps != 0 || downSteps != 0) {
		return false
	}
	if endX >= x1 && endX <= x2 && endY >= y1 && endY <= y2 {
		return true
	}
	return false

}

func main() {

	fmt.Scanf("%d\n", &testCases)

	for ti := int64(0); ti < testCases; ti++ {
		fmt.Scanf("%d %d %d %d\n", &leftSteps, &rightSteps, &downSteps, &upSteps)
		fmt.Scanf("%d %d %d %d %d %d\n", &startX, &startY, &x1, &y1, &x2, &y2)

		switch canStayInside() {
		case true:
			fmt.Println("YES")
		case false:
			fmt.Println("NO")
		}
	}

}

package main

import (
	"fmt"
)

func main() {
	//fmt.Println(time.Now().UnixNano()/1e9, "begin")
	CF1332_A()
}

func CF1332_A() {
	type I struct {
		U int64
		D int64
		L int64
		R int64

		Sx   int64
		Sy   int64
		MinX int64
		MaxX int64
		MinY int64
		MaxY int64
	}
	var input = func() []I {
		var retVal []I

		var caseNum int
		//_, _ = fmt.Scanf("%d", &caseNum)
		_, _ = fmt.Scan(&caseNum)
		for i := 0; i < caseNum; i++ {
			i := I{}
			//_, _ = fmt.Scanf("%d%d%d%d", &i.U, &i.D, &i.L, &i.R)
			_, _ = fmt.Scan(&i.U, &i.D, &i.L, &i.R)
			//_, _ = fmt.Scanf("%d%d%d%d%d%d", &i.Sx, &i.Sy, &i.MinX, &i.MinY, &i.MaxX, &i.MaxY)
			_, _ = fmt.Scan(&i.Sx, &i.Sy, &i.MinX, &i.MinY, &i.MaxX, &i.MaxY)
			retVal = append(retVal, i)
		}

		return retVal
	}()
	//var judge = func(x, y int64, i I) bool { return i.MinX <= x && x <= i.MaxX && i.MinY <= y && y <= i.MaxY }
	var judge2 = func(x, min, max int64, padding bool) bool {
		if padding {
			return (min <= x-1 && x-1 <= max) || (min <= x+1 && x+1 <= max)
		}
		return min <= x && x <= max
	}
	for _, i := range input {
		x := i.D - i.U + i.Sx
		y := i.R - i.L + i.Sy
		paddingX := x == i.Sx && i.D > 0
		paddingY := y == i.Sy && i.R > 0
		//fmt.Println(x, y, paddingX, paddingY)
		if judge2(x, i.MinX, i.MaxX, paddingX) && judge2(y, i.MinY, i.MaxY, paddingY) {
			fmt.Println("Yes")
			continue
		}
		fmt.Println("No")
	}
}

var _ = `
6
3 2 2 2
0 0 -2 -2 2 2
3 1 4 1
0 0 -1 -1 1 1
1 1 1 1
1 1 1 1 1 1
0 0 0 1
0 0 0 0 0 1
5 1 1 1
0 0 -100 -100 0 100
1 1 5 1
0 0 -100 -100 100 0
`

package main

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

type T1332A struct {
	t   int
	Buf map[string] int32
	Result []string
}

func (p *T1332A) Init(r io.Reader) {
	var err error
	var src []string
	scanner := bufio.NewScanner(r)
	scanner.Split(bufio.ScanLines)
	scanner.Scan()
	p.t, err = strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	p.Buf = make(map[string] int32)
	p.Result = make([]string, p.t)
	wg := new(sync.WaitGroup)
	for cnt:=0; cnt < p.t; cnt++ {
		src = make([]string, 2)
		scanner.Scan()
		src[0] = scanner.Text()
		scanner.Scan()
		src[1] = scanner.Text()
		wg.Add(1)
		go p.process(wg, cnt, src)
	}
	wg.Wait()
}

func (p *T1332A) process(wg *sync.WaitGroup, id int, src []string) {
	Buf := make(map[string] int32)
	nm := make([][]string, 2)
	nm[0] = []string{"a","b","c","d"}
	nm[1] = []string{"x","y","x1","y1","x2","y2"}
	for rn:= range []int{0,1} {
		for i,s := range strings.Fields(src[rn]) {
			val, _ := strconv.Atoi(s)
			Buf[nm[rn][i]] = int32(val)
		}
	}
	resC1 := Buf["x2"] == Buf["x1"] && Buf["a"] + Buf["b"] > 0
	resC2 := Buf["y2"] == Buf["y1"] && Buf["c"] + Buf["d"] > 0
	resX := Buf["a"] - Buf["b"] >=0 && Buf["x"] - Buf["x1"] >= Buf["a"] - Buf["b"] ||
		Buf["b"] - Buf["a"] > 0 && Buf["x2"] - Buf["x"] >= Buf["b"] - Buf["a"]
	resY := Buf["c"] - Buf["d"] >=0 && Buf["y"] - Buf["y1"] >= Buf["c"] - Buf["d"] ||
		Buf["d"] - Buf["c"] > 0 && Buf["y2"] - Buf["y"] >= Buf["d"] - Buf["c"]
	p.Result[id] = map[bool]string{false:"No",true:"Yes"}[!resC1 && !resC2 && resX && resY]
	wg.Done()
}

func (p *T1332A) GetResult() string {
	return strings.Join(p.Result, "\n")
}

func main() {
	t1332a := new(T1332A)
	t1332a.Init(os.Stdin)
	fmt.Println(t1332a.GetResult())
}

package main

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

type T1332A struct {
	t   int
	Buf map[string] int32
	Result []string
}

func (p *T1332A) Init(r io.Reader) {
	var err error
	scanner := bufio.NewScanner(r)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	p.t, err = strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	p.Buf = make(map[string] int32)
	for cnt:=0; cnt < p.t; cnt++ {
		for _, id := range []string{"a","b","c","d","x","y","x1","y1","x2","y2"} {
			scanner.Scan()
			x, err := strconv.Atoi(scanner.Text())
			if err != nil {
				panic(err)
			}
			p.Buf[string(id)] = int32(x)
		}
		//fmt.Printf("%v\n", p.Buf)
		p.process()
	}
}

func (p *T1332A) process() {
	resC1 := p.Buf["x2"] == p.Buf["x1"] && p.Buf["a"] + p.Buf["b"] > 0
	resC2 := p.Buf["y2"] == p.Buf["y1"] && p.Buf["c"] + p.Buf["d"] > 0
	resX := p.Buf["a"] - p.Buf["b"] >=0 && p.Buf["x"] - p.Buf["x1"] >= p.Buf["a"] - p.Buf["b"] ||
		p.Buf["b"] - p.Buf["a"] > 0 && p.Buf["x2"] - p.Buf["x"] >= p.Buf["b"] - p.Buf["a"]
	resY := p.Buf["c"] - p.Buf["d"] >=0 && p.Buf["y"] - p.Buf["y1"] >= p.Buf["c"] - p.Buf["d"] ||
		p.Buf["d"] - p.Buf["c"] > 0 && p.Buf["y2"] - p.Buf["y"] >= p.Buf["d"] - p.Buf["c"]
	p.Result = append(p.Result,map[bool]string{false:"No",true:"Yes"}[!resC1 && !resC2 && resX && resY])
}

func (p *T1332A) GetResult() string {
	return strings.Join(p.Result, "\n")
}

func main() {
	t1332a := new(T1332A)
	t1332a.Init(os.Stdin)
	fmt.Println(t1332a.GetResult())
}

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 flush()                            { writer.Flush() }
func pp(a interface{})                  { fmt.Println(a) }

func solve(a, b, c, d, x, y, x1, y1, x2, y2 int) bool {
  if a != 0 || b != 0 {
    if x1 == x && x2 == x {
      return false
    }
  }
  if c != 0 || d != 0 {
    if y1 == y && y2 == y {
      return false
    }
  }

  if a >= b {
    a -= b
    b = 0
  } else {
    b -= a
    a = 0
  }
  if c >= d {
    c -= d
    d = 0
  } else {
    d -= c
    c = 0
  }
  if a > 0 {
    if x-x1 < a {
      return false
    }
  }
  if b > 0 {
    if x2-x < b {
      return false
    }
  }
  if c > 0 {
    if y-y1 < c {
      return false
    }
  }
  if d > 0 {
    if y2-y < d {
      return false
    }
  }
  return true
}

func main() {
  defer flush()

  var n int
  scanf("%d\n", &n)
  for i := 1; i <= n; i++ {
    var a, b, c, d int
    var x, y, x1, y1, x2, y2 int
    scanf("%d %d %d %d\n", &a, &b, &c, &d)
    scanf("%d %d %d %d %d %d\n", &x, &y, &x1, &y1, &x2, &y2)
    if solve(a, b, c, d, x, y, x1, y1, x2, y2) {
      printf("Yes\n")
    } else {
      printf("No\n")
    }
  }
}

package main

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

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

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

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

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

var sc = newScanner()

var a, b, c, d, x, y, x1, y1, x2, y2 int

func check(xx, yy int) bool {
	if xx < x1 || xx > x2 || yy < y1 || yy > y2 {
		return false
	}
	return true
}

func sol() string {
	if x1 == x2 && a != 0 && b != 0  {
		return "No"
	}

	if y1 == y2 && c != 0 && d != 0 {
		return "No"
	}

	x -= a
	x += b
	y -= c
	y += d
	if check(x, y) {
		return "Yes"
	}
	return "No"
}

func main() {
	t := scanInt()
	results := make([]string, t)
	for i := 0; i < t; i++ {
		a, b, c, d = scanInt(), scanInt(), scanInt(), scanInt()
		x, y, x1, y1, x2, y2 = scanInt(), scanInt(), scanInt(), scanInt(), scanInt(), scanInt()
		results = append(results, sol())
	}

	for _, result := range results {
		fmt.Println(result)
	}
}

package main

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

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

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

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

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

var sc = newScanner()

var a, b, c, d, x, y, x1, y1, x2, y2 int

func check(xx, yy int) bool {
	if xx < x1 || xx > x2 || yy < y1 || yy > y2 {
		return false
	}
	return true
}

func sol() string {
	if x1 == x2 && a != 0 && b != 0  {
		return "No"
	}

	if y1 == y2 && c != 0 && d != 0 {
		return "No"
	}

	x -= a
	x += b
	y -= c
	y += d
	if check(x, y) {
		return "Yes"
	}
	return "No"
}

func main() {
	t := scanInt()
	for i := 0; i < t; i++ {
		a, b, c, d = scanInt(), scanInt(), scanInt(), scanInt()
		x, y, x1, y1, x2, y2 = scanInt(), scanInt(), scanInt(), scanInt(), scanInt(), scanInt()
		fmt.Println(sol())
	}
}

package main

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

type BufferedWriter interface {
    Printf(format string, a ...interface{})
    Flush()
}

type writerImpl struct {
    *bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
    return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
    fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
    impl.Writer.Flush()
}

type WordScanner interface {
    NextInt() int
    NextInt64() int64
    NextString() string
}

type wordScannerImpl struct {
    *bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
    s := bufio.NewScanner(reader)
    s.Split(bufio.ScanWords)
    return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
    impl.Scan()
    bb := impl.Bytes()
    i := 0
    if bb[0] == '-' {
        for _, b := range bb[1:] {
            i *= 10
            i -= int(b - '0')
        }
        return i
    }
    for _, b := range bb {
        i *= 10
        i += int(b - '0')
    }
    return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
    impl.Scan()
    bb := impl.Bytes()
    i := int64(0)
    if bb[0] == '-' {
        for _, b := range bb[1:] {
            i *= 10
            i -= int64(b - '0')
        }
        return i
    }
    for _, b := range bb {
        i *= 10
        i += int64(b - '0')
    }
    return i
}

func (impl *wordScannerImpl) NextString() string {
    impl.Scan()
    return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
    defer writer.Flush()
    t := reader.NextInt64()
    for ; t > 0; t-- {
        // left right down up
        a := reader.NextInt64()
        b := reader.NextInt64()
        c := reader.NextInt64()
        d := reader.NextInt64()

        // x1 <= x <= x2
        // y1 <= y <= y2
        x := reader.NextInt64()
        y := reader.NextInt64()
        x1 := reader.NextInt64()
        y1 := reader.NextInt64()
        x2 := reader.NextInt64()
        y2 := reader.NextInt64()

        if (x2-x1 == 0) && (a > 0 || b > 0) {
            writer.Printf("No\n")
        } else if (y2-y1 == 0) && (c > 0 || d > 0) {
            writer.Printf("No\n")
        } else if (x-x1 >= a-b) &&
        (x2-x >= b-a) &&
        (y-y1 >= c-d) &&
        (y2-y >= d-c) {
            writer.Printf("Yes\n")
        } else {
            writer.Printf("No\n")
        }
    }
}

package main

import (
	"fmt"
)

func main() {
	var tc int
	fmt.Scanf("%d", &tc)
	for i := 0; i < tc; i++ {
		var a, b, c, d int
		fmt.Scanf("%d %d %d %d", &a, &b, &c, &d)
		var x, y, x1, y1, x2, y2 int
		fmt.Scanf("%d %d %d %d %d %d", &x, &y, &x1, &y1, &x2, &y2)
		diffx := -1*a + b
		diffy := -1*c + d
		if (x + diffx < x1 || x + diffx > x2 || y + diffy < y1 || y + diffy > y2){
			fmt.Println("No")
		}else if (x == x1 && x1 == x2 && (a > 0 || b > 0)){
			fmt.Println("No")
		}else if (y == y1 && y1 == y2 && (c > 0 || d > 0)){
			fmt.Println("No")
		}else{
			fmt.Println("Yes")
		}
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)
var 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 main() {
	var count int16
	scanf("%d\n", count)

	for i := int16(0); i < count; i++ {
		if calculate(reader) {
			printf("Yes\n")
			continue
		}
		printf("No\n")
	}

	if err := writer.Flush(); err != nil {
		panic(err)
	}
}

func calculate(reader *bufio.Reader) bool {
	var a, b, c, d int32
	scanf("%d %d %d %d\n", a, b, c, d)

	var x, y, x1, y1, x2, y2 int32
	scanf("%d %d %d %d %d %d\n", x, y, x1, y1, x2, y2)

	if a > b {
		if x1 > x-(a-b) {
			return false
		}
	} else if b > a {
		if x2 < x+(b-a) {
			return false
		}
	} else if a != 0 && b != 0 {
		if x-x1 == 0 && x2-x == 0 {
			return false
		}
	}

	if c > d {
		if y1 > y-(c-d) {
			return false
		}
	} else if d > c {
		if y2 < y+(d-c) {
			return false
		}
	} else if c != 0 && d != 0 {
		if y-y1 == 0 && y2-y == 0 {
			return false
		}
	}

	return true
}

package main

import "fmt"

func main() {
    t := 0
    fmt.Scanln(&t)
    for i:=0;i<t;i++ {
        var a,b,c,d,x,y,x1,y1,x2,y2 int
        fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &d)
        fmt.Scanf("%d %d %d %d %d %d\n", &x,&y,&x1,&y1,&x2,&y2)
        if (abs(a-c) <= abs(x-x1) || abs(a-c) <= abs(x-x2)) &&
        (abs(b-d) <= abs(y-y1) || abs(b-d) <= abs(y-y2)) {
            fmt.Println("YES")
        }
    }
}

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

package main

import (
	"fmt"
)

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

	fmt.Println(tests)

	for t := 0; t < tests; t++ {
		var a, b, c, d int
		fmt.Scan(&a, &b, &c, &d)

		var x, y, x1, y1, x2, y2 int
		fmt.Scan(&x, &y, &x1, &y1, &x2, &y2)

		ok := y-y1 >= c-d && y2-y >= d-c &&
			x-x1 >= a-b && x2-x >= b-a

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

/*
1
3 3 1 1
0 0 0 0 1 1
*/

package main

import (
	"fmt"
)

var (
	testCases                                 int64
	leftSteps, rightSteps, upSteps, downSteps int64
	startX, startY, x1, y1, x2, y2            int64
)

func canStayInside() bool {
	endX := startX - leftSteps + rightSteps
	endY := startY - downSteps + upSteps

	if x1 == x2 && x1 == startX && (leftSteps != 0 || rightSteps != 0) {
		return false
	}

	if y1 == y2 && y1 == startY && (upSteps != 0 || downSteps != 0) {
		return false
	}
	if endX >= x1 && endX <= x2 && endY >= y1 && endY <= y2 {
		return true
	}
	return false

}

func main() {

	fmt.Scanf("%d", &testCases)

	for ti := int64(0); ti < testCases; ti++ {
		fmt.Scanf("%d %d %d %d", &leftSteps, &rightSteps, &downSteps, &upSteps)
		fmt.Scanf("%d %d %d %d %d %d", &startX, &startY, &x1, &y1, &x2, &y2)

		switch canStayInside() {
		case true:
			fmt.Println("YES")
		case false:
			fmt.Println("NO")
		}
	}

}

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(time.Now().UnixNano()/1e9, "begin")
	CF1332_A()
}

func CF1332_A() {
	type I struct {
		U int64
		D int64
		L int64
		R int64

		Sx   int64
		Sy   int64
		MinX int64
		MaxX int64
		MinY int64
		MaxY int64
	}
	var input = func() []I {
		var retVal []I

		var caseNum int
		_, _ = fmt.Scanf("%d", &caseNum)
		for i := 0; i < caseNum; i++ {
			i := I{}
			_, _ = fmt.Scanf("%d%d%d%d", &i.U, &i.D, &i.L, &i.R)
			_, _ = fmt.Scanf("%d%d%d%d%d%d", &i.Sx, &i.Sy, &i.MinX, &i.MinY, &i.MaxX, &i.MaxY)
			retVal = append(retVal, i)
		}

		return retVal
	}()
	//var judge = func(x, y int64, i I) bool { return i.MinX <= x && x <= i.MaxX && i.MinY <= y && y <= i.MaxY }
	var judge2 = func(x, min, max int64, padding bool) bool {
		if padding {
			return (min <= x-1 && x-1 <= max) || (min <= x+1 && x+1 <= max)
		}
		return min <= x && x <= max
	}
	for _, i := range input {
		x := i.D - i.U + i.Sx
		y := i.R - i.L + i.Sy
		paddingX := x == i.Sx && i.D > 0
		paddingY := y == i.Sy && i.R > 0
		//fmt.Println(x, y, paddingX, paddingY)
		if judge2(x, i.MinX, i.MaxX, paddingX) && judge2(y, i.MinY, i.MaxY, paddingY) {
			fmt.Println("YES")
			continue
		}
		fmt.Println("NO")
	}
}

var _ = `
6
3 2 2 2
0 0 -2 -2 2 2
3 1 4 1
0 0 -1 -1 1 1
1 1 1 1
1 1 1 1 1 1
0 0 0 1
0 0 0 0 0 1
5 1 1 1
0 0 -100 -100 0 100
1 1 5 1
0 0 -100 -100 100 0
`

package main

import (
	"fmt"
)

func main() {
	//fmt.Println(time.Now().UnixNano()/1e9, "begin")
	CF1332_A()
}

func CF1332_A() {
	type I struct {
		U int64
		D int64
		L int64
		R int64

		Sx   int64
		Sy   int64
		MinX int64
		MaxX int64
		MinY int64
		MaxY int64
	}
	var input = func() []I {
		var retVal []I

		var caseNum int
		_, _ = fmt.Scanf("%d", &caseNum)
		for i := 0; i < caseNum; i++ {
			i := I{}
			_, _ = fmt.Scanf("%d%d%d%d", &i.U, &i.D, &i.L, &i.R)
			_, _ = fmt.Scanf("%d%d%d%d%d%d", &i.Sx, &i.Sy, &i.MinX, &i.MinY, &i.MaxX, &i.MaxY)
			retVal = append(retVal, i)
		}

		return retVal
	}()
	//var judge = func(x, y int64, i I) bool { return i.MinX <= x && x <= i.MaxX && i.MinY <= y && y <= i.MaxY }
	var judge2 = func(x, min, max int64, padding bool) bool {
		if padding {
			return (min <= x-1 && x-1 <= max) || (min <= x+1 && x+1 <= max)
		}
		return min <= x && x <= max
	}
	for _, i := range input {
		x := i.D - i.U + i.Sx
		y := i.R - i.L + i.Sy
		paddingX := x == i.Sx && i.D > 0
		paddingY := y == i.Sy && i.R > 0
		//fmt.Println(x, y, paddingX, paddingY)
		if judge2(x, i.MinX, i.MaxX, paddingX) && judge2(y, i.MinY, i.MaxY, paddingY) {
			fmt.Println("YES")
			continue
		}
		fmt.Println("NO")
	}
}

var _ = `
6
3 2 2 2
0 0 -2 -2 2 2
3 1 4 1
0 0 -1 -1 1 1
1 1 1 1
1 1 1 1 1 1
0 0 0 1
0 0 0 0 0 1
5 1 1 1
0 0 -100 -100 0 100
1 1 5 1
0 0 -100 -100 100 0
`

package main

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

type T1332A struct {
	t   int
	Buf map[string] int32
	Result []string
}

func (p *T1332A) Init(r io.Reader) {
	var err error
	scanner := bufio.NewScanner(r)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	p.t, err = strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	p.Buf = make(map[string] int32)
	for cnt:=0; cnt < p.t; cnt++ {
		for _, id := range []string{"a","b","c","d","x","y","x1","y1","x2","y2"} {
			scanner.Scan()
			x, err := strconv.Atoi(scanner.Text())
			if err != nil {
				panic(err)
			}
			p.Buf[string(id)] = int32(x)
		}
		//fmt.Printf("%v\n", p.Buf)
		p.process()
	}
}

func (p *T1332A) process() {
	resX := (p.Buf["x"]- p.Buf["x1"] >= p.Buf["a"] || p.Buf["x2"] - p.Buf["x"]>= p.Buf["c"]) &&
		int32(math.Abs(float64(p.Buf["a"] - p.Buf["c"]))) <= p.Buf["x2"] - p.Buf["x1"]
	resY := (p.Buf["y"]- p.Buf["y1"] >= p.Buf["b"] || p.Buf["y2"] - p.Buf["y"]>= p.Buf["d"]) &&
		int32(math.Abs(float64(p.Buf["b"] - p.Buf["d"]))) <= p.Buf["y2"] - p.Buf["y1"]
	p.Result = append(p.Result,map[bool]string{false:"No",true:"Yes"}[resX && resY])
}

func (p *T1332A) GetResult() string {
	return strings.Join(p.Result, "\n")
}

func main() {
	t1332a := new(T1332A)
	t1332a.Init(os.Stdin)
	fmt.Println(t1332a.GetResult())
}


Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.

package main

import "fmt"
import "bufio"
import "os"

var bufin *bufio.Reader
var bufout *bufio.Writer

func toArray(s string, n int) ([]int, int) {
	a := make([]int, n+1)
	dot := -1
	for i := 0; i < n; i++ {
		c := s[i]
		if c == '.' {
			dot = i + 1
			a[dot] = -1
		} else {
			a[i+1] = int(c - '0')
		}
	}
	return a, dot
}

func findPos(a []int, n int, dot int) int {
	for i := dot + 1; i < n; i++ {
		if a[i] >= 5 {
			return i
		}
	}
	return -1
}

func previousDigit(pos int, dot int) int {
	if pos-1 == dot {
		return dot - 1
	}
	return pos - 1
}

func roundAt(a []int, n int, dot int, pos int) int {
	for (pos > 0) && (a[pos] >= 5) {
		a[pos] = 0
		pos = previousDigit(pos, dot)
		a[pos]++
		if a[pos] < 10 {
			break
		}
	}
	return pos
}

func meaningfulSegment(a []int, n int, dot int) (int, int) {
	for (n-1 > dot) && (a[n-1] == 0) {
		n--
	}
	if n-1 == dot {
		n--
	}
	if a[0] == 0 {
		return 1, n
	}
	return 0, n
}

func solve(a []int, n int, t int, dot int) (int, int) {
	pos := findPos(a, n, dot)
	if pos == -1 {
		return 1, n
	}
	for i := pos + 1; i < n; i++ {
		a[i] = 0
	}
	for (t > 0) && (pos > dot) {
		nextpos := roundAt(a, n, dot, pos)
		if nextpos == pos {
			break
		}
		pos = nextpos
		t--
	}
	return meaningfulSegment(a, n, dot)
}

func print(a []int, f int, n int, dot int) {
	for i := f; i < n; i++ {
		if i == dot {
			fmt.Fprintf(bufout, ".")
		} else {
			fmt.Fprintf(bufout, "%d", a[i])
		}
	}
	fmt.Fprintf(bufout, "\n")
}

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

	var n, t, f int
	var s string

	fmt.Fscanf(bufin, "%d %d\n", &n, &t)
	fmt.Fscanf(bufin, "%s\n", &s)

	a, dot := toArray(s, n)
	f, n = solve(a, n+1, t, dot)
	print(a, f, n, dot)
}

package main

import (
  "os"
  "bufio"
  "fmt"
  "strings"
  "math/big"
)

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

  line, _ := reader.ReadString('\n')
  var n, allowed int
  fmt.Sscanf(line, "%d %d", &n, &allowed)
  original, _ := reader.ReadString('\n')
  original = strings.TrimSpace(original) + "0"
  rounded := []byte(original)
  left := strings.Index(original, ".") + 1
  right := left
  for right != n - 1 {
    if original[right] >= '5' {
      break
    }
    right++
  }
  used := 0
  pos := right
  for pos != left - 1 {
    pos--
    if rounded[pos + 1] < '5' {
      continue
    }
    used++
    for rounded[pos] == '9' {
      pos--
    }
    if pos == left - 1 {
      x := new(big.Int)
      x.SetString(original[:pos], 10)
      x.Add(x, big.NewInt(1))
      writer.WriteString(fmt.Sprintf("%s\n", x))
      return
    }
    rounded[pos] = rounded[pos] + 1
    right = pos
    if used == allowed {
      break
    }
  }
  writer.WriteString(fmt.Sprintf("%s\n", rounded[:right + 1]))
}

// http://codeforces.com/problemset/problem/719/C#
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const inf int = 1e9 + 7

func main () {
	var n, t int

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	output := bufio.NewWriterSize(os.Stdout, 1<<10)
	fmt.Fscanln(input, &n, &t)

	values := make([]rune, n)
	dp := make([]int, n)
	dot := 0;
	for i := 0; i < n; i++ {
		var tmp rune
		fmt.Fscanf(input, "%c", &tmp)

		values[i] = tmp
		dp[i] = inf
		if tmp == '.' {
			dot = i
		}
	}

	// Solve
	for i := n - 1; i >= dot; i-- {
		if values[i] >= '5' {
			dp[i] = 1
		}

		if values[i] == '4' && i + 1 < n && dp[i + 1] != inf {
			dp[i] = dp[i + 1] + 1
		}
	}

	ans := -1
	for i := dot; i < n; i++ {
		if dp[i] <= t {
			ans = i - 1
			break
		}
	}

	if ans < 0 {
		for i := 0; i < n; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	} else {

		if values[ans] == '.' {
			ans--
		}

		pos := ans
		for pos >= 0 {
			if values[pos] == '.' {
				pos--
				continue
			}

			if values[pos] == '9' {
				values[pos] = '0'
				pos--
				continue
			}

			values[pos]++
			break
		}

		if pos < 0 {
			fmt.Fprint(output, "1")
		}

		// Output
		for i := 0; i <= ans; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	}

	output.Flush()
}

package main

import "fmt"
import "bufio"
import "os"

var bufin *bufio.Reader
var bufout *bufio.Writer

func toArray(s string, n int) ([]int, int) {
	a := make([]int, n+1)
	dot := -1
	for i := 0; i < n; i++ {
		c := s[i]
		if c == '.' {
			dot = i + 1
			a[dot] = -1
		} else {
			a[i+1] = int(c - '0')
		}
	}
	return a, dot
}

func findPos(a []int, n int, dot int) int {
	for i := dot + 1; i < n; i++ {
		if a[i] >= 5 {
			return i
		}
	}
	return -1
}

func previousDigit(pos int, dot int) int {
	if pos-1 == dot {
		return dot - 1
	}
	return pos - 1
}

func roundAt(a []int, n int, dot int, pos int) int {
	for pos > 0 {
		a[pos] = 0
		pos = previousDigit(pos, dot)
		a[pos]++
		if a[pos] < 10 {
			break
		}
		a[pos] = 0
	}
	return pos
}

func solve(a []int, n int, t int, dot int) (int, int) {
	pos := findPos(a, n, dot)
	if pos == -1 {
		return 1, n
	}
	for i := pos + 1; i < n; i++ {
		a[i] = 0
	}
	for (t > 0) && (pos > dot) {
		pos = roundAt(a, n, dot, pos)
		t--
	}
	for (n-1 > dot) && (a[n-1] == 0) {
		n--
	}
	if n-1 == dot {
		n--
	}
	if a[0] == 0 {
		return 1, n
	}
	return 0, n
}

func print(a []int, f int, n int, dot int) {
	for i := f; i < n; i++ {
		if i == dot {
			fmt.Fprintf(bufout, ".")
		} else {
			fmt.Fprintf(bufout, "%d", a[i])
		}
	}
	fmt.Fprintf(bufout, "\n")
}

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

	var n, t, f int
	var s string

	fmt.Fscanf(bufin, "%d %d\n", &n, &t)
	fmt.Fscanf(bufin, "%s\n", &s)

	a, dot := toArray(s, n)
	f, n = solve(a, n+1, t, dot)
	print(a, f, n, dot)
}

// http://codeforces.com/problemset/problem/719/C#
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const inf int = 1e9

func main () {
	var n, t int

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	output := bufio.NewWriterSize(os.Stdout, 1<<10)
	fmt.Fscanln(input, &n, &t)

	values := make([]rune, n)
	dp := make([]int, n)
	dot := 0;
	for i := 0; i < n; i++ {
		var tmp rune
		fmt.Fscanf(input, "%c", &tmp)

		values[i] = tmp
		dp[i] = inf
		if tmp == '.' {
			dot = i
		}
	}

	// Solve
	for i := n - 1; i >= dot; i-- {
		if values[i] >= '5' {
			dp[i] = 1
		}

		if values[i] == '4' && i + 1 < n && dp[i + 1] != inf {
			dp[i] = dp[i + 1] + 1
		}
	}

	ans := -1
	for i := dot; i < n; i++ {
		if dp[i] <= t {
			ans = i - 1
			break
		}
	}

	if ans < 0 {
		for i := 0; i < n; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	} else {

		if values[ans] == '.' {
			ans--
		}

		pos := ans
		for pos >= 0 {
			if values[pos] == '.' {
				pos--
				continue
			}

			if values[pos] == '9' {
				values[pos] = '0'
				pos--
				continue
			}

			values[pos]++
			break
		}

		if pos < 0 {
			fmt.Fprint(output, "1")
		}

		// Output
		for i := 0; i <= ans; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	}

	output.Flush()
}

// http://codeforces.com/problemset/problem/719/C#
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const inf int = 1e9

func main () {
	var n, t int

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	output := bufio.NewWriterSize(os.Stdout, 1<<10)
	fmt.Fscanln(input, &n, &t)

	values := make([]rune, n)
	dp := make([]int, n)
	dot := 0;
	for i := 0; i < n; i++ {
		var tmp rune
		fmt.Fscanf(input, "%c", &tmp)

		values[i] = tmp
		dp[i] = inf
		if tmp == '.' {
			dot = i
		}
	}

	// Solve
	for i := n - 1; i > dot; i-- {
		if values[i] >= '5' {
			dp[i] = 1
		}

		if values[i] == '4' && i + 1 < n && dp[i + 1] != inf {
			dp[i] = dp[i + 1] + 1
		}
	}

	ans := 0
	for i := dot; i < n; i++ {
		if dp[i] <= t {
			ans = i
			break
		}
	}

	if ans == 0 {
		for i := 0; i < n; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	} else {
		if values[ans - 1] == '.' {
			ans--
		}

		inc_pos := int(ans - 1)
		for inc_pos >= 0 {
			if values[inc_pos] < '9' {
				break
			}

			if values[inc_pos] == '.' {
				inc_pos--
				continue
			}

			values[inc_pos] = '0'
			inc_pos--
		}

		if inc_pos < 0 {
			fmt.Fprint(output, "1")
		} else {
			values[inc_pos]++
		}

		for i := 0; i < ans; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	}

	output.Flush()
}

// http://codeforces.com/problemset/problem/719/C#
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const inf int = 1e9

func main () {
	var n, t int

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	output := bufio.NewWriterSize(os.Stdout, 1<<10)
	fmt.Fscanln(input, &n, &t)

	values := make([]rune, n)
	dp := make([]int, n)
	dot := 0;
	for i := 0; i < n; i++ {
		var tmp rune
		fmt.Fscanf(input, "%c", &tmp)

		values[i] = tmp
		dp[i] = inf
		if tmp == '.' {
			dot = i
		}
	}

	// Solve
	for i := n - 1; i > dot; i-- {
		if values[i] >= '5' {
			dp[i] = 1
		}

		if values[i] == '4' && i + 1 < n && dp[i + 1] != inf {
			dp[i] = dp[i + 1] + 1
		}
	}

	ans := 0
	for i := dot; i < n; i++ {
		if dp[i] <= t {
			ans = i
			break
		}
	}

	if ans == 0 {
		for i := 0; i < n; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	} else {
		for i := 0; i < n; i++ {
			out := values[i]

			if i == ans - 1{
				if out == '9' {
					out = '0'
				} else {
					out++
				}
			}

			fmt.Fprint(output, string(out))

			if i == ans - 1 {
				break
			}
		}
	}

	output.Flush()
}

// http://codeforces.com/problemset/problem/719/C#
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const inf int = 1e9

func main () {
	var n, t int

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	output := bufio.NewWriterSize(os.Stdout, 1<<10)
	fmt.Fscanln(input, &n, &t)

	values := make([]rune, n)
	dp := make([]int, n)
	dot := 0;
	for i := 0; i < n; i++ {
		var tmp rune
		fmt.Fscanf(input, "%c", &tmp)

		values[i] = tmp
		dp[i] = inf
		if tmp == '.' {
			dot = i
		}
	}

	// Solve
	for i := n - 1; i > dot; i-- {
		if values[i] >= '5' {
			dp[i] = 1
		}

		if values[i] == '4' && i + 1 < n && dp[i + 1] != inf {
			dp[i] = dp[i + 1] + 1
		}
	}

	ans := -1
	for i := dot; i < n; i++ {
		if dp[i] <= t {
			ans = i - 1
			break
		}
	}

	if ans < 0 {
		for i := 0; i < n; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	} else {

		if values[ans] == '.' {
			ans--
		}

		pos := ans
		for pos >= 0 {
			if values[pos] == '.' {
				pos--
				continue
			}

			if values[pos] == '9' {
				values[pos] = '0'
				pos--
				continue
			}

			values[pos]++
			break
		}

		if pos < 0 {
			fmt.Fprint(output, "1")
		}

		// Output
		for i := 0; i <= ans; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	}

	output.Flush()
}

// http://codeforces.com/problemset/problem/719/C#
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const inf int = 1e9

func main () {
	var n, t int

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	output := bufio.NewWriterSize(os.Stdout, 1<<10)
	fmt.Fscanln(input, &n, &t)

	values := make([]rune, n)
	dp := make([]int, n)
	dot := 0;
	for i := 0; i < n; i++ {
		var tmp rune
		fmt.Fscanf(input, "%c", &tmp)

		values[i] = tmp
		dp[i] = inf
		if tmp == '.' {
			dot = i
		}
	}

	// Solve
	for i := n - 1; i > dot; i-- {
		if values[i] >= '5' {
			dp[i] = 1
		}

		if values[i] == '4' && i + 1 < n && dp[i + 1] != inf {
			dp[i] = dp[i + 1] + 1
		}
	}

	ans := 0
	for i := dot; i < n; i++ {
		if dp[i] <= t {
			ans = i
			break
		}
	}

	if ans == 0 {
		for i := 0; i < n; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	} else {
		if values[ans - 1] == '.' {
			ans--
		}

		if values[ans - 1] == '9' {
			values[ans - 1] = '0'
		} else {
			values[ans - 1]++
		}

		for i := 0; i < ans; i++ {
			fmt.Fprint(output, string(values[i]))
		}
	}

	output.Flush()
}


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

package main

import "fmt"

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

	max = 0
	min = 1000000000
	for i := 0; i < n; i++ {
		var number int
		fmt.Scanf("%d", &number)
		if number > max {
			max = number
		}
		if number < min {
			min = number
		}
	}

	fmt.Println(max - min + 1 - n)
}

package main

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

func main() {
	var n int
	var a int64
	max := int64(math.MinInt64)
	min := int64(math.MaxInt64)
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &a)
		if max < a {
			max = a
		}
		if min > a {
			min = a
		}
	}
	fmt.Println(max - min + int64(1) - int64(n))
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scanln(&n)
	el := make([]int, n)
	for i := range el {
		fmt.Scan(&el[i])
	}
	sort.Sort(sort.IntSlice(el))
	minEl, maxEl := el[0], el[len(el)-1]
	fmt.Println(maxEl - minEl + 1 - len(el))
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	var m []int = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&m[i])
	}
	sort.Ints(m)
	var pr int = 0
	for i := 0; i < n-1; i ++ {
		pr += m[i+1] - m[i] - 1
	}
	fmt.Println(pr)
}

package main

import (
	"fmt"
)

func main() {
	var n, nextVal int
	fmt.Scanln(&n)
	fmt.Scan(&nextVal)
	min := nextVal
	max := nextVal
	for i := 0; i < n-1; i++ {
		fmt.Scan(&nextVal)
		if nextVal < min {
			min = nextVal
		}
		if nextVal > max {
			max = nextVal
		}
	}
	fmt.Println(max - min + 1 - n)
}

package main

import "fmt"

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

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

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

	var x int
	fmt.Scan(&x)

	min, max := x, x
	for i := 1; i < N; i++ {
		var x int
		fmt.Scan(&x)
		min = mn2(x, min)
		max = mx2(x, max)
	}

	fmt.Println(max - min + 1 - N)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var buf []int
	var n, k, sum int
	//var colvo int = 1
	fmt.Scan(&k)
	for i:=0; i<k; i++ {
		fmt.Scan(&n)
		buf = append(buf, n)
	}
	sort.Ints(buf)
		buf = append(buf, -1)
	for i:=0; i<k; i++ {
		if buf[i+1] != -1 && buf[i+1]-buf[i] != 1 {
			sum += buf[i+1]-buf[i]-1
		}
	}
	fmt.Println(sum)
}

package main

import "fmt"

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int,n)
	readN(a,0,n)
	max , min := maxMin(a)
	out := max-min+1-len(a)
	if out < 0 {
		out = 0
	}
	fmt.Println(out)
}

func maxMin(a []int)(max int,min int){
	max,min = a[0],a[0]
	for _,v := range a{
		if v > max {
			max = v
		}
		if v < min {
			min = v
		}
	}
	return
}

func readN(all []int,i ,n int){
	if n==0{
		return
	}
	if m,err := fmt.Scan(&all[i]);m != 1{
		panic(err)
	}
	readN(all,i+1,n-1)
}

package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	"sort"
)
var (
	r *bufio.Scanner
	w *bufio.Writer
)

const ISDEBUG = false

func readLine() string {
	r.Scan()
	return r.Text()
}

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

func readInts(n int) []int {
	var res []int
	for i:=0; i<n; i++ {
		if !r.Scan() {
			fmt.Println(r.Err())
		}
		x, _ := strconv.Atoi(r.Text())
		res = append(res, x)
	}
	return res
}

func heist() {
	n := readInt()
	a := readInts(n)
	sort.Ints(a)

	result := 0
	previous := a[0]

	for i:=1; i<n; i++ {
		result += a[i] - previous - 1
		previous = a[i]
	}

	w.WriteString(fmt.Sprintf("%v", result))
}

func main() {
	if ISDEBUG {
		fi, err := os.Open("input.txt")
		if err != nil {
			panic(err)
		}
		fo, _ := os.OpenFile("output.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
		r = bufio.NewScanner(fi)
		w = bufio.NewWriter(fo)

		defer fi.Close()
		defer fo.Close()
	} else {
		r = bufio.NewScanner(os.Stdin)
		w = bufio.NewWriter(os.Stdout)
	}
	r.Split(bufio.ScanWords)
	defer w.Flush()

	heist()
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	var ind []int = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&ind[i])
	}
	sort.Ints(ind)
	var res = 0
	for i := 0; i < n-1; i ++ {
		res += ind[i+1] - ind[i] - 1
	}
	fmt.Println(res)
}

package main
import "fmt"
import "math"
func main() {
	var n, x int
	fmt.Scan(&n)
	a := math.MaxInt32
	b:= -1
	for i := 0; i < n; i++ {
		fmt.Scan(&x)
		if x < a {
			a = x
		}
		if x > b {
			b = x
		}
	}
	fmt.Print(b+1-a-n)
}

package main

import "fmt"
import "sort"

func main() {
	var n int
	fmt.Scan(&n)
	var a []int = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)
	n = a[n-1] - a[0] + 1 - n
	fmt.Print(n)
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"os"
)

const INF  = 1000000001

type Pair struct {
	first, second int
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}
func sort(arr []int) []int {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i] < arr[right] {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort(arr[:left])
	sort(arr[left+1:])
	return arr
}

func solution(reader io.Reader, writer io.Writer) {
	var n, r int
	fmt.Fscanf(reader, "%d\n", &n)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	a = sort(a)

	for i := 0; i < n - 1; i++ {
		r += a[i + 1] - a[i] - 1
	}

	fmt.Fprintf(writer, "%d", r)

}

func main() {

	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("file.out")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)
	defer writer.Flush()

	solution(reader, writer)
}

package main

import "fmt"
import "sort"

func main() {
	var n int

	fmt.Scanln(&n)
	a := make([]int, n)

	for ii := 0; ii < n; ii++ {
		fmt.Scan(&a[ii])
	}
	sort.Ints(a)
	sum := 0
	for ii := 0; ii < n-1; ii++ {
		if ((a[ii + 1] - a[ii]) != 1) {
			sum = sum + a[ii + 1] - a[ii] - 1
		}
	}
	fmt.Println(sum)
}

func f(i int) float64 {
	return float64(i)
}

package main

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

func main() {
	var (
		n int // n - кол-во танцоров, a - стоимость белого, b - стоимость черного
		a []int
	)

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	n, _ = strconv.Atoi(scanner.Text())

	a = make([]int, n)

	for i := 0; i < n; i++ {
		scanner.Scan()
		tmp, _ := strconv.Atoi(scanner.Text())

		a[i] = tmp
	}

	sort.Ints(a)

	cnt := 0
	for i := 1; i < n; i++ {
		prev := a[i-1]
		cur := a[i]
		if cur-prev > 1 {
			cnt += cur - prev - 1
		}
	}

	fmt.Println(cnt)
}

package main

import "fmt"

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

	max = 0
	min = 1000000000
	for i := 0; i < n; i++ {
		var number int
		fmt.Scanf("%d", &number)
		if number > max {
			max = number
		}
		if number < min {
			min = number
		}
	}

	fmt.Println(max - min + 1 - n)
}

package main

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

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

package main

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

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

package main

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

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

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scanln(&n)
	el := make([]int, n)
	for i := range el {
		fmt.Scan(&el[i])
	}
	sort.Sort(sort.IntSlice(el))
	minEl, maxEl := el[0], el[len(el)-1]
	elAtFirst := make([]int, 0)
	for i := minEl; i <= maxEl; i++ {
		elAtFirst = append(elAtFirst, i)
	}

}