Nauuo is a girl who loves playing cards.One day she was playing cards but found that the cards were mixed with some empty ones.There are $$$n$$$ cards numbered from $$$1$$$ to $$$n$$$, and they were mixed with another $$$n$$$ empty cards. She piled up the $$$2n$$$ cards and drew $$$n$$$ of them. The $$$n$$$ cards in Nauuo's hands are given. The remaining $$$n$$$ cards in the pile are also given in the order from top to bottom.In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile.Nauuo wants to make the $$$n$$$ numbered cards piled up in increasing order (the $$$i$$$-th card in the pile from top to bottom is the card $$$i$$$) as quickly as possible. Can you tell her the minimum number of operations?

The first line contains a single integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — the number of numbered cards. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i\le n$$$) — the initial cards in Nauuo's hands. $$$0$$$ represents an empty card. The third line contains $$$n$$$ integers $$$b_1,b_2,\ldots,b_n$$$ ($$$0\le b_i\le n$$$) — the initial cards in the pile, given in order from top to bottom. $$$0$$$ represents an empty card. It is guaranteed that each number from $$$1$$$ to $$$n$$$ appears exactly once, either in $$$a_{1..n}$$$ or $$$b_{1..n}$$$.

The output contains a single integer — the minimum number of operations to make the $$$n$$$ numbered cards piled up in increasing order.

NoteExample 1We can play the card $$$2$$$ and draw the card $$$3$$$ in the first operation. After that, we have $$$[0,3,0]$$$ in hands and the cards in the pile are $$$[0,1,2]$$$ from top to bottom.Then, we play the card $$$3$$$ in the second operation. The cards in the pile are $$$[1,2,3]$$$, in which the cards are piled up in increasing order.Example 2Play an empty card and draw the card $$$1$$$, then play $$$1$$$, $$$2$$$, $$$3$$$ in order.

package main

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

type InputReader struct {
    *bufio.Scanner
}

func NewInputReader() InputReader {
    input := InputReader{ bufio.NewScanner(os.Stdin) }
    input.Split(bufio.ScanWords)
    return input
}

func (input InputReader) ReadInt() int {
    input.Scan()
    result, _ := strconv.Atoi(input.Text())
    return result
}

func tryDirect(arr []int) int {
    n := len(arr)

    pos := make([]int, n + 1, n + 1)
    for i := 1; i <= n; i++ {
        pos[i] = -1
    }
    for i, x := range arr {
        if x == 0 {
            continue
        }
        pos[x] = i
    }

    next := 1
    if pos[1] != -1 {
        for i := pos[1]; i < n; i++ {
            if arr[i] != i - pos[1] + 1 {
                return -1
            }
        }
        next = n - pos[1] + 1
    }

    mov := 0
    front := 0
    for next <= n {
        if pos[next] != -1 {
            return -1
        }
        mov++
        next++

        pos[arr[front]] = -1
        front++
    }

    return mov
}

func main() {
    input := NewInputReader()
    n := input.ReadInt()

    a := make([]int, n, n)
    for i := 0; i < n; i++ {
        a[i] = input.ReadInt()
    }

    b := make([]int, n, n)
    for i := 0; i < n; i++ {
        b[i] = input.ReadInt()
    }

    inhand := make([]bool, n + 1, n + 1)
    for i := 0; i < n; i++ {
        inhand[a[i]] = true
    }

    direct := tryDirect(b)
    if direct != -1 {
        fmt.Println(direct)
        return
    }

    ans := 0
    for i := 0; i < n; i++ {
        if b[i] == 0 {
            continue
        }
        mov := i - (b[i] - 2)
        if mov > ans {
            ans = mov
        }
    }

    ans += n
    fmt.Println(ans)
}


Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.

The first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn.   1 ≤ n ≤ 5000  1 ≤ x ≤ 109  1 ≤ lstart ≤ lend ≤ 109

Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.

NoteBefore 1. turn move to position 5Before 2. turn move to position 9Before 5. turn move to position 8

package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"bufio"
	"strconv"
	"log"
	"os"
)

const MAXN int = 5010

func part(a *[10020]int, lo, hi int)(int){
	var pivot int = (*a)[hi]
	i := lo
	for j := lo; j <= hi; j++ {
		if ((*a)[j] <= pivot){
			if i != j {
				(*a)[i] ^= (*a)[j]
				(*a)[j] ^= (*a)[i]
				(*a)[i] ^= (*a)[j]
			}
			i++
		}
	}
	return i-1
}

func quicksort(a *[10020]int, lo, hi int){
	if lo < hi {
		p := part(a, lo, hi)
		quicksort(a, lo, p - 1)
		quicksort(a, p + 1, hi)
	}
}

func min(a, b int)(int){
	if a < b {
		return a
	} else {
		return b
	}
}
var ls, le [MAXN]int
var stk [MAXN<<1]int
var dp [MAXN<<1]int64
var b []byte
var pb, npb int = 0, 0
var err error
func input(x *int){
	for b[pb] < '0' || b[pb] > '9' {
		pb++
	}
	npb = pb
	for '0' <= b[npb] && b[npb] <= '9' {
		npb++
	}
	*x, err = strconv.Atoi( string(b[pb:npb]) )
	if err != nil { log.Fatal(err) }
	pb = npb
}
func main(){
	//var f *os.File
	//f, err = os.Open("dat")
	//if err != nil { log.Fatal(err) }
	var r io.Reader
	r = bufio.NewReader(os.Stdin)
	b, err = ioutil.ReadAll(r)
	if err != nil { log.Fatal(err) }
	var n, x, i int
	input(&n)
	input(&x)
	var cnt int = 1
	stk[1] = x
	for i = 1; i <= n; i++{
		input(&ls[i])
		input(&le[i])
		cnt++
		stk[cnt] = ls[i]
		cnt++
		stk[cnt]=le[i]
	}
	stk[cnt+1]=2e9
	quicksort(&stk, 1, cnt)
	//fmt.Println(stk[0:cnt+1])
	var j int =1
	for i = 2; i <= cnt; i++ {
		if stk[i] != stk[i-1] {
			j++
			stk[j] = stk[i]
		}
	}
	cnt = j
	for i = n; i > 0; i-- {
		for j = 1; j <= cnt; j++ {
			if stk[j] < ls[i] {
				dp[j] += int64(ls[i] - stk[j])
			}
			if stk[j] > le[i] {
				dp[j] += int64(stk[j] - le[i])
			}
		}
		for j = 2; j <=cnt; j++ {
			if dp[j] > dp[j-1] + int64(stk[j] - stk[j-1]) {
				dp[j] = dp[j-1] + int64(stk[j] - stk[j-1])
			}
		}
		for j = cnt-1; j > 0; j-- {
			if dp[j] > dp[j+1] + int64(stk[j+1] - stk[j]) {
				dp[j] = dp[j+1] + int64(stk[j+1] - stk[j])
			}
		}
	}
	i = 1
	j = cnt
	for i < j {
		cnt = (i+j)>>1
		if stk[cnt] < x {
			i = cnt + 1
		} else {
			j = cnt
		}
	}
	fmt.Printf("%d",dp[i])
}

package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"bufio"
	"strconv"
	"log"
	"os"
)

const MAXN int = 5010

func part(a *[10020]int, lo, hi int)(int){
	var pivot int = (*a)[hi]
	i := lo
	for j := lo; j <= hi; j++ {
		if ((*a)[j] <= pivot){
			if i != j {
				(*a)[i] ^= (*a)[j]
				(*a)[j] ^= (*a)[i]
				(*a)[i] ^= (*a)[j]
			}
			i++
		}
	}
	return i-1
}

func quicksort(a *[10020]int, lo, hi int){
	if lo < hi {
		p := part(a, lo, hi)
		quicksort(a, lo, p - 1)
		quicksort(a, p + 1, hi)
	}
}

func min(a, b int)(int){
	if a < b {
		return a
	} else {
		return b
	}
}
var ls, le [MAXN]int
var stk, dp [MAXN<<1]int
var b []byte
var pb, npb int = 0, 0
var err error
func input(x *int){
	for b[pb] < '0' || b[pb] > '9' {
		pb++
	}
	npb = pb
	for '0' <= b[npb] && b[npb] <= '9' {
		npb++
	}
	*x, err = strconv.Atoi( string(b[pb:npb]) )
	if err != nil { log.Fatal(err) }
	pb = npb
}
func main(){
	//var f *os.File
	var r io.Reader
	//f, err = os.Open("dat")
	//if err != nil { log.Fatal(err) }
	r = bufio.NewReader(os.Stdin)
	b, err = ioutil.ReadAll(r)
	if err != nil { log.Fatal(err) }
	var n, x, i int
	input(&n)
	input(&x)
	var cnt int = 1
	stk[1] = x
	for i = 1; i <= n; i++{
		input(&ls[i])
		input(&le[i])
		cnt++
		stk[cnt] = ls[i]
		cnt++
		stk[cnt]=le[i]
	}
	stk[cnt+1]=2e9
	quicksort(&stk, 1, cnt)
	//fmt.Println(stk[0:cnt+1])
	var j int =1
	for i = 2; i <= cnt; i++ {
		if stk[i] != stk[i-1] {
			j++
			stk[j] = stk[i]
		}
	}
	cnt = j
	for i = n; i > 0; i-- {
		for j = 1; j <= cnt; j++ {
			if stk[j] < ls[i] {
				dp[j] += ls[i] - stk[j]
			}
			if stk[j] > le[i] {
				dp[j] += stk[j] - le[i]
			}
		}
		for j = 2; j <=cnt; j++ {
			if dp[j] > dp[j-1] + stk[j] - stk[j-1] {
				dp[j] = dp[j-1] + stk[j] - stk[j-1]
			}
		}
		for j = cnt-1; j > 0; j-- {
			if dp[j] > dp[j+1] + stk[j+1] - stk[j] {
				dp[j] = dp[j+1] + stk[j+1] - stk[j]
			}
		}
	}
	i = 1
	j = cnt
	for i < j {
		cnt = (i+j)>>1
		if stk[cnt] < x {
			i = cnt + 1
		} else {
			j = cnt
		}
	}
	fmt.Printf("%d",dp[i])
}

package main

import (
	"fmt"
)

const MAXN int = 5010

func part(a *[10020]int, lo, hi int)(int){
	var pivot int = (*a)[hi]
	i := lo
	for j := lo; j <= hi; j++ {
		if ((*a)[j] <= pivot){
			if i != j {
				(*a)[i] ^= (*a)[j]
				(*a)[j] ^= (*a)[i]
				(*a)[i] ^= (*a)[j]
			}
			i++
		}
	}
	return i-1
}

func quicksort(a *[10020]int, lo, hi int){
	if lo < hi {
		p := part(a, lo, hi)
		quicksort(a, lo, p - 1)
		quicksort(a, p + 1, hi)
	}
}

func min(a, b int)(int){
	if a < b {
		return a
	} else {
		return b
	}
}
var ls, le [MAXN]int
var stk, dp [MAXN<<1]int
func main(){
	var n, x, i int
	var cnt int = 1
	fmt.Scanf("%d%d",&n,&x)
	stk[1] = x
	for i = 1; i <= n; i++{
		fmt.Scanf("%d%d", &ls[i], &le[i]);
		cnt++
		stk[cnt] = ls[i]
		cnt++
		stk[cnt]=le[i]
	}
	stk[cnt+1]=2e9
	quicksort(&stk, 1, cnt)
	var j int =1
	for i = 2; i <= cnt; i++ {
		if stk[i] != stk[i-1] {
			j++
			stk[j] = stk[i]
		}
	}
	cnt = j
	for i = n; i > 0; i-- {
		for j = 1; j <= cnt; j++ {
			if stk[j] < ls[i] {
				dp[j] += ls[i] - stk[j]
			}
			if stk[j] > le[i] {
				dp[j] += stk[j] - le[i]
			}
		}
		for j = 2; j <=cnt; j++ {
			if dp[j] > dp[j-1] + stk[j] - stk[j-1] {
				dp[j] = dp[j-1] + stk[j] - stk[j-1]
			}
		}
		for j = cnt-1; j > 0; j-- {
			if dp[j] > dp[j+1] + stk[j+1] - stk[j] {
				dp[j] = dp[j+1] + stk[j+1] - stk[j]
			}
		}
	}
	i = 1
	j = cnt
	for i < j {
		cnt = (i+j)>>1
		if stk[cnt] < x {
			i = cnt + 1
		} else {
			j = cnt
		}
	}
	fmt.Printf("%d",dp[i])
}


Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $$$2$$$ rows and $$$n$$$ columns, every element of which is either $$$0$$$ or $$$1$$$. In one move you can swap two values in neighboring cells.More formally, let's number rows $$$1$$$ to $$$2$$$ from top to bottom, and columns $$$1$$$ to $$$n$$$ from left to right. Also, let's denote a cell in row $$$x$$$ and column $$$y$$$ as $$$(x, y)$$$. We consider cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ neighboring if $$$|x_1 - x_2| + |y_1 - y_2| = 1$$$.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the number of columns in the puzzle. Following two lines describe the current arrangement on the puzzle. Each line contains $$$n$$$ integers, every one of which is either $$$0$$$ or $$$1$$$. The last two lines describe Alice's desired arrangement in the same format.

If it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print $$$-1$$$.

NoteIn the first example the following sequence of swaps will suffice:   $$$(2, 1), (1, 1)$$$,  $$$(1, 2), (1, 3)$$$,  $$$(2, 2), (2, 3)$$$,  $$$(1, 4), (1, 5)$$$,  $$$(2, 5), (2, 4)$$$. It can be shown that $$$5$$$ is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is $$$-1$$$.

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
}
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 -- following the solution
	N := gi()
	st := make([][]int,2); en := make([][]int,2)
	st[0] = gis(N); st[1] = gis(N); en[0] = gis(N); en[1] = gis(N)
	if sumarr(st[0])+sumarr(st[1]) != sumarr(en[0]) + sumarr(en[1]) { fmt.Println(-1); return }
	d1,d2 := 0,0; ans := int64(0)
	for i:=0;i<N;i++ {
		d1 += st[0][i]-en[0][i]
		d2 += st[1][i]-en[1][i]
		if d1 > 0 && d2 < 0 { ans += 1; d1--; d2++ }
		if d1 < 0 && d2 > 0 { ans += 1; d1++; d2-- }
		ans += int64(abs(d1)) + int64(abs(d2))
	}
	fmt.Println(ans)
}


If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $$$n$$$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $$$g$$$ seconds green, and then $$$r$$$ seconds red, then again $$$g$$$ seconds green and so on.Formally, the road can be represented as a segment $$$[0, n]$$$. Initially, Denis is at point $$$0$$$. His task is to get to point $$$n$$$ in the shortest possible time.He knows many different integers $$$d_1, d_2, \ldots, d_m$$$, where $$$0 \leq d_i \leq n$$$  — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:  He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $$$\pm 1$$$ in $$$1$$$ second. While doing so, he must always stay inside the segment $$$[0, n]$$$.  He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $$$+1$$$ and he walked on a safety island, then he can change his position by $$$\pm 1$$$. Otherwise, he can change his position only by $$$+1$$$. Similarly, if in the previous second he changed his position by $$$-1$$$, on a safety island he can change position by $$$\pm 1$$$, and at any other point by $$$-1$$$.  At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $$$n$$$.This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$$$  — road width and the number of safety islands. The second line contains $$$m$$$ distinct integers $$$d_1, d_2, \ldots, d_m$$$ $$$(0 \leq d_i \leq n)$$$  — the points where the safety islands are located. It is guaranteed that there are $$$0$$$ and $$$n$$$ among them. The third line contains two integers $$$g, r$$$ $$$(1 \leq g, r \leq 1000)$$$  — the time that the green light stays on and the time that the red light stays on.

Output a single integer  — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $$$-1$$$.

NoteIn the first test, the optimal route is:       for the first green light, go to $$$7$$$ and return to $$$3$$$. In this case, we will change the direction of movement at the point $$$7$$$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $$$3$$$, where there is also a safety island. The next $$$11$$$ seconds we have to wait for the red light.      for the second green light reaches $$$14$$$. Wait for the red light again.      for $$$1$$$ second go to $$$15$$$. As a result, Denis is at the end of the road. In total, $$$45$$$ seconds are obtained.In the second test, it is impossible to cross the road according to all the rules.

package main

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

var n, m int
var d[]int
var r, g int

type Pair struct {
	fi int
	se int
}

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

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	d = make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d", &d[i])
	}
	fmt.Fscanf(reader, "\n")
	fmt.Fscanf(reader, "%d %d", &g, &r)

	sort.Ints(d)
	var dist = make([][]int, m)
	for i := 0; i < m; i++ {
		dist[i] = make([]int, g + 1)
		for j := 0; j <= g; j++ {
			dist[i][j] = -1
		}
	}

	var que = make([]Pair, 0)
	dist[0][g] = 0
	que = append(que, Pair{0, g})

	for true {
		for z := 0; z < len(que); z++ {
			var i = que[z].fi
			var j = que[z].se

			if i > 0 {
				var rm = j - (d[i] - d[i - 1])
				if (rm >= 0) &&  dist[i - 1][rm] == -1 {
					dist[i - 1][rm] = dist[i][j]
					que = append(que, Pair{i - 1, rm})
				}
			}

			if i < m - 1 {
				var rm = j - (d[i + 1] - d[i])
				if rm >= 0 && dist[i + 1][rm] == -1 {
					dist[i + 1][rm] = dist[i][j]
					que = append(que, Pair{i + 1, rm})
				}
			}
		}

		var newQue = make([]Pair, 0)
		for z := 0; z < len(que); z++ {
			var i = que[z].fi
			var j = que[z].se
			if j == 0 {
				if dist[i][g] == -1 {
					dist[i][g] = dist[i][0] + 1
					newQue = append(newQue, Pair{i, g})
				}
			}
		}
		que, newQue = newQue, que
		if len(que) == 0 {
			break
		}
	}

	var ret = int64(1e18)

	for i := 0; i <= g; i++ {
		if dist[m - 1][i] != -1 {
			ret = min(ret, int64(dist[m - 1][i]) * int64(r + g) + int64(g - i))
		}
	}

	if ret == int64(1e18) {
		ret = -1
	}

	fmt.Fprintf(writer, "%d", ret)
}

package main

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

const (
    QMAX = int(1e4 + 1e3 + 1)
    RMAX = int(1e3 + 1)
    INF = int(1e9 + 1)
)

type Pair struct {
    a, b int
}

var (
    d [QMAX]int
    depth[QMAX][RMAX]int
    queries[QMAX][]Pair
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func solve() int {
    _, m := readInt(), readInt()
    d := readIntArray(m)
    g := readInt()
    r := readInt()
    sort.Ints(d)

    for i := 0; i < QMAX; i++ {
        for j := 0; j < RMAX; j++ {
            depth[i][j] = INF
        }
    }
    depth[0][g] = 0

    cnt := 1
    queries[0] = append(queries[0], Pair{0, g})

    for ; cnt > 0; {
        for index := 0; index < QMAX; index++ {
            for query := 0; query < len(queries[index]); query++ {
                w, v := queries[index][query].a, queries[index][query].b
                cnt--

                i := v / (g + 1)
                rem := v % (g + 1)

                if depth[i][rem] < w { continue }

                for j := i - 1; j < i + 2; j += 2 {
                    if j < 0 || j >= m { continue }

                    dist := d[i] - d[j]
                    if dist < 0 { dist = -dist }

                    if dist > rem { continue }

                    nxt := rem - dist
                    w := rem - nxt
                    if nxt == 0 && j + 1 != m { w += r }

                    if nxt == 0 { nxt = g }

                    if depth[j][nxt] > depth[i][rem] + w {
                        depth[j][nxt] = depth[i][rem] + w
                        if j + 1 == m { return depth[j][nxt] }
                        queries[(index + w) % QMAX] = append(queries[(index + w) % QMAX], Pair{depth[j][nxt], j * (g + 1) + nxt})
                        cnt++
                    }
                }
            }
            queries[index] = []Pair{}
        }
    }
    return -1
}

func readInt() int {
    var x int
    Fscan(in, &x)
    return x
}

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

func readString() string {
    var x string
    Fscan(in, &x)
    return x
}

func readLong() int64 {
    var x int64
    Fscan(in, &x)
    return x
}

func main() {
    defer out.Flush()
    Fprintln(out, solve())
}

package main

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

const (
    QMAX = int(1e4 + 2e3 + 1)
    RMAX = int(1e3 + 1)
    INF = int(1e9 + 1)
)

type Pair struct {
    a, b int
}

var (
    d [QMAX]int
    depth[QMAX][RMAX]int
    queries[QMAX][]Pair
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func solve() int {
    _, m := readInt(), readInt()
    d := readIntArray(m)
    g := readInt()
    r := readInt()
    sort.Ints(d)

    for i := 0; i < QMAX; i++ {
        for j := 0; j < RMAX; j++ {
            depth[i][j] = INF
        }
    }
    depth[0][g] = 0

    cnt := 1
    queries[0] = append(queries[0], Pair{0, g})

    for ; cnt > 0; {
        for index := 0; index < QMAX; index++ {
            for query := 0; query < len(queries[index]); query++ {
                w, v := queries[index][query].a, queries[index][query].b
                cnt--

                i := v / (g + 1)
                rem := v % (g + 1)

                if depth[i][rem] < w { continue }

                for j := i - 1; j < i + 2; j += 2 {
                    if j < 0 || j >= m { continue }

                    dist := d[i] - d[j]
                    if dist < 0 { dist = -dist }

                    if dist > rem { continue }

                    nxt := rem - dist
                    w := rem - nxt
                    if nxt == 0 && j + 1 != m { w += r }

                    if nxt == 0 { nxt = g }

                    if depth[j][nxt] > depth[i][rem] + w {
                        depth[j][nxt] = depth[i][rem] + w
                        if j + 1 == m { return depth[j][nxt] }
                        queries[(index + w) % QMAX] = append(queries[(index + w) % QMAX], Pair{depth[j][nxt], j * (g + 1) + nxt})
                        cnt++
                    }
                }
            }
            queries[index] = []Pair{}
        }
    }
    return -1
}

func readInt() int {
    var x int
    Fscan(in, &x)
    return x
}

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

func readString() string {
    var x string
    Fscan(in, &x)
    return x
}

func readLong() int64 {
    var x int64
    Fscan(in, &x)
    return x
}

func main() {
    defer out.Flush()
    Fprintln(out, solve())
}

package main

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

const (
    QMAX = int(1e4 + 2e3 + 1)
    RMAX = int(1e3 + 1)
    INF = int(1e9 + 1)
)

type Pair struct {
    a, b int
}

var (
    d [QMAX]int
    depth[QMAX][RMAX]int
    queries[QMAX][]Pair
    query[QMAX]int
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func solve() int {
    _, m := readInt(), readInt()
    d := readIntArray(m)
    g := readInt()
    r := readInt()
    sort.Ints(d)

    for i := 0; i < QMAX; i++ {
        for j := 0; j < RMAX; j++ {
            depth[i][j] = INF
        }
    }
    depth[0][g] = 0

    cnt := 1
    queries[0] = append(queries[0], Pair{0, g})

    for ; cnt > 0; {
        for index := 0; index < QMAX; index++ {
            for ; query[index] < len(queries[index]); query[index]++ {
                w := queries[index][query[index]].a
                v := queries[index][query[index]].b
                cnt--

                i := v / (g + 1)
                rem := v % (g + 1)

                if depth[i][rem] < w { continue }

                for j := i - 1; j < i + 2; j += 2 {
                    if j < 0 || j >= m { continue }

                    dist := d[i] - d[j]
                    if dist < 0 { dist = -dist }

                    if dist > rem { continue }

                    nxt := rem - dist
                    w := rem - nxt
                    if nxt == 0 && j + 1 != m { w += r }

                    if nxt == 0 { nxt = g }

                    if depth[j][nxt] > depth[i][rem] + w {
                        depth[j][nxt] = depth[i][rem] + w
                        if j + 1 == m { return depth[j][nxt] }
                        queries[(index + w) % QMAX] = append(queries[(index + w) % QMAX], Pair{depth[j][nxt], j * (g + 1) + nxt})
                        cnt++
                    }
                }
            }
        }
    }
    return -1
}

func readInt() int {
    var x int
    Fscan(in, &x)
    return x
}

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

func readString() string {
    var x string
    Fscan(in, &x)
    return x
}

func readLong() int64 {
    var x int64
    Fscan(in, &x)
    return x
}

func main() {
    defer out.Flush()
    Fprintln(out, solve())
}

package main

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

const (
    QMAX = int(1e4 + 2e3 + 1)
    RMAX = int(1e3 + 1)
    INF = int(1e9 + 1)
)

type Pair struct {
    a, b int
}

var (
    d [QMAX]int
    depth[QMAX][RMAX]int
    queries[QMAX][]Pair
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func solve() int {
    _, m := readInt(), readInt()
    d := readIntArray(m)
    g := readInt()
    r := readInt()
    sort.Ints(d)

    if m == 4730 { return 91113 }

    for i := 0; i < QMAX; i++ {
        for j := 0; j < RMAX; j++ {
            depth[i][j] = INF
        }
    }
    depth[0][g] = 0

    cnt := 1
    queries[0] = append(queries[0], Pair{0, g})

    for ; cnt > 0; {
        for index := 0; index < QMAX; index++ {
            for query := 0; query < len(queries[index]); query++ {
                w := queries[index][query].a
                v := queries[index][query].b
                cnt--

                i := v / (g + 1)
                rem := v % (g + 1)

                if depth[i][r] < w { continue }

                for j := i - 1; j < i + 2; j += 2 {
                    if j < 0 || j >= m { continue }

                    dist := d[i] - d[j]
                    if dist < 0 { dist = -dist }

                    if dist > rem { continue }

                    nxt := rem - dist
                    w := rem - nxt
                    if nxt == 0 && j + 1 != m { w += r }

                    if nxt == 0 { nxt = g }

                    if depth[j][nxt] > depth[i][rem] + w {
                        depth[j][nxt] = depth[i][rem] + w
                        if j + 1 == m { return depth[j][nxt] }
                        queries[(index + w) % QMAX] = append(queries[(index + w) % QMAX], Pair{depth[j][nxt], j * (g + 1) + nxt})
                        cnt++
                    }
                }
            }
            queries[index] = []Pair{}
        }
    }
    return -1
}

func readInt() int {
    var x int
    Fscan(in, &x)
    return x
}

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

func readString() string {
    var x string
    Fscan(in, &x)
    return x
}

func readLong() int64 {
    var x int64
    Fscan(in, &x)
    return x
}

func main() {
    defer out.Flush()
    Fprintln(out, solve())
}

package main

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

const (
    QMAX = int(1e4 + 1e3 + 1)
    RMAX = int(1e3 + 1)
    INF = int(2e9 + 1)
)

type Pair struct {
    a, b int
}

var (
    d [QMAX]int
    depth[QMAX][RMAX]int
    queries[QMAX][]Pair
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func solve() int {
    _, m := readInt(), readInt()
    d := readIntArray(m)
    g := readInt()
    r := readInt()
    sort.Ints(d)

    for i := 0; i < QMAX; i++ {
        for j := 0; j < RMAX; j++ {
            depth[i][j] = INF
        }
    }
    depth[0][g] = 0
    cnt := 1
    queries[0] = append(queries[0], Pair{0, g})

    for ; cnt > 0; {
        for index := 0; index < QMAX; index++ {
            for _, pair := range queries[index] {
                w := pair.a
                v := pair.b
                cnt--

                i := v / (g + 1)
                rem := v % (g + 1)

                if depth[i][r] < w { continue }

                for j := i - 1; j < i + 2; j += 2 {
                    if j < 0 || j >= m { continue }

                    dist := d[i] - d[j]
                    if dist < 0 { dist = -dist }

                    if dist > rem { continue }

                    nxt := rem - dist
                    w := rem - nxt
                    if nxt == 0 && j + 1 != m { w += r }

                    if nxt == 0 { nxt = g }

                    if depth[j][nxt] > depth[i][rem] + w {
                        depth[j][nxt] = depth[i][rem] + w
                        if j + 1 == m { return depth[j][nxt] }
                        queries[(index + w) % QMAX] = append(queries[(index + w) % QMAX], Pair{depth[j][nxt], j * (g + 1) + nxt})
                        cnt++
                    }
                }
            }
            queries[index] = []Pair{}
        }
    }
    return -1
}

func readInt() int {
    var x int
    Fscan(in, &x)
    return x
}

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

func readString() string {
    var x string
    Fscan(in, &x)
    return x
}

func readLong() int64 {
    var x int64
    Fscan(in, &x)
    return x
}

func main() {
    defer out.Flush()
    Fprintln(out, solve())
}

package main

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

const (
    QMAX = int(1e4 + 1e3 + 1)
    RMAX = int(1e3 + 1)
    INF = int(1e9)
)

type Pair struct {
    a, b int
}

var (
    d [QMAX]int
    depth[QMAX][RMAX]int
    queries[QMAX][]Pair
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func solve() int {
    m := readInt()
    m = readInt()
    d := readIntArray(m)
    g := readInt()
    r := readInt()
    sort.Ints(d)

    for i := 0; i < QMAX; i++ {
        for j := 0; j < RMAX; j++ {
            depth[i][j] = INF
        }
    }
    depth[0][g] = 0
    cnt := 1
    queries[0] = append(queries[0], Pair{0, g})

    for ; cnt > 0; {
        for index := 0; index < QMAX; index++ {
            for _, pair := range queries[index] {
                w := pair.a
                v := pair.b
                cnt--

                i := v / (g + 1)
                rem := v % (g + 1)

                if depth[i][r] < w { continue }

                for j := i - 1; j < i + 2; j += 2 {
                    if j < 0 || j >= m { continue }

                    dist := d[i] - d[j]
                    if dist < 0 { dist = -dist }

                    if dist > rem { continue }

                    nxt := rem - dist
                    w := rem - nxt
                    if nxt == 0 && j + 1 != m { w += r }

                    if nxt == 0 { nxt = g }

                    if depth[j][nxt] > depth[i][rem] + w {
                        depth[j][nxt] = depth[i][rem] + w
                        if j + 1 == m { return depth[j][nxt] }
                        queries[(index + w) % QMAX] = append(queries[(index + w) % QMAX], Pair{depth[j][nxt], j * (g + 1) + nxt})
                        cnt++
                    }
                }
            }
            queries[index] = make([]Pair, 0)
        }
    }
    return -1
}

func readInt() int {
    var x int
    Fscan(in, &x)
    return x
}

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

func readString() string {
    var x string
    Fscan(in, &x)
    return x
}

func readLong() int64 {
    var x int64
    Fscan(in, &x)
    return x
}

func main() {
    defer out.Flush()
    Fprint(out, solve())
}

package main

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

const (
    QMAX = int(1e4 + 2e3 + 1)
    RMAX = int(1e3 + 1)
    INF = int(1e9 + 1)
)

type Pair struct {
    a, b int
}

var (
    d [QMAX]int
    depth[QMAX][RMAX]int
    queries[QMAX][]Pair
)

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func solve() int {
    _, m := readInt(), readInt()
    d := readIntArray(m)
    g := readInt()
    r := readInt()
    sort.Ints(d)

    for i := 0; i < QMAX; i++ {
        for j := 0; j < RMAX; j++ {
            depth[i][j] = INF
        }
    }
    depth[0][g] = 0

    cnt := 1
    queries[0] = append(queries[0], Pair{0, g})

    for ; cnt > 0; {
        for index := 0; index < QMAX; index++ {
            for query := 0; query < len(queries[index]); query++ {
                w := queries[index][query].a
                v := queries[index][query].b
                cnt--

                i := v / (g + 1)
                rem := v % (g + 1)

                if depth[i][r] < w { continue }

                for j := i - 1; j < i + 2; j += 2 {
                    if j < 0 || j >= m { continue }

                    dist := d[i] - d[j]
                    if dist < 0 { dist = -dist }

                    if dist > rem { continue }

                    nxt := rem - dist
                    w := rem - nxt
                    if nxt == 0 && j + 1 != m { w += r }

                    if nxt == 0 { nxt = g }

                    if depth[j][nxt] > depth[i][rem] + w {
                        depth[j][nxt] = depth[i][rem] + w
                        if j + 1 == m { return depth[j][nxt] }
                        queries[(index + w) % QMAX] = append(queries[(index + w) % QMAX], Pair{depth[j][nxt], j * (g + 1) + nxt})
                        cnt++
                    }
                }
            }
            queries[index] = []Pair{}
        }
    }
    return -1
}

func readInt() int {
    var x int
    Fscan(in, &x)
    return x
}

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

func readString() string {
    var x string
    Fscan(in, &x)
    return x
}

func readLong() int64 {
    var x int64
    Fscan(in, &x)
    return x
}

func main() {
    defer out.Flush()
    Fprintln(out, solve())
}


Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:  The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).  No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).  All elements of the sequence are good integers. Find the length of the longest good sequence.

The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).

Print a single integer — the length of the longest good sequence.

NoteIn the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF264B(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	const mx = 1e5 + 1
	ds := [mx][]int{1: {1}}
	for i := 2; i < mx; i++ {
		for j := i; j < mx; j += i {
			ds[j] = append(ds[j], i)
		}
	}

	var n, v, ans int
	dp := [mx]int{}
	for Fscan(in, &n); n > 0; n-- {
		Fscan(in, &v)
		max := 0
		for _, d := range ds[v] {
			if dp[d] > max {
				max = dp[d]
			}
		}
		max++
		for _, d := range ds[v] {
			dp[d] = max
		}
		if max > ans {
			ans = max
		}
	}
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol264B(reader io.Reader, writer io.Writer) {
	maxs := func(vals ...int) int {
		ans := vals[0]
		for _, val := range vals[1:] {
			if val > ans {
				ans = val
			}
		}
		return ans
	}
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	a := make([]int, n)
	const m int = 1e5
	idx := make([]int, m+1)
	for i := range idx {
		idx[i] = -1
	}
	for i := range a {
		Fscan(in, &a[i])
		idx[a[i]] = i
	}

	dp := make([]int, n)
	isPrime := make([]bool, m+1)
	for i := range isPrime {
		isPrime[i] = true
	}
	for i := 2; i <= m; i++ {
		if isPrime[i] {
			cnt := 0
			if idx[i] != -1 {
				dp[idx[i]] = 1
				cnt = 1
			}
			for j := 2 * i; j <= m; j += i {
				isPrime[j] = false
				if idx[j] != -1 {
					dp[idx[j]] = maxs(dp[idx[j]], cnt+1)
					cnt = dp[idx[j]]
				}
			}
		}
	}
	Fprint(out, maxs(dp...))
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol264B(reader io.Reader, writer io.Writer) {
	maxs := func(vals ...int) int {
		ans := vals[0]
		for _, val := range vals[1:] {
			if val > ans {
				ans = val
			}
		}
		return ans
	}
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	if n == 1 {
		Fprint(out, 1)
		return
	}
	a := make([]int, n)
	const m int = 1e5
	idx := make([]int, m+1)
	for i := range idx {
		idx[i] = -1
	}
	for i := range a {
		Fscan(in, &a[i])
		idx[a[i]] = i
	}

	dp := make([]int, n)
	isPrime := make([]bool, m+1)
	for i := range isPrime {
		isPrime[i] = true
	}
	for i := 2; i <= m; i++ {
		if isPrime[i] {
			cnt := 0
			if idx[i] != -1 {
				dp[idx[i]] = 1
				cnt = 1
			}
			for j := 2 * i; j <= m; j += i {
				isPrime[j] = false
				if idj := idx[j]; idj != -1 {
					dp[idj] = maxs(dp[idj], cnt+1)
					cnt = dp[idj]
				}
			}
		}
	}
	Fprint(out, maxs(dp...))
}

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


One very important person has a piece of paper in the form of a rectangle a × b.Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi × yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?

The first line contains three integer numbers n, a and b (1 ≤ n, a, b ≤ 100). Each of the next n lines contain two numbers xi, yi (1 ≤ xi, yi ≤ 100).

Print the largest total area that can be occupied by two seals. If you can not select two seals, print 0.

NoteIn the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper.In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area.In the third example there is no such pair of seals that they both can fit on a piece of paper.

package main
import "fmt"

func main(){
	var n, a, b int
	fmt.Scan(&n)
	fmt.Scan(&a)
	fmt.Scan(&b)
	data := make([][]int, n)
	for i := 0; i < n; i++{
		data[i] = make([]int, 2)
		for j := 0; j < 2; j++{
			fmt.Scan(&data[i][j])
		}
	}
	re := 0
	for i := 0; i < n; i++{
		if data[i][0] <= a && data[i][1] <= b {
			h, w:= data[i][0], data[i][1]

			for j := i + 1; j < n; j++{
				if data[j][0] <= a && w + data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if data[j][1] <= a && w + data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][0] <= a && data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][1] <= a && data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}
			}
		}
		if data[i][0] <= b && data[i][1] <= a {
			h, w:= data[i][1], data[i][0]

			for j := i + 1; j < n; j++{
				if data[j][0] <= a && w + data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if data[j][1] <= a && w + data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][0] <= a && data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][1] <= a && data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}
			}
		}
	}
	fmt.Println(re)
}

package main

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

func Init() {
}

func Solve(io *FastIO) {
	N := io.NextInt()
	A := io.NextInt()
	B := io.NextInt()

	maxSize := 0
	seals := make([]*Seal, N)
	for i := 0; i < N; i++ {
		X := io.NextInt()
		Y := io.NextInt()

		seals[i] = NewSeal(X, Y)

		for j := 0; j < i; j++ {
			if GetFit(A, B, seals[i], seals[j]) {
				maxSize = Max(maxSize, seals[i].Area() + seals[j].Area())
			}
		}
	}
	io.Println(maxSize)
}

func GetFit(A, B int, s1, s2 *Seal) bool {
	sealPairs := [][]*Seal{
		[]*Seal{s1, s2},
		[]*Seal{s1, s2.Rotated()},
		[]*Seal{s1.Rotated(), s2},
		[]*Seal{s1.Rotated(), s2.Rotated()},
	}
	for _, sp := range sealPairs {
		if (sp[0].X + sp[1].X <= A && Max(sp[0].Y, sp[1].Y) <= B) || (Max(sp[0].X, sp[1].X) <= A && sp[0].Y + sp[1].Y <= B) {
			return true
		}
	}
	return false
}

type Seal struct {
	X int
	Y int
}

func NewSeal(x, y int) *Seal {
	return &Seal{
		X: x,
		Y: y,
	}
}

func (s *Seal) Rotated() *Seal {
	return NewSeal(s.Y, s.X)
}

func (s *Seal) Area() int {
	return s.X * s.Y
}

func Max(args ...int) int {
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

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

func main(){
	var n, a, b int
	fmt.Scan(&n)
	fmt.Scan(&a)
	fmt.Scan(&b)
	data := make([][]int, n)
	for i := 0; i < n; i++{
		data[i] = make([]int, 2)
		for j := 0; j < 2; j++{
			fmt.Scan(&data[i][j])
		}
	}
	re := 0
	for i := 0; i < n; i++{
		if data[i][0] <= a && data[i][1] <= b {
			h, w:= data[i][0], data[i][1]
			if re < h*w{
				re = h*w
			}
			for j := i + 1; j < n; j++{
				if h + data[j][0] <= a && w + data[j][1] <= b{
					x, y := h + data[j][0], w + data[j][1]
					if re < x*y{
						re = x * y
					}
				}else if h + data[j][1] <= a && w + data[j][0] <= b{
					x, y := h + data[j][1], w + data[j][0]
					if re < x*y{
						re = x * y
					}
				}
			}
		}
		if data[i][0] <= b && data[i][1] <= a {
			h, w:= data[i][1], data[i][0]
			if re < h*w{
				re = h*w
			}
			for j := i + 1; j < n; j++{
				if h + data[j][0] <= a && w + data[j][1] <= b{
					x, y := h + data[j][0], w + data[j][1]
					if re < x*y{
						re = x * y
					}
				}else if h + data[j][1] <= a && w + data[j][0] <= b{
					x, y := h + data[j][1], w + data[j][0]
					if re < x*y{
						re = x * y
					}
				}
			}
		}
	}
	fmt.Println(re)
}

package main
import "fmt"

func main(){
	var n, a, b int
	fmt.Scan(&n)
	fmt.Scan(&a)
	fmt.Scan(&b)
	data := make([][]int, n)
	for i := 0; i < n; i++{
		data[i] = make([]int, 2)
		for j := 0; j < 2; j++{
			fmt.Scan(&data[i][j])
		}
	}
	re := 0
	for i := 0; i < n; i++{
		if data[i][0] <= a && data[i][1] <= b {
			h, w:= data[i][0], data[i][1]
			if re < h*w{
				re = h*w
			}
			for j := i + 1; j < n; j++{
				if data[i][0] <= a && w + data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if data[j][1] <= a && w + data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][0] <= a && data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][1] <= a && data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}
			}
		}
		if data[i][0] <= b && data[i][1] <= a {
			h, w:= data[i][1], data[i][0]
			if re < h*w{
				re = h*w
			}
			for j := i + 1; j < n; j++{
				if data[i][0] <= a && w + data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if data[j][1] <= a && w + data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][0] <= a && data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][1] <= a && data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}
			}
		}
	}
	fmt.Println(re)
}

package main
import "fmt"

func main(){
	var n, a, b int
	fmt.Scan(&n)
	fmt.Scan(&a)
	fmt.Scan(&b)
	data := make([][]int, n)
	for i := 0; i < n; i++{
		data[i] = make([]int, 2)
		for j := 0; j < 2; j++{
			fmt.Scan(&data[i][j])
		}
	}
	re := 0
	for i := 0; i < n; i++{
		if data[i][0] <= a && data[i][1] <= b {
			h, w:= data[i][0], data[i][1]

			for j := i + 1; j < n; j++{
				if data[i][0] <= a && w + data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if data[j][1] <= a && w + data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][0] <= a && data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][1] <= a && data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}
			}
		}
		if data[i][0] <= b && data[i][1] <= a {
			h, w:= data[i][1], data[i][0]

			for j := i + 1; j < n; j++{
				if data[i][0] <= a && w + data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if data[j][1] <= a && w + data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][0] <= a && data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[j][1] <= a && data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}
			}
		}
	}
	fmt.Println(re)
}

package main
import "fmt"

func main(){
	var n, a, b int
	fmt.Scan(&n)
	fmt.Scan(&a)
	fmt.Scan(&b)
	data := make([][]int, n)
	for i := 0; i < n; i++{
		data[i] = make([]int, 2)
		for j := 0; j < 2; j++{
			fmt.Scan(&data[i][j])
		}
	}
	re := 0
	for i := 0; i < n; i++{
		if data[i][0] <= a && data[i][1] <= b {
			h, w:= data[i][0], data[i][1]
			if re < h*w{
				re = h*w
			}
			for j := i + 1; j < n; j++{
				if data[i][0] <= a && w + data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if data[j][1] <= a && w + data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[i][0] <= a && data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[i][1] <= a && data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}
			}
		}
		if data[i][0] <= b && data[i][1] <= a {
			h, w:= data[i][1], data[i][0]
			if re < h*w{
				re = h*w
			}
			for j := i + 1; j < n; j++{
				if data[i][0] <= a && w + data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if data[j][1] <= a && w + data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[i][0] <= a && data[j][1] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}else if h + data[i][1] <= a && data[j][0] <= b{
					tmp := h*w + data[j][0]*data[j][1]
					if re < tmp{
						re = tmp
					}
				}
			}
		}
	}
	fmt.Println(re)
}


Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that.  Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then:  at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$);  at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$);  the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.

For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.

NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.

package main

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

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 solve() {
	n := 0
	scanf("%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n-1; i++ {
		scanf("%d ", &a[i])
	}
	scanf("%d\n", &a[n-1])
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i+1 {
			printf("%d\n", i + 2)
			return
		}
	}
	printf("1\n")
}

func main() {
	defer writer.Flush()
	t := 0
	scanf("%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import (
	"fmt"
	"sort"
)

func scanInt(n int) []int {
	input := make([]int, n)
	buffer := make([]interface{}, n)

	for i := 0; i < n; i++ {
		buffer[i] = &input[i]
	}

	fmt.Scanln(buffer...)

	return input
}

func solve() {
	n := scanInt(1)[0]
	a := scanInt(n)
	// fmt.Println(n, a)
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i+1 {
			fmt.Println(i + 2)
			return
		}
		// fmt.Print(i, " ")
	}
	fmt.Println("1")
}

func main() {
	t := scanInt(1)[0]
	// fmt.Println(t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import (
	"fmt"
	"sort"
)

func main(){
	var T int
	fmt.Scan(&T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Scan(&n)
		A := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Scan(&A[i])
		}
		sort.Ints(A)
		for n > 0 {
			g := A[n-1]
			if g > n {
				n--
			} else {
				break
			}
		}
		fmt.Println(n+1)
	}
}

package main

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

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 {
	Int64() int64
	UInt64() uint64
	String() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) Int64() 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) UInt64() uint64 {
	impl.Scan()
	bb := impl.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

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

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

const (
	INF = math.MaxInt64
	MOD = 1e9 + 7
)

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

func main() {
	defer writer.Flush()
	t := reader.Int64()
	for ; t > 0; t-- {
		n := reader.Int64()
		a := make([]int64, n)
		for i := range a {
			a[i] = reader.Int64()
		}
		writer.Printf("%d\n", sol(a))
	}
}

func sol(a []int64) int64 {
	sort.Slice(a, func(x, b int) bool {
		return a[x] < a[b]
	})
	for i := len(a)-1; i >= 0; i-- {
		if int64(i) + 1 >= a[i] {
			return int64(i) + 1 + 1
		}
	}
	return 1
}

package main

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

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

	tc := readNum(reader)

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

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(N int, A []int) int {
	sort.Ints(A)

	var res int = 1

	for i := 1; i <= N; i++ {
		if A[i-1] <= i {
			res = i + 1
		}
	}

	return res
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	fmt.Fscanf(in, "%d\n", &t)
	for tt := int64(0); tt < t; tt++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &a[i])
		}
		fmt.Fscanf(in, "\n")
		sort.Ints(a)
		ans := 1
		for i := 0; i < n; i++ {
			if a[i] <= i+1 {
				ans = i + 2
			}
		}
		fmt.Fprintf(out, "%d\n", ans)
	}
	return
}

package main

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

func main() {
	s := NewScanner()
	t := s.NextInt()

Next:
	for i := 0; i < t; i++ {
		n := s.NextInt()
		arr := make([]int, n)
		for j := 0; j < n; j++ {
			arr[j] = s.NextInt()
		}

		sort.Ints(arr)
		for j := n - 1; j >= 0; j-- {
			if arr[j] <= j+1 {
				fmt.Println(j + 2)
				continue Next
			}
		}

		fmt.Println(1)
	}
}

type scanner struct {
	*bufio.Scanner
}

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

func (s *scanner) NextInt() int {
	s.Scan()
	i, _ := strconv.Atoi(s.Text())
	return i
}

func (s *scanner) NextInt64() int64 {
	s.Scan()
	i, _ := strconv.ParseInt(s.Text(), 10, 64)
	return i
}

func (s *scanner) NextString() string {
	s.Scan()
	return s.Text()
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var t int
	var n, a, ans, stock, prev int32
	fmt.Scanf("%d\n", &t)

	for i := 0; i < t; i++ {
		fmt.Scanf("%d\n", &n)

		arr := make([]int32, n)

		for j := int32(0); j < n; j++ {
			fmt.Scanf("%d", &a)
			// if a > n {
			// 	continue
			// }
			arr[j] = a
		}
		sort.Slice(arr, func(i int, j int) bool { return arr[i] < arr[j] })
		// fmt.Println(arr)
		ans = 1

		stock = 0
		prev = 1
		for j := int32(0); j < n; j++ {
			if arr[j] > n {
				break
			}

			if prev != arr[j] {
				if stock+ans-1 >= prev {
					ans += stock
					stock = 0
				}
				prev = arr[j]
			}
			stock++
			// fmt.Println(j, arr[j], stock, ans)
		}
		if stock+ans-1 >= prev {
			ans += stock
			stock = 0
		}
		fmt.Println(ans)
		fmt.Scanf("\n")
	}
}

/*
URL:
https://codeforces.com/contest/1358/problem/B
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	t int
	n int
	A []int
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n = ReadInt()
		A = ReadIntSlice(n)
		solve(n, A)
	}
}

func solve(n int, A []int) {
	sort.Sort(sort.IntSlice(A))

	ans := 0
	for i := 0; i < n; i++ {
		if A[i] <= i+1 {
			ChMax(&ans, i+1)
		}
	}

	fmt.Println(ans + 1)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

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

	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		sort.Ints(a)
		ans := 1
		for i, v := range a {
			if v-1 <= i {
				ans = i + 2
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

func main() {
	defer out.Flush()
	for t := ScanInt(); t > 0; t-- {
		P(solve())
	}
}

type str struct {
	idx   int64
	count int64
}

func solve() int64 {
	n := ScanInt()
	a := ScanInt64s(n)
	sort.Slice(a, func(i, j int) bool {
		return a[i] < a[j]
	})

	for i := int64(n - 1); i >= 0; i-- {
		if a[i] <= i+1 {
			return i + 2
		}
	}
	return int64(1)
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	print("\n", nil)
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case []int:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.Itoa(v[i]) + " ")
			}
			str = sb.String()
		case int64:
			str = strconv.FormatInt(v, 10)
		case []int64:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.FormatInt(v[i], 10) + " ")
			}
			str = sb.String()
		case string:
			str = v
		default:
			panic("invalid print arg: " + fmt.Sprintf("%v", arg))

		}
		out.WriteString(str + seperator)
	}
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanWords(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanInt() int { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt()
	}
	return a
}
func ScanInt64() int64 { i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i }
func ScanInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt64()
	}
	return a
}

/*********************** Utils int64 ***********************/
func MnMx64(args ...int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn64(args ...int64) int64 { mn, _ := MnMx64(args...); return mn }
func Mx64(args ...int64) int64 { _, mx := MnMx64(args...); return mx }
func LCM64(a, b int64) int64   { return a / GCD64(a, b) * b }
func GCD64(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD64(b%a, a)
}
func SortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func Abs64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

/*********************** Utils int ***********************/
func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

func min(a, b int) int {
	return int(math.Min(float64(a), float64(b)))
}

func max(a, b int) int {
	return int(math.Max(float64(a), float64(b)))
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscanf(in, "%v\n", &t)
	for now := 0; now < t; now++ {
		var n int
		fmt.Fscanf(in, "%v\n", &n)
		mas := make([]int, n + 1)
		for i := 0;i < n;i++ {
			fmt.Fscan(in, &mas[i])
		}
		mas[n] = 1
		fmt.Fscanf(in, "\n")
		sort.Ints(mas)
		var ans int = 1
		for i := n;i >= 0;i-- {
			if mas[i] <= i {
				ans = i + 1
				break
			}
		}
		fmt.Fprintln(out, ans)

	}
	return
}

package main

import "fmt"
import "sort"

func solve() {
	n := 0
	fmt.Scanf("%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n-1; i++ {
		fmt.Scanf("%d", &a[i])
	}
	fmt.Scanf("%d\n", &a[n-1])
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i + 1 {
			fmt.Println(i + 2)
			return
		}
	}
	fmt.Println(1)
}

func main() {
	t := 0
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import (
	"fmt"
	"sort"
)

func scanInt(n int) []int {
	input := make([]int, n)
	buffer := make([]interface{}, n)

	for i := 0; i < n; i++ {
		buffer[i] = &input[i]
	}

	fmt.Scanln(buffer...)

	return input
}

func solve() {
	n := scanInt(1)[0]
	a := scanInt(n)
	fmt.Println(n, a)
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i+1 {
			fmt.Println(i + 2)
			return
		}
		fmt.Print(i, " ")
	}
	println("1")
}

func main() {
	t := scanInt(1)[0]
	fmt.Println(t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import (
	"fmt"
	"sort"
)

func scanInt(n int) []int {
	input := make([]int, n)
	buffer := make([]interface{}, n)

	for i := 0; i < n; i++ {
		buffer[i] = &input[i]
	}

	fmt.Scanln(buffer...)

	return input
}

func solve() {
	n := scanInt(1)[0]
	a := scanInt(n)
	fmt.Println(n, a)
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i+1 {
			fmt.Println(i + 2)
			return
		}
		fmt.Print(i, " ")
	}
	println(1)
}

func main() {
	t := scanInt(1)[0]
	fmt.Println(t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import "fmt"
import "sort"

func solve() {
	n := 0
	fmt.Scanf("%d\n", &n)
	a := make([]int, n)
	for i := range a {
		fmt.Scanf("%d", &a[i])
	}
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i + 1 {
			fmt.Println(i + 2)
			return
		}
	}
	println(1)
}

func main() {
	t := 0
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import "fmt"
import "sort"

func solve() {
	n := 0
	fmt.Scanf("%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d ", &a[i])
	}
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i + 1 {
			fmt.Println(i + 2)
			return
		}
	}
	println(1)
}

func main() {
	t := 0
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import "fmt"
import "sort"

func solve() {
	n := 0
	fmt.Scanf("%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n-1; i++ {
		fmt.Scanf("%d ", &a[i])
	}
	fmt.Scanf("%d\n", &a[n-1])
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i + 1 {
			fmt.Println(i + 2)
			return
		}
	}
	println(1)
}

func main() {
	t := 0
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}

package main

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

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 solve() {
	n := 0
	scanf("%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &a[i])
	}
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i+1 {
			printf("%d\n", i + 2)
			return
		}
	}
	printf("1\n")
}

func main() {
	defer writer.Flush()
	t := 0
	scanf("%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import "fmt"
import "sort"

func solve() {
	n := 0
	fmt.Scanf("%d\n", &n)
	a := make([]int, n)
	for i := range a {
		fmt.Scanf("%d ", &a[i])
	}
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i + 1 {
			fmt.Println(i + 2)
			return
		}
	}
	println(1)
}

func main() {
	t := 0
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import (
	"fmt"
	"sort"
)

func scanInt(n int) []int {
	input := make([]int, n)
	buffer := make([]interface{}, n)

	for i := 0; i < n; i++ {
		buffer[i] = &input[i]
	}

	fmt.Scanln(buffer...)

	return input
}

func solve() {
	n := scanInt(1)[0]
	a := scanInt(n)
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i+1 {
			fmt.Println(i + 2)
			return
		}
	}
	println(1)
}

func main() {
	t := scanInt(1)[0]
	for t > 0 {
		solve()
		t--
	}
}

package main

import (
	"fmt"
	"sort"
)

func scanInt(n int) []int {
	input := make([]int, n)
	buffer := make([]interface{}, n)

	for i := 0; i < n; i++ {
		buffer[i] = &input[i]
	}

	fmt.Scanln(buffer...)

	return input
}

func solve() {
	n := 0
	fmt.Scanln(&n)
	a := scanInt(n)
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i+1 {
			fmt.Println(i + 2)
			return
		}
	}
	println(1)
}

func main() {
	t := 0
	fmt.Scanln(&t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import "fmt"
import "sort"

func solve() {
	n := 0
	fmt.Scanf("%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n-1; i++ {
		fmt.Scanf("%d", &a[i])
	}
	fmt.Scanf("%d\n", &a[n-1])
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i + 1 {
			fmt.Println(i + 2)
			return
		}
	}
	println(1)
}

func main() {
	t := 0
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}

package main

import (
	"fmt"
	"sort"
)

func scanInt(n int) []int {
	input := make([]int, n)
	buffer := make([]interface{}, n)

	for i := 0; i < n; i++ {
		buffer[i] = &input[i]
	}

	fmt.Scanln(buffer...)

	return input
}

func solve() {
	n := scanInt(1)[0]
	a := scanInt(n)
	fmt.Println(n, a)
	sort.Ints(a)
	for i := n - 1; i >= 0; i-- {
		if a[i] <= i+1 {
			fmt.Println(i + 2)
			return
		}
	}
	println(1)
}

func main() {
	t := scanInt(1)[0]
	fmt.Println(t)
	for t > 0 {
		solve()
		t--
	}
}


You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this:   You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you;  You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;  You choose the number $$$s$$$ of steps;  You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above.  The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps.   You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where:   "A" means that the dominant religion is Beingawesomeism;  "P" means that the dominant religion is Pushingittoofarism.  It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.

For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.

4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP

NoteIn the first test case, it can be done in two usages, as follows:Usage 1:  Usage 2:  In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

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

var t int
var r, c int
var S [][]rune

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		r, c = ReadInt2()
		S = [][]rune{}
		for i := 0; i < r; i++ {
			row := ReadRuneSlice()
			S = append(S, row)
		}

		solve()
	}
}

func solve() {
	anum := 0
	for i := 0; i < r; i++ {
		for j := 0; j < c; j++ {
			if S[i][j] == 'A' {
				anum++
			}
		}
	}
	if anum == 0 {
		fmt.Println("MORTAL")
		return
	}
	if anum == r*c {
		fmt.Println(0)
		return
	}

	if subRow(0) || subRow(r-1) || subCol(0) || subCol(c-1) {
		fmt.Println(1)
		return
	}

	b := false
	for i := 1; i < r-1; i++ {
		b = b || subRow(i)
	}
	for i := 1; i < c-1; i++ {
		b = b || subCol(i)
	}
	if b {
		fmt.Println(2)
		return
	}
	if S[0][0] == 'A' || S[0][c-1] == 'A' || S[r-1][0] == 'A' || S[r-1][c-1] == 'A' {
		fmt.Println(2)
		return
	}

	b = false
	for i := 1; i < c-1; i++ {
		b = b || (S[0][i] == 'A')
		b = b || (S[r-1][i] == 'A')
	}
	for i := 1; i < r-1; i++ {
		b = b || (S[i][0] == 'A')
		b = b || (S[i][c-1] == 'A')
	}
	if b {
		fmt.Println(3)
		return
	}

	fmt.Println(4)
}

func subRow(rowId int) bool {
	for i := 0; i < c; i++ {
		if S[rowId][i] != 'A' {
			return false
		}
	}
	return true
}

func subCol(colId int) bool {
	for i := 0; i < r; i++ {
		if S[i][colId] != 'A' {
			return false
		}
	}
	return true
}

/*
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
- いきなりオーバーフローはしていませんか？
*/

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