package main

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

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

const (
	//MaxScanTokenSize = 64 * 1024 // package default
	MaxScanTokenSize = 8 * 1024 * 1024 // 8M
)

func init() {
	scanner.Buffer(make([]byte, 0, MaxScanTokenSize), MaxScanTokenSize)
	scanner.Split(bufio.ScanWords)
}

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

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

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

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

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

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

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

type Edge struct {
	From int
	To   int
	Dist int
	Cap  int
	Flow int
}

type Graph struct {
	NNode int
	NEdge int
	Edges []Edge
	Nodes [][]int
}

func NewGraph(nNode, nEdge int) *Graph {
	g := &Graph{
		NNode: nNode,
		NEdge: nEdge,
		Edges: make([]Edge, 0, nEdge),
		Nodes: make([][]int, nNode, nNode),
	}
	return g
}

func (g *Graph) AddEdge(from, to, dist, cap, flow int) {
	g.Nodes[from] = append(g.Nodes[from], len(g.Edges))
	g.Edges = append(g.Edges, Edge{from, to, dist, cap, flow})
	g.Nodes[to] = append(g.Nodes[to], len(g.Edges))
	g.Edges = append(g.Edges, Edge{to, from, dist, cap, flow})
}

func (g *Graph) Show() {
	fmt.Printf("n node = %d, n edge = %d\n", g.NNode, g.NEdge)
	for i, cur := range g.Nodes {
		fmt.Printf("[%d]", i)
		for _, next := range cur {
			fmt.Printf(" %d", g.Edges[next].To)
		}
		fmt.Println()
	}
}

type QueueStack struct {
	data []interface{}
}

func (q *QueueStack) size() int {
	return len(q.data)
}

func (q *QueueStack) push(v interface{}) {
	q.data = append(q.data, v)
}

func (q *QueueStack) popFront() interface{} {
	v := q.data[0]
	q.data = q.data[1:]
	return v
}

func (q *QueueStack) pop() interface{} {
	last := len(q.data) - 1
	v := q.data[last]
	q.data = q.data[:last]
	return v
}

var arrival [][]int

func findNextTiming(at, earlist int) int {
	a := arrival[at]
	i := sort.Search(len(a), func(i int) bool {
		return a[i] >= earlist
	})
	for i < len(a) && a[i] == earlist {
		i++
		earlist++
	}
	return earlist
}

func Spfa(g *Graph, from, to int) int {
	n := g.NNode
	dist := make([]int, n, n)
	inQueue := make([]bool, n, n)
	dist[0] = 0
	for i := 1; i < n; i++ {
		dist[i] = -1
	}

	q := &QueueStack{}
	q.push(from)
	inQueue[from] = true
	for q.size() > 0 {
		cur := q.pop().(int)
		inQueue[cur] = false

		nextStart := findNextTiming(cur, dist[cur])
		for _, ie := range g.Nodes[cur] {
			e := g.Edges[ie]
			fromCur := nextStart + e.Dist
			if dist[e.To] == -1 || fromCur < dist[e.To] {
				dist[e.To] = fromCur
				if !inQueue[e.To] {
					q.push(e.To)
					inQueue[e.To] = true
				}
			}
		}
	}

	return dist[to]
}

type PQType struct {
	node int
	dist int
}

type PriorityQueue []PQType

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

func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].dist < pq[j].dist
}

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

func (pq *PriorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.(PQType))
}

func (pq *PriorityQueue) Pop() interface{} {
	last := len(*pq) - 1
	old := *pq
	x := old[last]
	*pq = old[:last]
	return x
}

func (pq PriorityQueue) Show() {
	for _, x := range pq {
		fmt.Printf("%v <<< ", x)
	}
	fmt.Println()
}

func Dijkstra(g *Graph, from, to int) int {
	n := g.NNode
	done := make([]bool, n, n)

	pq := make(PriorityQueue, 0)
	heap.Push(&pq, PQType{from, 0})

	ans := -1
	for pq.Len() > 0 {
		x := heap.Pop(&pq).(PQType)
		if done[x.node] {
			continue
		}
		done[x.node] = true
		if x.node ==  to {
			ans = x.dist
			//break
		}
		nextStart := findNextTiming(x.node, x.dist)
		for _, ie := range g.Nodes[x.node] {
			e := g.Edges[ie]
			if !done[e.To] {
				x = PQType{e.To, e.Dist + nextStart}
				heap.Push(&pq, x)
			}
		}
	}

	return ans
}

func main() {
	defer writer.Flush()

	n, m := readInt(), readInt()
	g := NewGraph(n, m)

	for i := 0; i < m; i++ {
		x, y, d := readInt(), readInt(), readInt()
		g.AddEdge(x - 1, y - 1, d, 0, 0)
	}

	arrival = make([][]int, n, n)
	for i := 0; i < n; i++ {
		nArrival := readInt()
		arrival[i] = make([]int, nArrival, nArrival)
		for j := 0; j < nArrival; j++ {
			arrival[i][j] = readInt()
		}
	}

	//ans := Spfa(g, 0, n - 1)
	ans := Dijkstra(g, 0, n - 1)
	fmt.Fprintf(writer, "%d\n", ans)
}

package main

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

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

const (
	//MaxScanTokenSize = 64 * 1024 // package default
	MaxScanTokenSize = 8 * 1024 * 1024 // 8M
)

func init() {
	scanner.Buffer(make([]byte, 0, MaxScanTokenSize), MaxScanTokenSize)
	scanner.Split(bufio.ScanWords)
}

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

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

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

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

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

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

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

type Edge struct {
	From int
	To   int
	Dist int
	Cap  int
	Flow int
}

type Graph struct {
	NNode int
	NEdge int
	Edges []Edge
	Nodes [][]int
}

func NewGraph(nNode, nEdge int) *Graph {
	g := &Graph{
		NNode: nNode,
		NEdge: nEdge,
		Edges: make([]Edge, 0, nEdge),
		Nodes: make([][]int, nNode, nNode),
	}
	return g
}

func (g *Graph) AddEdge(from, to, dist, cap, flow int) {
	g.Nodes[from] = append(g.Nodes[from], len(g.Edges))
	g.Edges = append(g.Edges, Edge{from, to, dist, cap, flow})
	g.Nodes[to] = append(g.Nodes[to], len(g.Edges))
	g.Edges = append(g.Edges, Edge{to, from, dist, cap, flow})
}

func (g *Graph) Show() {
	fmt.Printf("n node = %d, n edge = %d\n", g.NNode, g.NEdge)
	for i, cur := range g.Nodes {
		fmt.Printf("[%d]", i)
		for _, next := range cur {
			fmt.Printf(" %d", g.Edges[next].To)
		}
		fmt.Println()
	}
}

type QueueStack struct {
	data []interface{}
}

func (q *QueueStack) size() int {
	return len(q.data)
}

func (q *QueueStack) push(v interface{}) {
	q.data = append(q.data, v)
}

func (q *QueueStack) popFront() interface{} {
	v := q.data[0]
	q.data = q.data[1:]
	return v
}

func (q *QueueStack) pop() interface{} {
	last := len(q.data) - 1
	v := q.data[last]
	q.data = q.data[:last]
	return v
}

var arrival [][]int

func findNextTiming(at, earlist int) int {
	a := arrival[at]
	i := sort.Search(len(a), func(i int) bool {
		return a[i] >= earlist
	})
	for i < len(a) && a[i] == earlist {
		i++
		earlist++
	}
	return earlist
}

func Spfa(g *Graph, from, to int) int {
	n := g.NNode
	dist := make([]int, n, n)
	inQueue := make([]bool, n, n)
	dist[0] = 0
	for i := 1; i < n; i++ {
		dist[i] = -1
	}

	q := &QueueStack{}
	q.push(from)
	inQueue[from] = true
	for q.size() > 0 {
		cur := q.pop().(int)
		inQueue[cur] = false

		nextStart := findNextTiming(cur, dist[cur])
		for _, ie := range g.Nodes[cur] {
			e := g.Edges[ie]
			fromCur := nextStart + e.Dist
			if dist[e.To] == -1 || fromCur < dist[e.To] {
				dist[e.To] = fromCur
				if !inQueue[e.To] {
					q.push(e.To)
					inQueue[e.To] = true
				}
			}
		}
	}

	return dist[to]
}

type PQType struct {
	node int
	dist int
}

type PriorityQueue []PQType

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

func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].dist < pq[j].dist
}

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

func (pq *PriorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.(PQType))
}

func (pq *PriorityQueue) Pop() interface{} {
	last := len(*pq) - 1
	old := *pq
	x := old[last]
	*pq = old[:last]
	return x
}

func (pq PriorityQueue) Show() {
	for _, x := range pq {
		fmt.Printf("%v <<< ", x)
	}
	fmt.Println()
}

func Dijkstra(g *Graph, from, to int) int {
	n := g.NNode
	done := make([]bool, n, n)

	pq := make(PriorityQueue, 0)
	heap.Push(&pq, PQType{from, 0})

	ans := -1
	for pq.Len() > 0 {
		x := heap.Pop(&pq).(PQType)
		if done[x.node] {
			continue
		}
		done[x.node] = true
		if x.node ==  to {
			ans = x.dist
			break
		}
		nextStart := findNextTiming(x.node, x.dist)
		for _, ie := range g.Nodes[x.node] {
			e := g.Edges[ie]
			if !done[e.To] {
				x = PQType{e.To, e.Dist + nextStart}
				heap.Push(&pq, x)
			}
		}
	}

	return ans
}

func main() {
	defer writer.Flush()

	n, m := readInt(), readInt()
	g := NewGraph(n, m)

	for i := 0; i < m; i++ {
		x, y, d := readInt(), readInt(), readInt()
		g.AddEdge(x - 1, y - 1, d, 0, 0)
	}

	arrival = make([][]int, n, n)
	for i := 0; i < n; i++ {
		nArrival := readInt()
		arrival[i] = make([]int, nArrival, nArrival)
		for j := 0; j < nArrival; j++ {
			arrival[i][j] = readInt()
		}
	}

	//ans := Spfa(g, 0, n - 1)
	ans := Dijkstra(g, 0, n - 1)
	fmt.Fprintf(writer, "%d\n", ans)
}

package main

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

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

const (
	//MaxScanTokenSize = 64 * 1024 // package default
	MaxScanTokenSize = 8 * 1024 * 1024 // 8M
)

func init() {
	scanner.Buffer(make([]byte, 0, MaxScanTokenSize), MaxScanTokenSize)
	scanner.Split(bufio.ScanWords)
}

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

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

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

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

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

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

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

type Edge struct {
	From int
	To int
	Dist int
	Cap int
	Flow int
}

type Graph struct {
	NNode int
	NEdge int
	Edges []Edge
	Nodes [][]int
}

func NewGraph(nNode, nEdge int) *Graph {
	g := &Graph{
		NNode: nNode,
		NEdge: nEdge,
		Edges: make([]Edge, 0, nEdge),
		Nodes: make([][]int, nNode, nNode),
	}
	return g
}

func (g *Graph) AddEdge(from, to, dist, cap, flow int) {
	g.Nodes[from] = append(g.Nodes[from], len(g.Edges))
	g.Edges = append(g.Edges, Edge{from, to, dist, cap, flow})
	g.Nodes[to] = append(g.Nodes[to], len(g.Edges))
	g.Edges = append(g.Edges, Edge{to, from, dist, cap, flow})
}

func (g *Graph) Show() {
	fmt.Printf("n node = %d, n edge = %d\n", g.NNode, g.NEdge)
	for i, cur := range g.Nodes {
		fmt.Printf("[%d]", i)
		for _, next := range cur {
			fmt.Printf(" %d", g.Edges[next].To)
		}
		fmt.Println()
	}
}

type QueueStack struct {
	data []interface{}
}

func (q *QueueStack) size() int {
	return len(q.data)
}

func (q *QueueStack) push(v interface{}) {
	q.data = append(q.data, v)
}

func (q *QueueStack) popFront() interface{} {
	v := q.data[0]
	q.data = q.data[1:]
	return v
}

func (q *QueueStack) pop() interface{} {
	last := len(q.data) - 1
	v := q.data[last]
	q.data = q.data[:last]
	return v
}

var arrival [][]int

func findNextTiming(to, earlist int) int {
	for _, a := range arrival[to] {
		if a < earlist {
			continue
		} else if a == earlist {
			earlist++
		} else {
			break
		}
	}
	return earlist
}

func Spfa(g *Graph, from, to int) int {
	n := g.NNode
	dist := make([]int, n, n)
	dist[0] = 0
	for i := 1; i < n; i++ {
		dist[i] = -1
	}

	q := &QueueStack{}
	q.push(from)
	for q.size() > 0 {
		cur := q.pop().(int)
		for _, ie := range g.Nodes[cur] {
			e := g.Edges[ie]
			earlist := dist[cur] + e.Dist
			nextTiming := findNextTiming(e.To, earlist)
			if dist[e.To] == -1 || nextTiming < dist[e.To] {
				dist[e.To] = nextTiming
				q.push(e.To)
			}
		}
	}

	return dist[to]
}

func main() {
	defer writer.Flush()

	n, m := readInt(), readInt()
	g := NewGraph(n, m)

	for i := 0; i < m; i++ {
		x, y, d := readInt(), readInt(), readInt()
		g.AddEdge(x - 1, y - 1, d, 0, 0)
	}

	arrival = make([][]int, n, n)
	for i := 0; i < n; i++ {
		nArrival := readInt()
		arrival[i] = make([]int, nArrival, nArrival)
		for j := 0; j < nArrival; j++ {
			arrival[i][j] = readInt()
		}
	}

	ans := Spfa(g, 0, n - 1)
	fmt.Fprintf(writer, "%d\n", ans)
}


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 gi2() (int,int) { return gi(),gi() }
func gi3() (int,int,int) { return gi(),gi(),gi() }
func gi4() (int,int,int,int) { return gi(),gi(),gi(),gi() }
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 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 tern(cond bool, a int, b int) int { if cond { return a }; return b }
func terns(cond bool, a string, b string) string { if cond { return a }; return b }
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 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 vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }

type rbtreemultisetnode struct { left, right, up int32; red bool; key int; count int }
type rbtreemultiset struct {
	lessthan func(a, b int) bool; tree []rbtreemultisetnode; root int32; recycler []int32; sz int; minidx int32
	maxidx int32
}
type rbtreemultisetIterator interface { Next() (ok bool); Prev() (ok bool); Key() int; Count() int }
type rbtreemultisetiter struct { cur int32; key int; count int; rbtree *rbtreemultiset }
func (i *rbtreemultisetiter) Key() int { return i.key }
func (i *rbtreemultisetiter) Count() int { return i.count }
func (i *rbtreemultisetiter) Next() bool {
	rbtree := i.rbtree; v := rbtree.nextidx(i.cur); if v == 0 { return false }
	i.cur, i.key, i.count = v, rbtree.tree[v].key, rbtree.tree[v].count; return true
}
func (i *rbtreemultisetiter) Prev() bool {
	rbtree := i.rbtree; v := rbtree.previdx(i.cur); if v == 0 { return false }
	i.cur, i.key, i.count = v, rbtree.tree[v].key, rbtree.tree[v].count; return true
}
func Newrbtreemultiset(lessthan func(a, b int) bool) *rbtreemultiset {
	q := &rbtreemultiset{lessthan, make([]rbtreemultisetnode, 2), int32(0), make([]int32, 0), 0, 0, 0}
	q.tree[0].left, q.tree[0].right, q.tree[0].up, q.tree[0].red = 0, 0, 0, false; q.recycler = append(q.recycler, 1)
	return q
}
func (q *rbtreemultiset) Add(k int) {
	if q.sz == 0 {
		z := q.getNewNodenum(); tree := q.tree; q.minidx, q.maxidx, q.sz, q.root = z, z, q.sz+1, z
		tree[z].key, tree[z].count, tree[z].up, tree[z].left, tree[z].right, tree[z].red = k, 1, 0, 0, 0, false; return
	}
	y, cmp := q.findInsertionPoint(k); if cmp == 0 { q.tree[y].count++; q.sz += 1; return }; z := q.getNewNodenum()
	q.sz += 1; tree := q.tree
	tree[z].key, tree[z].count, tree[z].up, tree[z].left, tree[z].right, tree[z].red = k, 1, y, 0, 0, true
	if cmp < 0 { tree[y].left = z } else { tree[y].right = z }
	if q.sz == 0 || q.lessthan(k, tree[q.minidx].key) { q.minidx = z }
	if q.sz == 0 || q.lessthan(tree[q.maxidx].key, k) { q.maxidx = z }; var p, g, u int32
	for p = tree[z].up; tree[p].red; p = tree[z].up {
		g = tree[p].up ; if g == 0 { break }
		if p == tree[g].left {
			u = tree[g].right
			if tree[u].red { tree[p].red, tree[u].red, tree[g].red, z = false, false, true, g; continue }
			if z == tree[p].right { z = p; q.rotleft(z); p = tree[z].up }; q.rotright(g)
			tree[g].red, tree[p].red = true, false
		} else {
			u = tree[g].left
			if tree[u].red { tree[p].red, tree[u].red, tree[g].red, z = false, false, true, g; continue }
			if z == tree[p].left { z = p; q.rotright(z); p = tree[z].up }; q.rotleft(g)
			tree[g].red, tree[p].red = true, false
		}
	}
	tree[q.root].red = false
}
func (q *rbtreemultiset) Delete(k int) bool {
	if q.sz == 0 { return false }; z, cmp := q.findInsertionPoint(k)
	if cmp != 0 { return false } else if q.tree[z].count > 1 { q.tree[z].count--; q.sz--; return true }; q.sz--
	q.recycler = append(q.recycler, z)
	if q.sz > 0 && !q.lessthan(q.tree[q.minidx].key, k) { q.minidx = q.nextidx(q.minidx) }
	if q.sz > 0 && !q.lessthan(k, q.tree[q.maxidx].key) { q.maxidx = q.previdx(q.maxidx) }
	if q.sz == 0 { q.root = 0; return true }; tree := q.tree; var x int32; y, y_orig_red := z, tree[z].red
	if tree[z].left == 0 {
		x = tree[z].right; q.rbTransplant(z, x)
	} else if tree[z].right == 0 {
		x = tree[z].left; q.rbTransplant(z, x)
	} else {
		y = q.findminidx(tree[z].right); y_orig_red = tree[y].red; x = tree[y].right
		if tree[y].up == z {
			tree[x].up = y
		} else {
			q.rbTransplant(y, x); tree[y].right = tree[z].right; tree[tree[y].right].up = y
		}
		q.rbTransplant(z, y); tree[y].left = tree[z].left; tree[tree[y].left].up = y; tree[y].red = tree[z].red
	}
	if !y_orig_red {
		for q.root != x && !tree[x].red {
			p := tree[x].up
			if tree[p].left == x {
				s := tree[p].right
				if tree[s].red { tree[s].red = false; tree[p].red = true; q.rotleft(p); s = tree[p].right }
				c := tree[s].left; d := tree[s].right
				if !tree[c].red && !tree[d].red {
					tree[s].red = true; x = p
				} else {
					if !tree[d].red { tree[c].red = false; tree[s].red = true; q.rotright(s); s = tree[p].right }
					tree[s].red = tree[p].red; tree[p].red = false; tree[tree[s].right].red = false; q.rotleft(p)
					x = q.root
				}
			} else {
				s := tree[p].left
				if tree[s].red { tree[s].red = false; tree[p].red = true; q.rotright(p); s = tree[p].left }
				c := tree[s].right; d := tree[s].left
				if !tree[c].red && !tree[d].red {
					tree[s].red = true; x = p
				} else {
					if !tree[d].red { tree[c].red = false; tree[s].red = true; q.rotleft(s); s = tree[p].left }
					tree[s].red = tree[p].red; tree[p].red = false; tree[tree[s].left].red = false; q.rotright(p)
					x = q.root
				}
			}
		}
		tree[x].red = false
	}
	return true
}
func (q *rbtreemultiset) Clear() {
	q.tree, q.root, q.recycler, q.sz = q.tree[:2], 0, q.recycler[:0], 0; q.recycler = append(q.recycler, int32(1))
}
func (q *rbtreemultiset) IsEmpty() bool { return q.sz == 0 }
func (q *rbtreemultiset) Contains(k int) bool { _, cmp := q.findInsertionPoint(k); return cmp == 0 }
func (q *rbtreemultiset) Count(k int) int {
	z, cmp := q.findInsertionPoint(k); if cmp != 0 { return 0 }; return q.tree[z].count
}
func (q *rbtreemultiset) Len() int { return q.sz }
func (q *rbtreemultiset) MinKey() (k int) {
	if q.sz == 0 { panic("Called MinKey on an empty rbtreemultiset") }; return q.tree[q.minidx].key
}
func (q *rbtreemultiset) MaxKey() (k int) {
	if q.sz == 0 { panic("Called MaxKey on an empty rbtreemultiset") }; return q.tree[q.maxidx].key
}
func (q *rbtreemultiset) findLtIdx(k int) (int32, bool) {
	if q.sz == 0 || !q.lessthan(q.tree[q.minidx].key, k) { return 0, false }; idx, pos := q.findInsertionPoint(k)
	if pos != 1 { idx = q.previdx(idx) }; return idx, true
}
func (q *rbtreemultiset) findLeIdx(k int) (int32, bool) {
	if q.sz == 0 || q.lessthan(k, q.tree[q.minidx].key) { return 0, false }; idx, pos := q.findInsertionPoint(k)
	if pos == -1 { idx = q.previdx(idx) }; return idx, true
}
func (q *rbtreemultiset) findGtIdx(k int) (int32, bool) {
	if q.sz == 0 || !q.lessthan(k, q.tree[q.maxidx].key) { return 0, false }; idx, pos := q.findInsertionPoint(k)
	if pos != -1 { idx = q.nextidx(idx) }; return idx, true
}
func (q *rbtreemultiset) findGeIdx(k int) (int32, bool) {
	if q.sz == 0 || q.lessthan(q.tree[q.maxidx].key, k) { return 0, false }; idx, pos := q.findInsertionPoint(k)
	if pos == 1 { idx = q.nextidx(idx) }; return idx, true
}
func (q *rbtreemultiset) FindLt(k int) (int, bool) {
	var ans int; idx, ok := q.findLtIdx(k); if ok { ans = q.tree[idx].key }; return ans, ok
}
func (q *rbtreemultiset) FindLe(k int) (int, bool) {
	var ans int; idx, ok := q.findLeIdx(k); if ok { ans = q.tree[idx].key }; return ans, ok
}
func (q *rbtreemultiset) FindGt(k int) (int, bool) {
	var ans int; idx, ok := q.findGtIdx(k); if ok { ans = q.tree[idx].key }; return ans, ok
}
func (q *rbtreemultiset) FindGe(k int) (int, bool) {
	var ans int; idx, ok := q.findGeIdx(k); if ok { ans = q.tree[idx].key }; return ans, ok
}
func (q *rbtreemultiset) FindLtIter(k int) (rbtreemultisetIterator, bool) {
	var ans *rbtreemultisetiter; idx, ok := q.findLtIdx(k)
	if ok { ans = &rbtreemultisetiter{idx, q.tree[idx].key, q.tree[idx].count, q} }; return ans, ok
}
func (q *rbtreemultiset) FindLeIter(k int) (rbtreemultisetIterator, bool) {
	var ans *rbtreemultisetiter; idx, ok := q.findLeIdx(k)
	if ok { ans = &rbtreemultisetiter{idx, q.tree[idx].key, q.tree[idx].count, q} }; return ans, ok
}
func (q *rbtreemultiset) FindGtIter(k int) (rbtreemultisetIterator, bool) {
	var ans *rbtreemultisetiter; idx, ok := q.findGtIdx(k)
	if ok { ans = &rbtreemultisetiter{idx, q.tree[idx].key, q.tree[idx].count, q} }; return ans, ok
}
func (q *rbtreemultiset) FindGeIter(k int) (rbtreemultisetIterator, bool) {
	var ans *rbtreemultisetiter; idx, ok := q.findGeIdx(k)
	if ok { ans = &rbtreemultisetiter{idx, q.tree[idx].key, q.tree[idx].count, q} }; return ans, ok
}
func (q *rbtreemultiset) FindIter(k int) (rbtreemultisetIterator, bool) {
	if q.sz == 0 { return nil, false }; idx, pos := q.findInsertionPoint(k); if pos != 0 { return nil, false }
	return &rbtreemultisetiter{idx, q.tree[idx].key, q.tree[idx].count, q}, true
}
func (q *rbtreemultiset) MinIter() (rbtreemultisetIterator, bool) {
	if q.sz == 0 { return nil, false }; idx := q.findminidx(q.root)
	return &rbtreemultisetiter{idx, q.tree[idx].key, q.tree[idx].count, q}, true
}
func (q *rbtreemultiset) MaxIter() (rbtreemultisetIterator, bool) {
	if q.sz == 0 { return nil, false }; idx := q.findmaxidx(q.root)
	return &rbtreemultisetiter{idx, q.tree[idx].key, q.tree[idx].count, q}, true
}
func (q *rbtreemultiset) rbTransplant(u, v int32) {
	tree := q.tree
	if tree[u].up == 0 {
		q.root = v
	} else {
		p := tree[u].up; if u == tree[p].left { tree[p].left = v } else { tree[p].right = v }
	}
	tree[v].up = tree[u].up
}
func (q *rbtreemultiset) findInsertionPoint(k int) (int32, int8) {
	n, lt, tree := q.root, q.lessthan, q.tree
	for {
		nkey := tree[n].key
		if lt(nkey, k) {
			r := tree[n].right; if r == 0 { return n, 1 }; n = r
		} else if lt(k, nkey) {
			l := tree[n].left; if l == 0 { return n, -1 }; n = l
		} else {
			return n, 0
		}
	}
}
func (q *rbtreemultiset) findmaxidx(n1 int32) int32 {
	tree := q.tree; for { xx := tree[n1].right; if xx == 0 { break }; n1 = xx }; return n1
}
func (q *rbtreemultiset) findminidx(n1 int32) int32 {
	tree := q.tree; for { xx := tree[n1].left; if xx == 0 { break }; n1 = xx }; return n1
}
func (q *rbtreemultiset) nextidx(cur int32) int32 {
	last := int32(-2); tree := q.tree; rr := tree[cur].right; if rr > 0 { return q.findminidx(rr) }
	for { last, cur = cur, tree[cur].up; if cur == 0 || tree[cur].left == last { break } }; return cur
}
func (q *rbtreemultiset) previdx(cur int32) int32 {
	last := int32(0); tree := q.tree; ll := tree[cur].left; if ll > 0 { return q.findmaxidx(ll) }
	for { last, cur = cur, tree[cur].up; if cur == 0 || tree[cur].right == last { break } }; return cur
}
func (q *rbtreemultiset) rotleft(x int32) {
	tree := q.tree; y := tree[x].right; p := tree[x].up; tree[x].right = tree[y].left
	if tree[y].left != 0 { tree[tree[y].left].up = x }; tree[y].up = p
	if p == 0 {
		q.root = y
	} else if x == tree[p].left {
		tree[p].left = y
	} else {
		tree[p].right = y
	}
	tree[y].left = x; tree[x].up = y
}
func (q *rbtreemultiset) rotright(x int32) {
	tree := q.tree; y := tree[x].left; p := tree[x].up; tree[x].left = tree[y].right
	if tree[y].right != 0 { tree[tree[y].right].up = x }; tree[y].up = p
	if p == 0 {
		q.root = y
	} else if x == tree[p].right {
		tree[p].right = y
	} else {
		tree[p].left = y
	}
	tree[y].right = x; tree[x].up = y
}
func (q *rbtreemultiset) getNewNodenum() int32 {
	l := len(q.recycler); newnode := q.recycler[l-1]; q.recycler = q.recycler[:l-1]
	if l == 1 { q.tree = append(q.tree, rbtreemultisetnode{}); q.recycler = append(q.recycler, int32(len(q.tree)-1)) }
	return newnode
}

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
	// Any singleton greater than the mex should be used to help the mex (guaranteed to reduce cost by at least 1)
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N,K := gi(),gi(); A := gis(N)
		hist := make(map[int]int)
		for _,a := range A { hist[a]++ }
		aa := Newrbtreemultiset(func(a,b int) bool { return a < b })
		bb := Newrbtreemultiset(func(a,b int) bool { return a < b })
		for _,v := range hist { bb.Add(v) }
		sum := 0; ans := 1000000000; holes := 0
		for mex:=0;mex<=N;mex++ {
			for !bb.IsEmpty() && sum + bb.MinKey() <= K {
				sum += bb.MinKey()
				aa.Add(bb.MinKey())
				bb.Delete(bb.MinKey())
			}
			if holes <= K {
				ans = min(ans, bb.Len())
			}
			if hist[mex] == 0 {
				holes++
			} else {
				s := hist[mex]
				if aa.Count(s) > 0 { sum -= s; aa.Delete(s) } else { bb.Delete(s) }
			}
		}
		fmt.Fprintln(wrtr,ans)
	}
}

package main

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

// 拿单独出现的最大的数来填
// 若最大的数很多，拿来填也不坏
// 0 1 3 5 5
// 0 1 2 5 5 = 1
// 0 1 2 3 5 = 2 better
// ----
// 0 1 6 8 8
// 0 1 2 8 8 = 1
// 0 1 2 6 8 = 2 bad
// 二分答案 二分 mex
// get mex ->  <= mex 不变 get an ans
// mex 越大越好
// mex 可达 加大
//不可达 变小
func A4() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	Fscan(in, &cas)
	var sol func()
	// Coding...beg!
	sol = func() {
		var n, op int
		Fscan(in, &n, &op)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			Fscan(in, &arr[i])
		}
		if op == 0 {
			mmap := make(map[int]int)
			for i := 0; i < n; i++ {
				mmap[arr[i]]++
			}
			var mex int
			for k := 0; k < int(1e6); k++ {
				if _, ok := mmap[k]; !ok {
					mex = k
					break
				}
			}
			Fprintln(out, len(mmap)-mex)
			return
		}
		sort.Ints(arr)
		// 0-mex
		l, r := 0, int(1e5)
		var ans int
		for l <= r {
			mex := l + (r-l)/2
			idx := sort.Search(n, func(k int) bool { return arr[k] > mex })
			var ct int //不同的数
			if idx >= 1 {
				ct = 1
			}
			for i := 1; i < idx; i++ {
				if arr[i] != arr[i-1] {
					ct++
				}
			}
			ct = (mex + 1) - ct
			if op < ct {
				r = mex - 1
				continue
			}
			cnt := make([]int, 0)
			Map := make(map[int]int)
			for k := idx; k < n; k++ {
				Map[arr[k]]++
			}
			for _, v := range Map {
				cnt = append(cnt, v)
			}
			sort.Ints(cnt)
			var k int
			for k = 0; k < len(cnt); k++ {
				if cnt[k] <= ct {
					ct -= cnt[k]
				} else {
					break
				}
			}
			ans = mex + 1 + (len(cnt) - k) - (mex + 1)
			l = mex + 1
		}
		Fprintln(out, ans)
	}
	// Coding...ove!
	for i := 0; i < cas; i++ {
		sol()
	}
}

func main() { A4() }


package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := getMid(start, end, total, k)
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = getMid(start, end, total, k)
		}
	}
}

func getMid(start, end, total, num int) int {
	// var point float64 = float64(num) - 1/float64(total)
	// if num == 1 {
	// 	point = 1 / float64(total)
	// }
	const point = 0.5
	return int(point*float64(end-start+1)) + start
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := int(float64(1)/float64(2)*float64(end-start+1)) + start
		// if k > total/2 {
		// 	mid = int(float64(total-k)/float64(total)*float64(end-start+1)) + start
		// }
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = int(float64(1)/float64(2)*float64(end-start+1)) + start
			// if k > total/2 {
			// 	mid = int(float64(total-k)/float64(total)*float64(end-start+1)) + start
			// }
		}
	}
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main
import(."fmt";."sort")

// github.com/EndlessCheng/codeforces-go
func main(){
	var n,k,c int
	Scan(&n,&k,&k)
	Println("!",1+Search(n-1,func(r int)bool{
		Println("?",1,r+1)
		Scan(&c)
		return c+k<=r+1
	}))
}

package main

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

type (
	input struct{ n, t, k int }
	req   struct{ l, r int }
	resp  struct{ v int }
	guess struct{ ans int }
)

// github.com/EndlessCheng/codeforces-go
func run(in input, Q func(req) resp) (gs guess) {
	q := func(l, r int) int { return Q(req{l, r}).v }
	n, k := in.n, in.k
	ans := 0
	defer func() { gs.ans = ans }()

	ans = sort.Search(n-1, func(r int) bool {
		c := q(1, r+1)
		return c + k <= r+1
	})
	ans++

	return
}

func ioq() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)

	// Interaction
	Q := func(req req) (resp resp) {
		Fprintln(out, "?", req.l, req.r)
		out.Flush()
		Fscan(in, &resp.v)
		return
	}

	T := 1
	//Fscan(in, &T) //
	for ; T > 0; T-- {
		// Input
		d := input{}
		Fscan(in, &d.n, &d.t, &d.k)

		// Output
		gs := run(d, Q)
		ans := gs.ans
		Fprintln(out, "!", ans)
		out.Flush()
	}
}

func main() { ioq() }

package main

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

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

func getDiff(cur int) int {
	fmt.Fprintf(out, "? 1 %d\n", cur)
	out.Flush()

	var sum int
	fmt.Fscan(in, &sum)
	return cur - sum
}

func main() {
	defer out.Flush()

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

	if t != 1 {
		log.Fatalf("invalid t: %d", t)
	}
	var k int
	fmt.Fscan(in, &k)

	cnt := 0
	result := -1
	left, right := 1, n
	for left <= right {
		mid := left + (right-left)/2
		if getDiff(mid) >= k {
			result = mid
			right = mid - 1
		} else {
			left = mid + 1
		}
		cnt++
		if cnt > 20 {
			log.Fatal("cnt is over")
		}
	}
	fmt.Fprintf(out, "! %d\n", result)
}

package main

import (
    "fmt"
)

func bscan(x *int) {
    _, err := fmt.Scanln(x)
    for err != nil {
        _, err = fmt.Scanln(x)
    }
}

func main() {
    var strlen, n_tasks, k int
    fmt.Scanln(&strlen, &n_tasks)
    fmt.Scanln(&k);

    // l_bord <= ans < r_bord ; ans in [0, n) format
    var l_bord = -1
    var r_bord = strlen - 1
    for r_bord - l_bord > 1 {
        var m_bord = (l_bord + r_bord) / 2
        fmt.Println("? 1", m_bord + 1)

        var query_ans int
        fmt.Scan(&query_ans)

        if (m_bord + 1) - query_ans >= k {
            r_bord = m_bord
        } else {
            l_bord = m_bord
        }
    }
    fmt.Printf("! %d\n", r_bord + 1)
}

package main

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

func getSum(in io.Reader, out *bufio.Writer, l, r int) int {
	fmt.Fprintf(out, "? %d %d\n", l + 1, r + 1)
	out.Flush()

	var sum int
	fmt.Fscanln(in, &sum)

	return sum
}

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

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

	for i := 0; i < t; i++ {
		var k int
		fmt.Fscanln(in, &k)

		l, r := 0, n-1

		for r != l {
			m := (r + l) / 2

			sum := getSum(in, out, l, m)
			zerosCnt := (m - l + 1) - sum

			if k > zerosCnt {
				l = m + 1
				k -= zerosCnt
			} else {
				r = m
			}
		}

		fmt.Fprintf(out, "! %d\n", l + 1)
		out.Flush()
	}
}

package main

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

func requests(l, r int, reader *bufio.Reader) (sum int) {
	// var arr []int = []int{100, 1, 0, 1, 1, 0, 1}
	// for i := l; i <= r; i++ {
	// 	sum += arr[i]
	// }
	fmt.Printf("? %d %d\n", l, r)
	os.Stdout.Sync()
	fmt.Fscanf(reader, "%d\n", &sum)

	return
}

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

	var n, t, k int

	fmt.Fscanf(reader, "%d %d\n", &n, &t)
	for ; t > 0; t-- {
		fmt.Fscanf(reader, "%d\n", &k)
		l, r := 1, n
		var mid, had int
		for l < r {
			mid = l + (r-l)/2
			had = mid - l + 1 - requests(l, mid, reader)
			if had < k {
				k = k - had
				l = mid + 1
			} else {
				r = mid
			}
		}

		fmt.Printf("! %d\n", l)
	}
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := getMid(start, end, total, k)
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = getMid(start, end, total, k)
		}
	}
}

func getMid(start, end, total, num int) int {
	var point float64 = float64(num) / float64(total+1)
	ret := int(point*float64(end-start+1)) + start
	if ret == start {
		ret = start + 1
	}
	return ret
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := getMid(start, end, total, k)
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = getMid(start, end, total, k)
		}
	}
}

func getMid(start, end, total, num int) int {
	var point float64 = float64(num) / float64(total+1)
	return int(point*float64(end-start+1)) + start
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := getMid(start, end, total, k)
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = getMid(start, end, total, k)
		}
	}
}

func getMid(start, end, total, num int) int {
	var point float64 = (float64(num) - 1) / float64(total)
	if num == 1 {
		point = 1 / float64(total)
	}
	return int(point*float64(end-start+1)) + start
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := getMid(start, end, total, k)
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = getMid(start, end, total, k)
		}
	}
}

func getMid(start, end, total, num int) int {
	var point float64 = float64(num) - 1/float64(total)
	if num == 1 {
		point = 1 / float64(total)
	}
	return int(point*float64(end-start+1)) + start
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := int(float64(1)/float64(total)*float64(end-start+1)) + start
		// if k > total/2 {
		// 	mid = int(float64(total-k)/float64(total)*float64(end-start+1)) + start
		// }
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = int(float64(1)/float64(total)*float64(end-start+1)) + start
			// if k > total/2 {
			// 	mid = int(float64(total-k)/float64(total)*float64(end-start+1)) + start
			// }
		}
	}
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := int(float64(k)/float64(total)*float64(end-start+1)) + start
		if k > total/2 {
			mid = int(float64(total-k)/float64(total)*float64(end-start+1)) + start
		}
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = int(float64(k)/float64(total)*float64(end-start+1)) + start
			if k > total/2 {
				mid = int(float64(total-k)/float64(total)*float64(end-start+1)) + start
			}
		}
	}
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := k/total*(end-start+1) + start
		if k > total/2 {
			mid = (total-k)/total*(end-start+1) + start
		}
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = k/total*(end-start+1) + start
			if k > total/2 {
				mid = (total-k)/total*(end-start+1) + start
			}
		}
	}
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := k/total*(end-start+1) + start
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid-1)
			if f >= k {
				end = mid - 1
				total = f
			} else {
				start = mid
				k -= f
				total -= f
			}
			mid = k/total*(end-start+1) + start
		}
	}
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := k/total*(end-start) + start
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid)
			if f >= k {
				end = mid
				total = f
			} else {
				start = mid + 1
				k -= f
				total = total - f
			}
			mid = k/total*(end-start) + start
		}
	}
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 - k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := k/total*(end-start) + start
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid)
			if f >= k {
				end = mid
				total = f
			} else {
				start = mid + 1
				k -= f
				total = total - f
			}
			mid = k/total*(end-start) + start
		}
	}
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 + k
}

func found(p int) {
	fmt.Printf("! %d\n", 5)
}

package main

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

func ReadByte() byte {
	return ReadBytes(1)[0]
}

func ReadNL() byte {
	var nl byte
	for nl != 0x0a {
		nl = ReadByte()
	}
	return nl
}

func ReadBytes(n int) []byte {
	p := make([]byte, n)
	_, err := io.ReadFull(os.Stdin, p)
	if err != nil {
		panic(err)
	}
	return p
}

func main() {
	var n int
	var t int
	_, err := fmt.Scanf("%d %d", &n, &t)
	if err != nil {
		panic(err)
	}
	for i := 0; i < t; i++ {
		ReadNL()
		var k int
		_, err := fmt.Scanf("%d", &k)
		if err != nil {
			panic(err)
		}
		if k == -1 {
			os.Exit(0)
		}
		start := 1
		end := n
		total := get(1, n)
		mid := k/total*(end-start) + start
		for {
			if end == start {
				found(start)
				break
			}
			f := get(start, mid)
			if f >= k {
				end = mid
				total = f
			} else {
				start = mid + 1
				k -= f
				total = total - f
			}
			mid = k/total*(end-start) + start
		}
	}
}

func get(s, e int) int {
	fmt.Printf("? %d %d\n", s, e)
	ReadNL()
	var k int
	_, err := fmt.Scanf("%d", &k)
	if err != nil {
		panic(err)
	}
	if k == -1 {
		os.Exit(0)
	}
	return e - s + 1 + k
}

func found(p int) {
	fmt.Printf("! %d\n", p)
}

package main
import(."fmt";."sort")

// github.com/EndlessCheng/codeforces-go
func main(){
	var n,k,c int
	Scan(&n,&k,&k)
	Println("!",1+Search(n-1,func(r int)bool{
		Println(1,r+1)
		Scan(&c)
		return c+k<=r+1
	}))
}

package main
import(."fmt";."sort")

// github.com/EndlessCheng/codeforces-go
func main(){
	var n,k,c int
	Scan(&n,&k,&k)
	Println("!",1+Search(n,func(r int)bool{
		Println(1,r+1)
		Scan(&c)
		return c+k<=r+1
	}))
}

package main

import "fmt"

func main() {
    var strlen, n_tasks, k int
    fmt.Scan(&strlen, &n_tasks, &k)

    // l_bord <= ans < r_bord ; ans in [0, n) format
    var l_bord = -1
    var r_bord = strlen - 1
    for r_bord - l_bord > 1 {
        var m_bord = (l_bord + r_bord) / 2

        fmt.Printf("? 1 %d\n", m_bord + 1)

        var query_ans int
        fmt.Scan(query_ans)

        if (m_bord + 1) - query_ans >= k {
            r_bord = m_bord
        } else {
            l_bord = m_bord
        }
    }
    fmt.Printf("! %d", r_bord + 1)
}

package main

import "fmt"

func main() {
    var strlen, n_tasks, k int
    fmt.Scan(&strlen, &n_tasks, &k)

    // l_bord <= ans < r_bord ; ans in [0, n) format
    var l_bord = 0
    var r_bord = strlen
    for r_bord - l_bord > 1 {
        var m_bord = (l_bord + r_bord) / 2

        fmt.Printf("? 1 %d\n", m_bord + 1)

        var query_ans int
        fmt.Scan(query_ans)

        if m_bord - query_ans > k {
            r_bord = m_bord
        } else {
            l_bord = m_bord
        }
    }
    fmt.Printf("! %d", l_bord)
}


package main

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

var n int
var a []int
var r int64
var p []int
var cnt map[int]int

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

	fmt.Fscan(bufin, &n)
	a = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(bufin, &a[i])
	}

	p = make([]int, 31)
	p[0] = 1
	for i := 1; i < 31; i++ {
		p[i] = p[i-1] * 2
	}

	cnt = make(map[int]int)
	r = 0

	for i := 0; i < n; i++ {
		x := a[i]
		for j := 30; j >= 0 && p[j] > x; j-- {
			y := p[j] - x
			r += int64(cnt[y])
		}
		cnt[x]++
	}

	fmt.Fprint(bufout, r)
}

package main

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

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

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)
	log.SetOutput(ioutil.Discard)
	// log.SetOutput(os.Stderr)

	n := nextInt()
	m := make(map[int]int64)
	ans := int64(0)

	for i := 0; i < n; i++ {
		m[nextInt()]++
	}
	// println(m)
	for k := range m {
		pow2 := 1

		for i := 1; i < 31; i++ {
			// println(pow2)
			pow2 = pow2 << 1

			if pow2 <= k {
				continue
			}

			if v, ok := m[pow2-k]; ok {
				// println(pow2, k, v, ans)

				if k<<1 == pow2 {
					ans += v * (v - 1) / 2
				} else {
					ans += (m[k] * v)
				}
			}
		}

		m[k] = 0
	}

	println(ans)
}

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

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

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

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

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

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin);
   	var n int
   	fmt.Fscan(reader,&n)
    s := make([]int,n + 5)
    for i := 0;i < n;i++ {
    	fmt.Fscan(reader,&s[i])
    }
    m := map[int]int {}
    p2 := make([]int,35)
    p2[0] = 1
    for i := 1;i <= 30;i++ {
 		p2[i] = p2[i - 1] * 2
    }
 	var ans int64 = 0
 	for i := 0;i < n;i++ {
 		for j := 0;j <= 30;j++ {
 			ans += (int64)(m[p2[j] - s[i]])
 		}
 		m[s[i]]++
 	}
 	fmt.Println(ans)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(reader, &n)
	a := make([]int, n+6)
	sum := map[int]int{}
	for i := 1; i <= n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	p2 := make([]int, 35)
	p2[0] = 1
	for i := 1; i <= 30; i++ {
		p2[i] = p2[i-1] * 2
	}
	var ans int64 = 0
	for i := 1; i <= n; i++ {
		for k := 1; k <= 30; k++ {
			ans += int64(sum[p2[k]-a[i]])
		}
		sum[a[i]]++
	}
	fmt.Println(ans)
}

package main

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

var n int
var a []int
var r int
var p []int
var cnt map[int]int

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

	fmt.Fscan(bufin, &n)
	a = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(bufin, &a[i])
	}

	p = make([]int, 31)
	p[0] = 1
	for i := 1; i < 31; i++ {
		p[i] = p[i-1] * 2
	}

	cnt = make(map[int]int)
	r = 0

	for i := 0; i < n; i++ {
		x := a[i]
		for j := 30; j >= 0 && p[j] > x; j-- {
			y := p[j] - x
			r += cnt[y]
		}
		cnt[x]++
	}

	fmt.Fprint(bufout, r)
}

package main

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

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

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)
	log.SetOutput(ioutil.Discard)
	// log.SetOutput(os.Stderr)

	n := nextInt()
	m := make(map[int]int)
	ans := 0

	for i := 0; i < n; i++ {
		m[nextInt()]++
	}
	// println(m)
	for k := range m {
		pow2 := 1

		for i := 1; i < 31; i++ {
			// println(pow2)
			pow2 = pow2 << 1

			if pow2 <= k {
				continue
			}

			if v, ok := m[pow2-k]; ok {
				// println(pow2, k, v, ans)

				if k<<1 == pow2 {
					ans += v * (v - 1) / 2
				} else {
					ans += (m[k] * v)
				}
			}
		}

		m[k] = 0
	}

	println(ans)
}

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

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

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

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

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

package main

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

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

func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)
	log.SetOutput(ioutil.Discard)
	// log.SetOutput(os.Stderr)

	n := nextInt()
	m := make(map[int]int)
	ans := int64(0)

	for i := 0; i < n; i++ {
		m[nextInt()]++
	}
	// println(m)
	for k := range m {
		pow2 := 1

		for i := 1; i < 31; i++ {
			// println(pow2)
			pow2 = pow2 << 1

			if pow2 <= k {
				continue
			}

			if v, ok := m[pow2-k]; ok {
				// println(pow2, k, v, ans)

				if k<<1 == pow2 {
					ans += int64(v * (v - 1) / 2)
				} else {
					ans += int64(m[k] * v)
				}
			}
		}

		m[k] = 0
	}

	println(ans)
}

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

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

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

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

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

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin);
   	var n int
   	fmt.Fscan(reader,&n)
    s := make([]int,n + 5)
    for i := 0;i < n;i++ {
    	fmt.Fscan(reader,&s[i])
    }
    m := map[int]int {}
    p2 := make([]int,35)
    p2[0] = 1
    for i := 1;i < 30;i++ {
 		p2[i] = p2[i - 1] * 2
    }
 	var ans int64 = 0
 	for i := 0;i < n;i++ {
 		for j := 0;j < 30;j++ {
 			ans += (int64)(m[p2[j] - s[i]])
 		}
 		m[s[i]]++
 	}
 	fmt.Println(ans)
}

package main

import "fmt"

var a [100009]int
var sum map[int]int = make(map[int]int)

func main() {
	var n, maxx int = 0, 0
	fmt.Scanf("%d", &n)
	for i := 1; i <= n; i++ {
		fmt.Scanf("%d", &a[i])
		sum[a[i]]++
		if a[i] > maxx {
			maxx = a[i]
		}
	}
	var ans = 0
	for s := 2; s <= maxx*2; s <<= 1 {
		for i := 1; i <= n; i++ {
			sum[a[i]]--
			if s > a[i] {
				ans += sum[s-a[i]]
			}
			sum[a[i]]++
		}
	}
	fmt.Print(ans >> 1)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(reader, &n)
	a := make([]int, n+6)
	sum := map[int]int{}
	for i := 1; i <= n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	p2 := make([]int, 35)
	p2[0] = 1
	for i := 1; i <= 30; i++ {
		p2[i] = p2[i-1] * 2
	}
	var ans int = 0
	for i := 1; i <= n; i++ {
		for k := 1; k <= 30; k++ {
			ans += sum[p2[k]-a[i]]
		}
		sum[a[i]]++
	}
	fmt.Println(ans)
}