// https://codeforces.com/problemset/problem/1695/E

// 1695E - Ambiguous Dominoes

// Polycarp and Monocarp are both solving the same puzzle with dominoes. They are given the same set of n dominoes, the i-th of which contains two numbers xi and yi. They are also both given the same m by k grid of values aij such that m⋅k=2n.
// The puzzle asks them to place the n dominoes on the grid in such a way that none of them overlap, and the values on each domino match the aij values that domino covers. Dominoes can be rotated arbitrarily before being placed on the grid, so the domino (xi,yi) is equivalent to the domino (yi,xi).
// They have both solved the puzzle, and compared their answers, but noticed that not only did their solutions not match, but none of the n dominoes were in the same location in both solutions! Formally, if two squares were covered by the same domino in Polycarp's solution, they were covered by different dominoes in Monocarp's solution. The diagram below shows one potential a grid, along with the two players' solutions.
// Polycarp and Monocarp remember the set of dominoes they started with, but they have lost the grid a. Help them reconstruct one possible grid a, along with both of their solutions, or determine that no such grid exists.

// Input
// The first line contains a single integer n (1≤n≤3⋅105).

// Output
// If there is no solution, print a single integer −1.
// Otherwise, print m and k, the height and width of the puzzle grid, on the first line of output. These should satisfy m⋅k=2n.
// The i-th of the next m lines should contain k integers, the j-th of which is aij.
// The next m lines describe Polycarp's solution. Print m lines of k characters each. For each square, if it is covered by the upper half of a domino in Polycarp's solution, it should contain a "U". Similarly, if it is covered by the bottom, left, or right half of a domino, it should contain "D", "L", or "R", respectively.
// The next m lines should describe Monocarp's solution, in the same format as Polycarp's solution.
// If there are multiple answers, print any.

// Examples

// input
// 1
// 1 2
// output
// -1

// input
// 2
// 1 1
// 1 2
// output
// 2 2
// 2 1
// 1 1
// LR
// LR
// UU
// DD

// input
// 10
// 1 3
// 1 1
// 2 1
// 3 4
// 1 5
// 1 5
// 3 1
// 2 4
// 3 3
// 4 1
// output
// 4 5
// 1 2 5 1 5
// 3 4 1 3 1
// 1 2 4 4 1
// 1 3 3 3 1
// LRULR
// LRDLR
// ULRLR
// DLRLR
// UULRU
// DDUUD
// LRDDU
// LRLRD

package main

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

func dfs(adj [][]struct{ v, i int }, i int, used *[]bool, usedEdges *[]bool, lst *[]int) {
	*lst = append(*lst, i)

	if !(*used)[i] {
		(*used)[i] = true

		for _, p := range adj[i] {
			if !(*usedEdges)[p.i] {
				(*usedEdges)[p.i] = true
				dfs(adj, p.v, used, usedEdges, lst)
				*lst = append(*lst, i)
			}
		}
	}
}

func main() {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	var t, n, x, y, i, j, idx, k int
	var adj [][]struct{ v, i int }
	var used, usedEdges []bool
	var ptop, pbot, mtop, mbot []byte
	var lst []int
	var flag bool
	var ans [][]int

	// Reads n and m until EOF
	for t, _ = fmt.Fscan(reader, &n); t == 1; t, _ = fmt.Fscan(reader, &n) {
		adj = make([][]struct{ v, i int }, 2*n)
		used = make([]bool, 2*n)
		usedEdges = make([]bool, 2*n)
		ptop = make([]byte, n)
		pbot = make([]byte, n)
		mtop = make([]byte, n)
		mbot = make([]byte, n)
		ans = make([][]int, 2)
		ans[0] = make([]int, n)
		ans[1] = make([]int, n)
		lst = make([]int, 0)

		for i = 0; i < n; i++ {
			fmt.Fscan(reader, &x, &y)
			x--
			y--
			adj[x] = append(adj[x], struct{ v, i int }{y, i})
			adj[y] = append(adj[y], struct{ v, i int }{x, i})
			used[i] = false
			used[n+i] = false
			usedEdges[i] = false
			usedEdges[n+i] = false
			ptop[i] = 'U'
			pbot[i] = 'D'
			mtop[i] = 'U'
			mbot[i] = 'D'
		}

		idx = 0
		flag = false

		for i = 0; i < 2*n && !flag; i++ {
			if !used[i] {
				dfs(adj, i, &used, &usedEdges, &lst)
				lst = lst[:len(lst)-1]
				k = len(lst) / 2

				if k != 1 {
					for j = 0; j < k; j++ {
						ans[0][idx+j] = lst[j]
						ans[1][idx+j] = lst[2*k-j-1]
					}

					for j = 0; j < k-1; j += 2 {
						ptop[idx+j] = 'L'
						pbot[idx+j] = 'L'
						ptop[idx+j+1] = 'R'
						pbot[idx+j+1] = 'R'
					}

					for j = 1; j < k-1; j += 2 {
						mtop[idx+j] = 'L'
						mbot[idx+j] = 'L'
						mtop[idx+j+1] = 'R'
						mbot[idx+j+1] = 'R'
					}

					lst = lst[:0]
					idx += k
				} else { // k == 1
					flag = true
				}
			}
		}

		if flag {
			fmt.Fprintln(writer, -1)
		} else {
			fmt.Fprintln(writer, 2, n)

			for i = 0; i < 2; i++ {
				for j = 0; j < n-1; j++ {
					fmt.Fprint(writer, ans[i][j]+1, " ")
				}

				fmt.Fprintln(writer, ans[i][n-1]+1)
			}

			fmt.Fprintln(writer, string(ptop))
			fmt.Fprintln(writer, string(pbot))
			fmt.Fprintln(writer, string(mtop))
			fmt.Fprintln(writer, string(mbot))
		}
	}

	writer.Flush()
}

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
}
type edge struct {n,idx int}
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
	N := gi(); X,Y := fill2(N)
	gr := make([][]edge,2*N+1)
	for i:=0;i<N;i++ { x,y := X[i],Y[i]; gr[x] = append(gr[x],edge{y,i}); gr[y] = append(gr[y],edge{x,i}) }
	ansarr := twodi(2,N,-1)
	mtop := make([]byte,N); mbot := make([]byte,N); ptop := make([]byte,N);	pbot := make([]byte,N)
	for i:=0;i<N;i++ { mtop[i] = 'U'; ptop[i] = 'U'; mbot[i] = 'D'; pbot[i] = 'D' }
	lst := make([]int,0)
	used := make([]bool,2*N+1)
	usedEdges := make([]bool,N)
	var dfs func(n int)
	dfs = func(n int) {
		lst = append(lst,n);
		if !used[n] {
			used[n] = true
			for _,p := range gr[n] {
				if !usedEdges[p.idx] {
					usedEdges[p.idx] = true
					dfs(p.n)
					lst = append(lst,n)
				}
			}
		}
	}
	idx := 0
	good := true
	for i:=1;i<=2*N;i++ {
		if used[i] { continue }
		dfs(i)
		lst = lst[:len(lst)-1]
		k := len(lst)/2
		if k == 1 { good = false; break }
		for j:=0;j<k;j++ {
			ansarr[0][j+idx] = lst[j]
			ansarr[1][j+idx] = lst[2*k-1-j]
		}
		for j:=0;j<k-1;j+=2 { ptop[j+idx] = 'L'; pbot[j+idx] = 'L'; ptop[j+idx+1] = 'R'; pbot[j+idx+1] = 'R' }
		for j:=1;j<k-1;j+=2 { mtop[j+idx] = 'L'; mbot[j+idx] = 'L'; mtop[j+idx+1] = 'R'; mbot[j+idx+1] = 'R' }
		lst = lst[:0]
		idx += k
	}
	if !good {
		fmt.Println(-1)
	} else {
		fmt.Printf("%v %v\n",2,N)
		fmt.Println(vecintstring(ansarr[0]))
		fmt.Println(vecintstring(ansarr[1]))
		fmt.Println(string(ptop))
		fmt.Println(string(pbot))
		fmt.Println(string(mtop))
		fmt.Println(string(mbot))
	}
}


package main

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

const N = 2e5 + 5

var g = make([][]int, N)

// g := [N][] int
var ans = 0
var edge_cnt = 0
var l [N]int64
var r [N]int64
var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

type Edge struct {
	// from int
	to   int
	next int
}

var head [N]int
var edges [N]Edge

func add_edge(u int, v int) {
	edge_cnt++
	edges[edge_cnt].next = head[u]
	edges[edge_cnt].to = v
	head[u] = edge_cnt
}
func Min(a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func dfs(u int) int64 {
	var sum int64 = 0
	for _, v := range g[u] {
		// v := edges[idx].to
		sum += dfs(v)
	}
	if sum < l[u] {
		ans++
		return r[u]
	}
	return Min(r[u], sum)

}
func solve() {
	var n int
	// edge_cnt = 0
	ans = 0
	fmt.Fscan(rr, &n)
	for i := 1; i <= n; i++ {
		head[i] = -1
		g[i] = make([]int, 0)
	}
	for i := 2; i <= n; i++ {
		var tmp int
		fmt.Fscan(rr, &tmp)
		g[tmp] = append(g[tmp], i)

	}
	for i := 1; i <= n; i++ {
		fmt.Fscan(rr, &l[i], &r[i])
	}
	dfs(1)
	// fmt.Printf("ans is : ")
	fmt.Println(ans)
}
func main() {
	// var a []int
	// a = make([]int, 0)
	// a = append(a, 1)
	// fmt.Println(a[0])
	// for i := 1; i <= 10; i++ {
	// 	a = append(a, i)
	// }
	// for _, val := range a {
	// 	fmt.Printf("%d\t", val)
	// }
	defer ww.Flush()
	var T int
	fmt.Fscan(rr, &T)
	for i := 1; i <= T; i++ {
		solve()
	}

}

package main

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

const N = 2e5 + 5

// var g = make([][]int, N)

// g := [N][] int
var ans = 0
var edge_cnt = 0
var l [N]int64
var r [N]int64
var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

type Edge struct {
	// from int
	to   int
	next int
}

var head [N]int
var edges [N]Edge

func add_edge(u int, v int) {
	edge_cnt++
	edges[edge_cnt].next = head[u]
	edges[edge_cnt].to = v
	head[u] = edge_cnt
}
func Min(a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func dfs(u int) int64 {
	var sum int64 = 0
	for idx := head[u]; idx != -1; idx = edges[idx].next {
		v := edges[idx].to
		sum += dfs(v)
	}
	if sum < l[u] {
		ans++
		return r[u]
	}
	return Min(r[u], sum)

}
func solve() {
	var n int
	edge_cnt = 0
	ans = 0
	fmt.Fscan(rr, &n)
	for i := 1; i <= n; i++ {
		head[i] = -1
	}
	for i := 2; i <= n; i++ {
		var tmp int
		fmt.Fscan(rr, &tmp)
		add_edge(tmp, i)

	}
	for i := 1; i <= n; i++ {
		fmt.Fscan(rr, &l[i], &r[i])
	}
	dfs(1)
	// fmt.Printf("ans is : ")
	fmt.Println(ans)
}
func main() {

	defer ww.Flush()
	var T int
	fmt.Fscan(rr, &T)
	for i := 1; i <= T; i++ {
		solve()
	}

}

package main

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

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

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

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

		pp := make([]int64, n)
		for i := 1; i < n; i++ {
			fmt.Fscan(in, &pp[i])
			pp[i]--
		}
		ll, rr := make([]int64, n), make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &ll[i], &rr[i])
		}

		gg := make([]int64, n)
		var tot int64
		for i := n - 1; i >= 0; i-- {
			if gg[i] < ll[i] {
				gg[i] = rr[i]
				tot++
			} else {
				gg[i] = min(gg[i], rr[i])
			}
			if i > 0 {
				gg[pp[i]] += gg[i]
			}
		}
		fmt.Fprintln(out, tot)
	}
}

package main

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

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

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

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

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

		l := make([]int64, n)
		r := make([]int64, n)
		for i := 0; i < n; i++ {
			var x, y int64
			fmt.Fscan(in, &x, &y)
			l[i] = x
			r[i] = y
		}

		var tot int
		var walk func(id int) int64
		walk = func(id int) int64 {
			var sum int64
			for _, cID := range m[id] {
				sum += walk(cID)
			}
			if sum < l[id] {
				tot++
				return r[id]
			}
			return min(sum, r[id])
		}

		walk(0)
		fmt.Fprintln(out, tot)
	}
}

package main

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

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

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

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

		m := make(map[int][]int)
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)
			m[v-1] = append(m[v-1], i+1)
		}

		l := make([]int64, n)
		r := make([]int64, n)
		for i := 0; i < n; i++ {
			var x, y int64
			fmt.Fscan(in, &x, &y)
			l[i] = x
			r[i] = y
		}

		var tot int
		var walk func(id int) int64
		walk = func(id int) int64 {
			var sum int64
			for _, cID := range m[id] {
				sum += walk(cID)
			}
			if sum < l[id] {
				tot++
				return r[id]
			}
			return min(sum, r[id])
		}

		walk(0)
		fmt.Fprintln(out, tot)
	}
}

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," ") }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N := gi(); P := gis(N-1); for i:=0;i<N-1;i++ { P[i]-- }; L,R := fill2(N)
		gr := make([][]int,N)
		for i:=1;i<N;i++ { p := P[i-1]; gr[p] = append(gr[p],i) }
		var dfs func(n int) (int,int64)
		dfs = func(n int) (int,int64) {
			if len(gr[n]) == 0 {
				return 1,int64(R[n])
			} else {
				cnt,sum := 0,int64(0)
				for _,c := range gr[n] { ccnt,ccmaxsum := dfs(c); cnt += ccnt; sum += ccmaxsum }
				if sum > int64(R[n]) { return cnt,int64(R[n]) }
				if sum < int64(L[n]) { return cnt+1,int64(R[n]) }
				return cnt,sum
			}
		}
		nops,_ := dfs(0)
		fmt.Fprintln(wrtr,nops)
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

type Node struct {
	l, r     int
	children []*Node
}

func solve() {
	var n int
	fmt.Fscan(r, &n)
	var nodes = make([]*Node, n)
	for i := range nodes {
		nodes[i] = &Node{
			children: []*Node{},
		}
	}
	var parent int
	for i := 1; i < n; i++ {
		fmt.Fscan(r, &parent)
		nodes[parent-1].children = append(nodes[parent-1].children, nodes[i])
	}
	var a, b int
	for i := 0; i < n; i++ {
		fmt.Fscan(r, &a, &b)
		nodes[i].l = a
		nodes[i].r = b
	}
	ans := 0
	var dfs func(node *Node) int64
	dfs = func(node *Node) int64 {
		var sum int64 = 0
		for _, c := range node.children {
			sum += dfs(c)
		}
		if sum < int64(node.l) {
			ans++
			return int64(node.r)
		}
		return min(int64(node.r), sum)
	}
	dfs(nodes[0])
	fmt.Fprintln(w, ans)
}

func min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func main() {
	defer w.Flush()
	var t int
	fmt.Fscan(r, &t)
	for ; t > 0; t-- {
		solve()
	}
}

package main

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

const N = 2e5 + 5

// var g = make([][]int, N)

// g := [N][] int
var ans = 0
var edge_cnt = 0
var l [N]int
var r [N]int
var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

type Edge struct {
	// from int
	to   int
	next int
}

var head [N]int
var edges [N]Edge

func add_edge(u int, v int) {
	edge_cnt++
	edges[edge_cnt].next = head[u]
	edges[edge_cnt].to = v
	head[u] = edge_cnt
}
func Min(a int, b int) int {
	if a < b {
		return a
	}
	return b
}
func dfs(u int) int {
	var sum = 0
	for idx := head[u]; idx != -1; idx = edges[idx].next {
		v := edges[idx].to
		sum += dfs(v)
	}
	if sum < l[u] {
		ans++
		return r[u]
	}
	return Min(r[u], sum)

}
func solve() {
	var n int
	edge_cnt = 0
	ans = 0
	fmt.Fscan(rr, &n)
	for i := 1; i <= n; i++ {
		head[i] = -1
	}
	for i := 2; i <= n; i++ {
		var tmp int
		fmt.Fscan(rr, &tmp)
		add_edge(tmp, i)

	}
	for i := 1; i <= n; i++ {
		fmt.Fscan(rr, &l[i], &r[i])
	}
	dfs(1)
	// fmt.Printf("ans is : ")
	fmt.Println(ans)
}
func main() {

	defer ww.Flush()
	var T int
	fmt.Fscan(rr, &T)
	for i := 1; i <= T; i++ {
		solve()
	}

}

package main

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

const N = 2e5 + 5

// var g = make([][]int, N)

// g := [N][] int
var ans = 0
var edge_cnt = 0
var l [N]int
var r [N]int
var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

type Edge struct {
	// from int
	to   int
	next int
}

var head [N]int
var edges [N]Edge

func add_edge(u int, v int) {
	edge_cnt += 1
	edges[edge_cnt].next = head[u]
	edges[edge_cnt].to = v
	head[u] = edge_cnt
}
func Min(a int, b int) int {
	if a < b {
		return a
	}
	return b
}
func dfs(u int) int {
	var sum = 0
	for idx := head[u]; idx != -1; idx = edges[idx].next {
		v := edges[idx].to
		sum += dfs(v)
	}
	if sum < l[u] {
		ans++
		return r[u]
	}
	return Min(r[u], sum)

}

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	for i := 1; i <= n; i++ {
		head[i] = -1
	}
	for i := 2; i <= n; i++ {
		var tmp int
		fmt.Fscan(rr, &tmp)
		add_edge(tmp, i)

	}
	for i := 1; i <= n; i++ {
		fmt.Fscan(rr, &l[i], &r[i])
	}
	dfs(1)
	fmt.Println(ans)

}

package main

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

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

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

		m := make(map[int][]int)
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)
			m[v-1] = append(m[v-1], i+1)
		}

		p := make([]int64, n)
		q := make([]int64, n)
		for i := 0; i < n; i++ {
			var x, y int64
			fmt.Fscan(in, &x, &y)
			p[i] = x
			q[i] = y
		}

		g := make([]int64, n)
		var walk func(id int) int64
		walk = func(id int) int64 {
			children, ok := m[id]
			if !ok {
				return q[id]
			}

			for _, childID := range children {
				g[id] += walk(childID)
			}
			return q[id]
		}

		walk(0)
		var tot int
		for i, v := range g {
			if p[i] > v {
				tot++
			}
		}
		fmt.Fprintln(out, tot)
	}
}


package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"sort"
	"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
const INF_INT32 = math.MaxInt32
const INF_BIT30 = 1 << 30

var n int
var A []int
var m int

type BinaryIndexedTree struct {
	bit     []int
	n       int
	minPow2 int
}

// n(>=1) is number of elements of original data
func NewBIT(n int) *BinaryIndexedTree {
	newBit := new(BinaryIndexedTree)

	newBit.bit = make([]int, n+1)
	newBit.n = n

	newBit.minPow2 = 1
	for {
		if (newBit.minPow2 << 1) > n {
			break
		}
		newBit.minPow2 <<= 1
	}

	return newBit
}

// Sum of [1, i](1-based)
func (b *BinaryIndexedTree) Sum(i int) int {
	s := 0

	for i > 0 {
		s += b.bit[i]
		i -= i & (-i)
	}

	return s
}

// Add x to i(1-based)
func (b *BinaryIndexedTree) Add(i, x int) {
	for i <= b.n {
		b.bit[i] += x
		i += i & (-i)
	}
}

// LowerBound returns minimum i such that bit.Sum(i) >= w.
func (b *BinaryIndexedTree) LowerBound(w int) int {
	if w <= 0 {
		return 0
	}

	x := 0
	for k := b.minPow2; k > 0; k /= 2 {
		if x+k <= b.n && b.bit[x+k] < w {
			w -= b.bit[x+k]
			x += k
		}
	}

	return x + 1
}

func main() {
	n = ReadInt()
	A = ReadIntSlice(n)
	m = ReadInt()

	// クエリを先読みしてkで昇順ソート
	L := make(QueryList, 0)
	for i := 0; i < m; i++ {
		k, pos := ReadInt2()
		L = append(L, &Query{id: i, k: k, pos: pos}) // idは0-basedで格納
	}
	sort.Stable(L)

	// Aを値で降順→位置で昇順にソート
	S := make(ElementList, 0)
	for i := 0; i < n; i++ {
		S = append(S, &Element{val: A[i], pos: i}) // posは0-basedで格納
	}
	sort.Stable(S)

	// BITをOrderedSetとして扱う
	bit := NewBIT(n)
	ck := 0
	// クエリの回答保持用
	answers := make([]int, m)
	// クエリをkの小さい順に処理していく
	for i := 0; i < m; i++ {
		q := L[i]
		// BITに格納した要素数がk個になるまで追加する
		for ; ck < q.k; ck++ {
			e := S[ck]
			bit.Add(e.pos+1, 1)
		}

		// BIT中のpos番目を回答する
		ans := bit.LowerBound(q.pos)
		answers[q.id] = A[ans-1]
	}

	// まとめて回答
	for i := 0; i < m; i++ {
		fmt.Println(answers[i])
	}
}

type Query struct {
	id, k, pos int
}
type QueryList []*Query

func (l QueryList) Len() int {
	return len(l)
}
func (l QueryList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l QueryList) Less(i, j int) bool {
	return l[i].k < l[j].k
}

// how to use
// L := make(QueryList, 0, 200000+5)
// L = append(L, &Query{key: intValue})
// sort.Stable(byKey{ L })                // Stable ASC
// sort.Stable(sort.Reverse(byKey{ L }))  // Stable DESC

type Element struct {
	val, pos int
}
type ElementList []*Element

func (l ElementList) Len() int {
	return len(l)
}
func (l ElementList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l ElementList) Less(i, j int) bool {
	if l[i].val > l[j].val {
		return true
	} else if l[i].val < l[j].val {
		return false
	} else {
		return l[i].pos < l[j].pos
	}
}

// how to use
// L := make(ElementList, 0, 200000+5)
// L = append(L, &Element{key: intValue})
// sort.Stable(byKey{ L })                // Stable ASC
// sort.Stable(sort.Reverse(byKey{ L }))  // Stable DESC

/*
- まずは全探索を検討しましょう
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
- いきなりオーバーフローはしていませんか？
- MOD取る系はint64必須ですよ？
*/

/*
ASCII code

ASCII   10進数  ASCII   10進数  ASCII   10進数
!       33      "       34      #       35
$       36      %       37      &       38
'       39      (       40      )       41
*       42      +       43      ,       44
-       45      .       46      /       47
0       48      1       49      2       50
3       51      4       52      5       53
6       54      7       55      8       56
9       57      :       58      ;       59
<       60      =       61      >       62
?       63      @       64      A       65
B       66      C       67      D       68
E       69      F       70      G       71
H       72      I       73      J       74
K       75      L       76      M       77
N       78      O       79      P       80
Q       81      R       82      S       83
T       84      U       85      V       86
W       87      X       88      Y       89
Z       90      [       91      \       92
]       93      ^       94      _       95
`       96      a       97      b       98
c       99      d       100     e       101
f       102     g       103     h       104
i       105     j       106     k       107
l       108     m       109     n       110
o       111     p       112     q       113
r       114     s       115     t       116
u       117     v       118     w       119
x       120     y       121     z       122
{       123     |       124     }       125
~       126             127
*/

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

package main

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

type pstNode struct {
	l, r   int
	lo, ro *pstNode
	sum    int
}
type pSegmentTree struct {
	versionRoots []*pstNode
}

func newPST(n int) *pSegmentTree {
	return &pSegmentTree{
		make([]*pstNode, 1, n+1),
	}
}

func (t *pSegmentTree) _build(l, r int) *pstNode {
	o := &pstNode{l: l, r: r}
	if l == r {
		return o
	}
	mid := (l + r) >> 1
	o.lo = t._build(l, mid)
	o.ro = t._build(mid+1, r)
	return o
}

func (t *pSegmentTree) _update(o *pstNode, idx int) *pstNode {
	tmp := *o
	o = &tmp
	if o.l == o.r {
		o.sum++
		return o
	}
	if idx <= o.lo.r {
		o.lo = t._update(o.lo, idx)
	} else {
		o.ro = t._update(o.ro, idx)
	}
	o.sum = o.lo.sum + o.ro.sum
	return o
}

func (t *pSegmentTree) _queryKth(o1, o2 *pstNode, k int) (idx int) {
	if o1.l == o1.r {
		return o1.l
	}
	if d := o2.lo.sum - o1.lo.sum; d >= k {
		return t._queryKth(o1.lo, o2.lo, k)
	} else {
		return t._queryKth(o1.ro, o2.ro, k-d)
	}
}

func (t *pSegmentTree) init(n int) {
	t.versionRoots[0] = t._build(1, n)
}

func (t *pSegmentTree) update(baseVersion int, idx int) {
	t.versionRoots = append(t.versionRoots, t._update(t.versionRoots[baseVersion], idx))
}

func (t *pSegmentTree) queryKth(l, r int, k int) (idx int) {
	return t._queryKth(t.versionRoots[l-1], t.versionRoots[r], k)
}

// github.com/EndlessCheng/codeforces-go
func Sol1262D2(reader io.Reader, writer io.Writer) {
	in := bufio.NewScanner(reader)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(writer)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}

	n := read()
	a := make([]int, n)
	type pair struct{ val, i int }
	ps := make([]pair, n)
	for i := range ps {
		a[i] = read()
		ps[i] = pair{a[i], i}
	}
	sort.Slice(ps, func(i, j int) bool {
		return ps[i].val > ps[j].val || ps[i].val == ps[j].val && ps[i].i < ps[j].i
	})
	st := newPST(n)
	st.init(n)
	for i, p := range ps {
		st.update(i, p.i+1)
	}

	for m := read(); m > 0; m-- {
		idx := st.queryKth(1, read(), read()) - 1
		Fprintln(out, a[idx])
	}
}

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

package main

import (
	"bufio"
	. "fmt"
	"io"
	"math/bits"
	"os"
	"sort"
)

type pstNode struct {
	l, r   int
	lo, ro *pstNode
	sum    int
}
type pSegmentTree struct {
	nodes        []pstNode
	versionRoots []*pstNode
}

func newPST(n int) *pSegmentTree {
	maxNodeSize := n * (3 + bits.Len(uint(n)))
	return &pSegmentTree{
		make([]pstNode, 0, maxNodeSize),
		make([]*pstNode, 1, n+1),
	}
}

func (t *pSegmentTree) _build(l, r int) *pstNode {
	t.nodes = append(t.nodes, pstNode{l: l, r: r})
	o := &t.nodes[len(t.nodes)-1]
	if l == r {
		return o
	}
	mid := (l + r) >> 1
	o.lo = t._build(l, mid)
	o.ro = t._build(mid+1, r)
	return o
}

func (t *pSegmentTree) _update(o *pstNode, idx int) *pstNode {
	t.nodes = append(t.nodes, *o)
	o = &t.nodes[len(t.nodes)-1]
	if o.l == o.r {
		o.sum++
		return o
	}
	if idx <= o.lo.r {
		o.lo = t._update(o.lo, idx)
	} else {
		o.ro = t._update(o.ro, idx)
	}
	o.sum = o.lo.sum + o.ro.sum
	return o
}

func (t *pSegmentTree) _queryKth(o1, o2 *pstNode, k int) (idx int) {
	if o1.l == o1.r {
		return o1.l
	}
	if d := o2.lo.sum - o1.lo.sum; d >= k {
		return t._queryKth(o1.lo, o2.lo, k)
	} else {
		return t._queryKth(o1.ro, o2.ro, k-d)
	}
}

func (t *pSegmentTree) init(n int) {
	t.versionRoots[0] = t._build(1, n)
}

func (t *pSegmentTree) update(baseVersion int, idx int) {
	t.versionRoots = append(t.versionRoots, t._update(t.versionRoots[baseVersion], idx))
}

func (t *pSegmentTree) queryKth(l, r int, k int) (idx int) {
	return t._queryKth(t.versionRoots[l-1], t.versionRoots[r], k)
}

// github.com/EndlessCheng/codeforces-go
func Sol1262D2(reader io.Reader, writer io.Writer) {
	in := bufio.NewScanner(reader)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(writer)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}

	n := read()
	a := make([]int, n)
	type pair struct{ val, i int }
	ps := make([]pair, n)
	for i := range ps {
		a[i] = read()
		ps[i] = pair{a[i], i}
	}
	sort.Slice(ps, func(i, j int) bool {
		return ps[i].val > ps[j].val || ps[i].val == ps[j].val && ps[i].i < ps[j].i
	})
	st := newPST(n)
	st.init(n)
	for i, p := range ps {
		st.update(i, p.i+1)
	}

	for m := read(); m > 0; m-- {
		idx := st.queryKth(1, read(), read()) - 1
		Fprintln(out, a[idx])
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go

type node struct {
	l, r   int
	lo, ro *node
	sum    int
}
type pst []*node

func (t pst) _build(l, r int) *node {
	o := &node{l: l, r: r}
	if l == r {
		return o
	}
	m := (l + r) >> 1
	o.lo = t._build(l, m)
	o.ro = t._build(m+1, r)
	return o
}

func (t pst) _update(o *node, idx int) *node {
	tmp := *o
	o = &tmp
	if o.l == o.r {
		o.sum++
		return o
	}
	if idx <= o.lo.r {
		o.lo = t._update(o.lo, idx)
	} else {
		o.ro = t._update(o.ro, idx)
	}
	o.sum = o.lo.sum + o.ro.sum
	return o
}

func (t pst) _queryKth(o1, o2 *node, k int) (idx int) {
	if o1.l == o1.r {
		return o1.l
	}
	if d := o2.lo.sum - o1.lo.sum; d >= k {
		return t._queryKth(o1.lo, o2.lo, k)
	} else {
		return t._queryKth(o1.ro, o2.ro, k-d)
	}
}

func (t pst) init(n int)                     { t[0] = t._build(1, n) }
func (t pst) update(ver, idx int)            { t[ver+1] = t._update(t[ver], idx) }
func (t pst) queryKth(l, r, k int) (idx int) { return t._queryKth(t[l-1], t[r], k) }

func CF1262D2(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type pair struct{ v, i int }

	var n, m, k, p int
	Fscan(in, &n)
	a := make([]int, n)
	ps := make([]pair, n)
	for i := range ps {
		Fscan(in, &a[i])
		ps[i] = pair{a[i], i}
	}

	sort.Slice(ps, func(i, j int) bool { a, b := ps[i], ps[j]; return a.v > b.v || a.v == b.v && a.i < b.i })
	t := make(pst, n+1)
	t.init(n)
	for i, p := range ps {
		t.update(i, p.i+1)
	}
	for Fscan(in, &m); m > 0; m-- {
		Fscan(in, &k, &p)
		Fprintln(out, a[t.queryKth(1, k, p)-1])
	}
}

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


package main

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

type Pair struct{ first, second int64 }

const (
	maxn int   = 2001
	MOD  int64 = 1000000007
)

type PointList []Pair

var p []Pair

var height, width, n int

func (s PointList) Len() int { return n }

func (s PointList) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func (p PointList) Less(i, j int) bool {
	return (p[i].first < p[j].first) || (p[i].first == p[j].first && p[i].second < p[j].second)
}

var (
	D     [maxn]int64
	fac   [200001]int64
	power [200001]int64
)

func initialize() {
	fac[0] = 1
	power[0] = 1
	for i := 1; i < 200001; i++ {
		fac[i] = (fac[i-1] * int64(i)) % MOD
		power[i] = power_mod(fac[i], MOD-2, MOD)
	}
}

func power_mod(a, b, c int64) int64 {
	if b == 1 {
		return a % c
	} else {
		var half_power int64 = power_mod(a, b/2, c)
		var res int64 = (half_power * half_power) % c
		if b%2 == 1 {
			res = (res * a) % c
		}
		return res
	}
}

func C(k, n int64) int64 {
	// n! * (n-k)!^(MOD-2) * (k!)^(MOD-2)
	return (((fac[n] * power[n-k]) % MOD) * power[k]) % MOD
}

func way_count(height, width int64) int64 {
	return C(width, width+height)
}

func main() {
	// f, _ := os.Open("input.txt")
	f := os.Stdin
	fmt.Fscanf(f, "%d %d %d\n", &height, &width, &n)
	initialize()
	p = make([]Pair, n+1)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%d %d\n", &p[i].first, &p[i].second)
	}

	p[n] = Pair{first: int64(height), second: int64(width)}
	n += 1
	sort.Sort(PointList(p))
	for i := 0; i < n; i++ {
		var res int64 = way_count(p[i].first-1, p[i].second-1)

		for j := 0; j < i; j++ {
			if p[i].first < p[j].first || p[i].second < p[j].second {
				continue
			}
			res -= (D[j] * way_count(p[i].first-p[j].first, p[i].second-p[j].second)) % MOD
			res = (res + MOD) % MOD
		}
		D[i] = res
	}
	fmt.Println(D[n-1])
}

package main

import (
	"fmt"
	"sort"
)

type Point struct {
	Column int
	Row    int
}

type Points []Point

func (collection Points) Len() int {

	return len(collection)
}

func (collection Points) Swap(i, j int) {

	collection[i], collection[j] = collection[j], collection[i]
}

func (collection Points) Less(i, j int) bool {

	if collection[i].Column == collection[j].Column {

		return collection[i].Row < collection[j].Row
	}

	return collection[i].Column < collection[j].Column
}

var factorials [100005*2]int64
var reverse_factorials [100005*2]int64

func power(a, base int64) int64 {

	var result int64
	result = 1

	for base > 0 {
		if base%2 == 0 {

			a = a * a % 1000000007
			base = base / 2

		} else {

			base = base - 1
			result = result * a % 1000000007

		}
	}

	return result
}

func choose(k, n int) int64 {

	result := int64(1)

	result *= factorials[n]
	result *= reverse_factorials[k]
	result %= int64(1000000007)
	result *= reverse_factorials[n-k]
	result %= int64(1000000007)

	return result
}

func main() {

	var h, w, n int

	fmt.Scan(&h, &w, &n)

	//fmt.Println(h)
	//fmt.Println(w)
	//fmt.Println(n)

	points := make([]Point, n+1)

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

		fmt.Scan(&points[i].Row, &points[i].Column)
	}

	points[n].Row = h
	points[n].Column = w

	sort.Sort(Points(points))

	//fmt.Println(points);

	for i := range factorials {

		if i == 0 {
			factorials[i] = 1
		} else {
			factorials[i] = int64(i) * factorials[i-1] % 1000000007
		}
	}

	for i := range factorials {

		reverse_factorials[i] = power(factorials[i], 1000000007-2)
	}

	result := make([]int64, n+1)

	if points[0].Row > 0 && points[0].Column > 0 {

		result[0] = choose(points[0].Row-1, points[0].Row+points[0].Column-2)
	} else {

		result[0] = 1
	}

	for i := 1; i <= n; i++ {

		//fmt.Printf("\n")
		//fmt.Printf("Step i = %d\n", i)

		r_offset := points[i].Row - 1
		c_offset := points[i].Column - 1

		total := int64(0);

		if r_offset > 0 && c_offset > 0 {

			//fmt.Printf("Step r_offset = %d\n", r_offset)
			//fmt.Printf("Step c_offset = %d\n", c_offset)

			total = choose(r_offset, r_offset+c_offset)

		} else {
			total = 1
		}

		bad := int64(0)

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

			r := points[i].Row - points[from].Row
			c := points[i].Column - points[from].Column

			if r >= 0 && c >= 0 {

				//fmt.Printf("r = %d\n", r)
				//fmt.Printf("c = %d\n", c)
				//fmt.Printf("amt = %d\n", choose(r, r+c))

				bad = bad + result[from]*choose(r, r+c)
				bad = bad % 1000000007
			}
		}

		value := (total - bad + 1000000007) % 1000000007

		//fmt.Printf("Total = %d\n", total)
		//fmt.Printf("Bad = %d\n", bad)

		result[i] = value
	}

	fmt.Println(result[n])

}

package main

import (
	"fmt"
	"sort"
)

type Point struct {
	Column int
	Row    int
}

type Points []Point

func (collection Points) Len() int {

	return len(collection)
}

func (collection Points) Swap(i, j int) {

	collection[i], collection[j] = collection[j], collection[i]
}

func (collection Points) Less(i, j int) bool {

	if collection[i].Column == collection[j].Column {

		return collection[i].Row < collection[j].Row
	}

	return collection[i].Column < collection[j].Column
}

var factorials [100005]int64
var reverse_factorials [100005]int64

func power(a, base int64) int64 {

	var result int64
	result = 1

	for base > 0 {
		if base%2 == 0 {

			a = a * a % 1000000007
			base = base / 2

		} else {

			base = base - 1
			result = result * a % 1000000007

		}
	}

	return result
}

func choose(k, n int) int64 {

	return factorials[n] * reverse_factorials[k] % 1000000007 * reverse_factorials[n-k] % 1000000007
}

func main() {

	var h, w, n int

	fmt.Scan(&h, &w, &n)

	fmt.Println(h)
	fmt.Println(w)
	fmt.Println(n)

	points := make([]Point, n+1)

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

		fmt.Scan(&points[i].Row, &points[i].Column)
	}

	points[n].Row = h
	points[n].Column = w

	sort.Sort(Points(points))

	fmt.Println(points);

	for i := range factorials {

		if i == 0 {
			factorials[i] = 1
		} else {
			factorials[i] = int64(i) * factorials[i-1] % 1000000007
		}
	}

	for i := range factorials {

		reverse_factorials[i] = power(factorials[i], 1000000007-2)
	}

	result := make([]int64, n+1)

	if points[0].Row > 0 && points[0].Column > 0 {

		result[0] = choose(points[0].Row-1, points[0].Row+points[0].Column-2)
	} else {

		result[0] = 1
	}

	for i := 1; i <= n; i++ {

		//fmt.Printf("\n")
		//fmt.Printf("Step i = %d\n", i)

		r_offset := points[i].Row - 1
		c_offset := points[i].Column - 1

		total := int64(0);

		if r_offset > 0 && c_offset > 0 {
			total = choose(r_offset, r_offset+c_offset)
		} else {
			total = 1
		}

		bad := int64(0)

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

			r := points[i].Row - points[from].Row
			c := points[i].Column - points[from].Column

			if r >= 0 && c >= 0 {

				//fmt.Printf("r = %d\n", r)
				//fmt.Printf("c = %d\n", c)
				//fmt.Printf("amt = %d\n", choose(r, r+c))

				bad = bad + result[from]*choose(r, r+c)
				bad = bad % 1000000007
			}
		}

		value := (total - bad + 1000000007) % 1000000007

		//fmt.Printf("Total = %d\n", total)
		//fmt.Printf("Bad = %d\n", bad)

		result[i] = value
	}

	fmt.Println(result[n])

}

package main

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

type Pair struct{ first, second int64 }

const (
	maxn int   = 2001
	MOD  int64 = 1000000007
)

type PointList [maxn]Pair

var p PointList

func (s PointList) Len() int {
	return len(s)
}

func (s PointList) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (p PointList) Less(i, j int) bool {
	return (p[i].first < p[j].first) || (p[i].first == p[j].first && p[i].second < p[j].second)
}

var (
	D   [maxn]int64
	fac [200001]int64
)

func initialize() {
	fac[0] = 1
	for i := 1; i < 200001; i++ {
		fac[i] = (fac[i-1] * int64(i)) % MOD
	}
}

func power_mod(a, b, c int64) int64 {
	if b == 1 {
		return a % c
	} else {
		var half_power int64 = power_mod(a, b/2, c)
		var res int64 = (half_power * half_power) % MOD
		if b%2 == 1 {
			res = (res * a) % MOD
		}
		return res
	}
}

func C(k, n int64) int64 {
	return (fac[n] * power_mod((fac[n-k]*fac[k])%MOD, MOD-2, MOD)) % MOD
}

func way_count(height, width int64) int64 {
	return C(width, width+height)
}

func main() {
	// f, _ := os.Open("input.txt")
	f := os.Stdin
	var height, width, n int
	fmt.Fscanf(f, "%d %d %d\n", &height, &width, &n)
	initialize()
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%d %d\n", &p[i].first, &p[i].second)
	}

	p[n] = Pair{first: int64(height), second: int64(width)}
	n += 1
	sort.Sort(p)

	for i := 0; i < n; i++ {
		var res int64 = way_count(p[i].first-1, p[i].second-1)

		for j := 0; j < i; j++ {
			if p[i].first < p[j].first || p[i].second < p[j].second {
				continue
			}
			res -= (D[j] * way_count(p[i].first-p[j].first, p[i].second-p[j].second)) % MOD
			res = (res + MOD) % MOD
		}
		D[i] = res
	}
	fmt.Println(D[n-1])
}

package main

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

type Pair struct{ first, second int64 }

const (
	maxn int   = 2001
	MOD  int64 = 1000000007
)

type PointList [maxn]Pair

var p PointList

func (s PointList) Len() int {
	return len(s)
}

func (s PointList) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (p PointList) Less(i, j int) bool {
	return (p[i].first < p[j].first) || (p[i].first == p[j].first && p[i].second < p[j].second)
}

var (
	D   [maxn]int64
	fac [200001]int64
)

func initialize() {
	fac[0] = 1
	for i := 1; i < 200001; i++ {
		fac[i] = (fac[i-1] * int64(i)) % MOD
	}
}

func power_mod(a, b, c int64) int64 {
	if b == 1 {
		return a % c
	} else {
		var half_power int64 = power_mod(a, b/2, c)
		var res int64 = (half_power * half_power) % c
		if b%2 == 1 {
			res = (res * a) % c
		}
		return res
	}
}

func C(k, n int64) int64 {
	return (fac[n] * power_mod((fac[n-k]*fac[k])%MOD, MOD-2, MOD)) % MOD
}

func way_count(height, width int64) int64 {
	return C(width, width+height)
}

func main() {
	// f, _ := os.Open("input.txt")
	f := os.Stdin
	var height, width, n int
	fmt.Fscanf(f, "%d %d %d\n", &height, &width, &n)
	initialize()
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%d %d\n", &p[i].first, &p[i].second)
	}

	p[n] = Pair{first: int64(height), second: int64(width)}
	n += 1
	sort.Sort(p)

	for i := 0; i < n; i++ {
		var res int64 = way_count(p[i].first-1, p[i].second-1)

		for j := 0; j < i; j++ {
			if p[i].first < p[j].first || p[i].second < p[j].second {
				continue
			}
			res -= (D[j] * way_count(p[i].first-p[j].first, p[i].second-p[j].second)) % MOD
			res = (res + MOD) % MOD
		}
		D[i] = res
	}
	fmt.Println(D[n-1])
}


package main

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

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	pair_count := int64(0)
	s_map := make(map[string]int)
	x_map := make(map[int]map[int]int)
	y_map := make(map[int]map[int]int)

	reader := bufio.NewReader(os.Stdin)
	re := regexp.MustCompile(`\r?\n`)
	for i := 0; i < n; i++ {
		if s, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			} else {
				return
			}
		} else {
			s = re.ReplaceAllString(s, "")

			xy := strings.Split(s, " ")
			a, err := strconv.Atoi(xy[0])
			if err != nil {
				return
			}
			b, err := strconv.Atoi(xy[1])
			if err != nil {
				return
			}

			if s_map[s] > 0 {
				pair_count += int64(s_map[s])
			}
			s_map[s] += 1
			if x_map[a] == nil {
				x_map[a] = make(map[int]int)
			}
			x_map[a][b] += 1
			if y_map[b] == nil {
				y_map[b] = make(map[int]int)
			}
			y_map[b][a] += 1
		}
	}

	bf := make([]int, n)
	bl := 0

	for _, xm := range x_map {
		if len(xm) > 1 {
			bl = 0
			for _, c := range xm {
				if bl == 0 {
					bf[0] = c
				} else {
					pair_count += int64(bf[bl-1]) * int64(c)
					bf[bl] = bf[bl-1] + c
				}
				bl++
			}
		}
	}

	for _, ym := range y_map {
		if len(ym) > 1 {
			bl = 0
			for _, c := range ym {
				if bl == 0 {
					bf[0] = c
				} else {
					pair_count += int64(bf[bl-1]) * int64(c)
					bf[bl] = bf[bl-1] + c
				}
				bl++
			}
		}
	}

	fmt.Println(pair_count)
}

package main

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

type point struct {
	x int
	y int
}

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

	mx := make(map[int]int)
	my := make(map[int]int)
	mp := make(map[point]int)
	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		bs.Scan()
		x, _ := strconv.Atoi(bs.Text())
		bs.Scan()
		y, _ := strconv.Atoi(bs.Text())

		//if _, ok := mx[x]; ok {
		//		mx[x]++
		//	} else {
		//		mx[x] = 1
		//	}
		mx[x]++

		if _, ok := my[y]; ok {
			my[y]++
		} else {
			my[y] = 1
		}
		//my[y]++

		pt := point{x, y}
		if _, ok := mp[pt]; ok {
			mp[pt]++
		} else {
			mp[pt] = 1
		}
		//mp[pt]++
	}

	var ans uint64
	ans = 0
	for _, v := range mx {
		if v > 1 {
			ans += uint64(v) * uint64(v-1) / 2
		}
	}
	for _, v := range my {
		if v > 1 {
			ans += uint64(v) * uint64(v-1) / 2
		}
	}

	for _, v := range mp {
		if v > 1 {
			ans -= uint64(v) * uint64(v-1) / 2
		}
	}

	fmt.Println(ans)
}

package main

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

type point struct {
	x int
	y int
}

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

	mx := make(map[int]int)
	my := make(map[int]int)
	mp := make(map[point]int)
	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		bs.Scan()
		x, _ := strconv.Atoi(bs.Text())
		bs.Scan()
		y, _ := strconv.Atoi(bs.Text())

		//if _, ok := mx[x]; ok {
		//		mx[x]++
		//	} else {
		//		mx[x] = 1
		//	}
		mx[x]++

		//if _, ok := my[y]; ok {
		//	my[y]++
		//} else {
		//	my[y] = 1
		//}
		my[y]++

		pt := point{x, y}
		//if _, ok := mp[pt]; ok {
		//	mp[pt]++
		//} else {
		//	mp[pt] = 1
		//}
		mp[pt]++
	}

	var ans uint64
	ans = 0
	for _, v := range mx {
		if v > 1 {
			ans += uint64(v) * uint64(v-1) / 2
		}
	}
	for _, v := range my {
		if v > 1 {
			ans += uint64(v) * uint64(v-1) / 2
		}
	}

	for _, v := range mp {
		if v > 1 {
			ans -= uint64(v) * uint64(v-1) / 2
		}
	}

	fmt.Println(ans)
}

package main

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

type Pair struct {
	first, second int
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(in, "%d\n", &n)
	ver := make(map[int]int64)
	hor := make(map[int]int64)
	p := make(map[Pair]int64)
	for i := 0; i < n; i++ {
		var x, y int
		fmt.Fscanf(in, "%d %d\n", &x, &y)
		ver[x] += 1
		hor[y] += 1
		p[Pair{x, y}] += 1
	}
	var ans int64
	for _, v := range hor {
		ans += v * (v - 1) / 2
	}
	for _, v := range ver {
		ans += v * (v - 1) / 2
	}
	for _, v := range p {
		ans -= v * (v - 1) / 2
	}
	fmt.Println(ans)
}

package main

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

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

	var n, x, y int
	Fscan(in, &n)
	rows, cols := map[int]int{}, map[int]int{}
	cnts := map[[2]int]int{}
	ans := int64(0)
	for ; n > 0; n-- {
		Fscan(in, &x, &y)
		p := [2]int{x, y}
		ans += int64(rows[y] + cols[x] - cnts[p])
		rows[y]++
		cols[x]++
		cnts[p]++
	}
	Fprint(out, ans)
}

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

package main

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

var (
	sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr *bufio.Writer  = bufio.NewWriter(os.Stdout)
)

func readInt() int64 {
	sc.Scan()
	ans, _ := strconv.ParseInt(sc.Text(), 10, 64)
	return ans
}

func printInts(ints ...int64) {
	for _, v := range ints {
		wr.WriteString(strconv.FormatInt(v, 10))
		wr.WriteByte(' ')
	}
}

func println() {
	wr.WriteByte('\n')
}

type pt struct {
	x, y int64
}

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)

	var n int64 = readInt()

	cols := make(map[int64]int64)
	rows := make(map[int64]int64)
	set := make(map[pt]int64)
	for i := int64(0); i < n; i++ {
		x, y := readInt(), readInt()
		if _, prs := cols[x]; prs {
			cols[x] = cols[x] + 1
		} else {
			cols[x] = 1
		}
		if _, prs := rows[y]; prs {
			rows[y] = rows[y] + 1
		} else {
			rows[y] = 1
		}
		p := pt{x, y}
		if _, prs := set[p]; prs {
			set[p] = set[p] + 1
		} else {
			set[p] = 1
		}
	}
	var r int64
	for _, v := range rows {
		r += v * (v - 1) / 2
	}
	for _, v := range cols {
		r += v * (v - 1) / 2
	}
	for _, v := range set {
		if v > 1 {
			r -= v * (v - 1) / 2
		}
	}
	printInts(r)
	println()
}

package main

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

type Pair struct {
	first, second int
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(in, "%d\n", &n)
	ver := make(map[int]int64)
	hor := make(map[int]int64)
	p := make(map[int64]int64)
	for i := 0; i < n; i++ {
		var x, y int
		fmt.Fscanf(in, "%d %d\n", &x, &y)
		ver[x] += 1
		hor[y] += 1
		p[int64(x)*1000000000+int64(y)] += 1
		//p[Pair{x, y}] += 1
	}
	var ans int64
	for _, v := range hor {
		ans += v * (v - 1) / 2
	}
	for _, v := range ver {
		ans += v * (v - 1) / 2
	}
	for _, v := range p {
		ans -= v * (v - 1) / 2
	}
	fmt.Println(ans)
}

package main

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

type point struct {
	x int
	y int
}

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

	mx := make(map[int]int)
	my := make(map[int]int)
	mp := make(map[point]int)
	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		bs.Scan()
		x, _ := strconv.Atoi(bs.Text())
		bs.Scan()
		y, _ := strconv.Atoi(bs.Text())

		if _, ok := mx[x]; ok {
			mx[x]++
		} else {
			mx[x] = 1
		}
		//mx[x]++

		if _, ok := my[y]; ok {
			my[y]++
		} else {
			my[y] = 1
		}

		pt := point{x, y}
		if _, ok := mp[pt]; ok {
			mp[pt]++
		} else {
			mp[pt] = 1
		}
	}

	var ans uint64
	ans = 0
	for _, v := range mx {
		if v > 1 {
			ans += uint64(v) * uint64(v-1) / 2
		}
	}
	for _, v := range my {
		if v > 1 {
			ans += uint64(v) * uint64(v-1) / 2
		}
	}

	for _, v := range mp {
		if v > 1 {
			ans -= uint64(v) * uint64(v-1) / 2
		}
	}

	fmt.Println(ans)
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var n int
	var x, y int64

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

	X := make(map[int64]int64)
	Y := make(map[int64]int64)
	Z := make(map[int64]int64)

	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %d\n", &x, &y)
		X[x]++
		Y[y]++

		z := x<<32 + y
		Z[z]++
	}

	var m int64
	for _, v := range X {
		if v > 1 {
			m += v * (v - 1) / 2
		}
	}
	for _, v := range Y {
		if v > 1 {
			m += v * (v - 1) / 2
		}
	}

	for _, v := range Z {
		if v > 1 {
			m -= v * (v - 1) / 2
		}
	}

	fmt.Println(m)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	mul := 1
	for _, b := range in.Bytes() {
		if b == '-' {
			mul *= -1
			continue
		}
		res = res*10 + int(b-'0')
	}
	return mul * res
}

func main() {
	in.Split(bufio.ScanWords)
	var res int64
	mx := make(map[int]int)
	my := make(map[int]int)
	mxy := make(map[[2]int]int)

	n := readInt()
	for i := 0; i < n; i++ {
		x := readInt()
		y := readInt()
		xy := [2]int{x, y}
		res += int64(mx[x] + my[y] - mxy[xy])
		mx[x]++
		my[y]++
		mxy[xy]++
	}
	fmt.Println(res)
}

package main

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

var (
	sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr *bufio.Writer  = bufio.NewWriter(os.Stdout)
)

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

func printInts(ints ...int) {
	for _, v := range ints {
		wr.WriteString(strconv.Itoa(v))
		wr.WriteByte(' ')
	}
}

func println() {
	wr.WriteByte('\n')
}

type pt struct {
	x, y int
}

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)

	var n int = readInt()

	cols := make(map[int]int)
	rows := make(map[int]int)
	set := make(map[pt]int)
	for i := 0; i < n; i++ {
		x, y := readInt(), readInt()
		if _, prs := cols[x]; prs {
			cols[x] = cols[x] + 1
		} else {
			cols[x] = 1
		}
		if _, prs := rows[y]; prs {
			rows[y] = rows[y] + 1
		} else {
			rows[y] = 1
		}
		p := pt{x, y}
		if _, prs := set[p]; prs {
			set[p] = set[p] + 1
		} else {
			set[p] = 1
		}
	}
	var r int
	for _, v := range rows {
		r += v * (v - 1) / 2
	}
	for _, v := range cols {
		r += v * (v - 1) / 2
	}
	for _, v := range set {
		if v > 1 {
			r -= v * (v - 1) / 2
		}
	}
	printInts(r)
	println()
}

package main

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

type Pair struct {
	first, second int
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(in, "%d\n", &n)
	if n > 100000 {
		for i := 0; i < n; i++ {
			var x, y int
			fmt.Fscanf(in, "%d %d\n", &x, &y)
			//fmt.Scanf("%d %d\n", &x, &y)
		}
		return
	}
	ver := make(map[int]int64)
	hor := make(map[int]int64)
	p := make(map[int64]int64)
	for i := 0; i < n; i++ {
		var x, y int
		fmt.Fscanf(in, "%d %d\n", &x, &y)
		ver[x] += 1
		hor[y] += 1
		p[int64(x)*1000000000+int64(y)] += 1
		//p[Pair{x, y}] += 1
	}
	var ans int64
	for _, v := range hor {
		ans += v * (v - 1) / 2
	}
	for _, v := range ver {
		ans += v * (v - 1) / 2
	}
	for _, v := range p {
		ans -= v * (v - 1) / 2
	}
	fmt.Println(ans)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

func main() {
	in.Split(bufio.ScanWords)
	var res int64
	mx := make(map[int]int)
	my := make(map[int]int)
	mxy := make(map[[2]int]int)

	n := readInt()
	for i := 0; i < n; i++ {
		x := readInt()
		y := readInt()
		xy := [2]int{x, y}
		res += int64(mx[x] + my[y] - mxy[xy])
		mx[x]++
		my[y]++
		mxy[xy]++
	}
	fmt.Println(res)
}

package main

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

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	s_map := make(map[string]int)
	x_map := make(map[int]map[int]int)
	y_map := make(map[int]map[int]int)

	reader := bufio.NewReader(os.Stdin)
	re := regexp.MustCompile(`\r?\n`)
	for i := 0; i < n; i++ {
		if s, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			} else {
				return
			}
		} else {
			s = re.ReplaceAllString(s, "")

			xy := strings.Split(s, " ")
			a, err := strconv.Atoi(xy[0])
			if err != nil {
				return
			}
			b, err := strconv.Atoi(xy[1])
			if err != nil {
				return
			}

			s_map[s] += 1
			if x_map[a] == nil {
				x_map[a] = make(map[int]int)
			}
			x_map[a][b] += 1
			if y_map[b] == nil {
				y_map[b] = make(map[int]int)
			}
			y_map[b][a] += 1
		}
	}

	pair_count := 0
	bf := make([]int, n)
	bl := 0

	for _, xm := range x_map {
		if len(xm) > 1 {
			bl = 0
			for _, c := range xm {
				for i := 0; i < bl; i++ {
					pair_count += bf[i] * c
				}

				bf[bl] = c
				bl++
			}
		}
	}

	for _, ym := range y_map {
		if len(ym) > 1 {
			bl = 0
			for _, c := range ym {
				for i := 0; i < bl; i++ {
					pair_count += bf[i] * c
				}

				bf[bl] = c
				bl++
			}
		}
	}

	for _, c := range s_map {
		if c > 1 {
			pair_count += c * (c - 1) / 2
		}
	}

	fmt.Println(pair_count)
}

package main

import (
	"bytes"
	"fmt"
)

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

	X := make(map[int]int)
	Y := make(map[int]int)
	Z := make(map[string]int)

	for i := 0; i < n; i++ {
		fmt.Scanf("%d %d\n", &x, &y)
		X[x]++
		Y[y]++

		var buf bytes.Buffer
		fmt.Fprintf(&buf, "%d,%d", x, y)
		Z[buf.String()]++
	}

	var m int
	for _, v := range X {
		if v > 1 {
			m += v * (v - 1) / 2
		}
	}
	for _, v := range Y {
		if v > 1 {
			m += v * (v - 1) / 2
		}
	}

	for _, v := range Z {
		if v > 1 {
			m -= (v - 1)
		}
	}

	fmt.Println(m)
}


package main

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

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

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

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

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

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

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

type Solver struct {
	m map[int64]bool
	k map[int64]int64
}

func (s *Solver) Add(n int64) {
	s.m[n] = true
}

func (s *Solver) KMex(n int64) int64 {
	from := n
	if prev, ok := s.k[n]; ok {
		from = prev
	}
	for {
		if !s.m[from] {
			s.k[n] = from
			return from
		}
		from += n
	}
}

func main() {
	defer writer.Flush()
	s := &Solver{
		m: map[int64]bool{},
		k: map[int64]int64{},
	}
	for q := _int(); q > 0; q-- {
		op := _string()
		n := _int64()
		if op == "+" {
			s.Add(n)
		} else {
			printf("%d\n", s.KMex(n))
		}
	}
}

package main

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

const cf = true

func solve() {
	var q int
	fmt.Fscan(in, &q)
	var set set[int]
	var query string
	var val int
	cache := make(map[int]int)
	for i := 0; i < q; i++ {
		fmt.Fscan(in, &query, &val)
		if query == "+" {
			set.add(val)
		} else {
			cur, ok := cache[val]
			if !ok {
				cur = val
			}
			for set.has(cur) {
				cur += val
			}
			fmt.Fprintln(out, cur)
			cache[val] = cur
		}
	}
}

func main() {
	defer out.Flush()
	t := 1
	//fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

func LCM(a, b int) int {
	return a * b / GCD(a, b)
}

func GCD(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}

	return a
}

type SqrtInt interface {
	SignedSqrt | UnsignedSqrt
}

type SignedSqrt interface {
	~int | ~int32 | ~int64
}

type UnsignedSqrt interface {
	~uint | ~uint32 | ~uint64 | ~uintptr
}

func sqrt[T SqrtInt](x T) T {
	l, r := T(0), T(2000000123)
	for l < r {
		mid := (l + r) / 2
		if mid*mid > x {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return l - 1
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

type set[T Ordered] struct {
	itms map[T]struct{}
}

func (s *set[T]) init() {
	if s.itms == nil {
		s.itms = make(map[T]struct{})
	}
}

func (s *set[T]) add(item T) *set[T] {
	s.init()
	s.itms[item] = exists
	return s
}

func (s *set[T]) remove(item T) *set[T] {
	s.init()
	delete(s.itms, item)
	return s
}

func (s *set[T]) has(item T) bool {
	s.init()
	_, c := s.itms[item]
	return c
}

func (s *set[T]) sortedItems() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	sort.Slice(items, func(i, j int) bool {
		return items[i] < items[j]
	})
	return items
}

func (s *set[T]) items() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	return items
}

func (s *set[T]) size() int {
	s.init()
	return len(s.itms)
}

var exists = struct{}{}

const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1

func reverseStr(s string) string {
	r := []byte(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

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

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

	var q int
	var x int64
	var op string
	Fscan(in, &q)
	mex := map[int64]int64{}
	has := map[int64]bool{}
	for qi := 1; qi <= q; qi++ {
		Fscan(in, &op, &x)
		if op == "+" {
			has[x] = true
		} else {
			if mex[x] == 0 {
				mex[x] = x
			}
			for has[mex[x]] {
				mex[x] += x
			}
			Fprintln(out, mex[x])
		}
	}
}

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