In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.

Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.

NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field.

package main

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

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1<<13)
	writer := bufio.NewWriterSize(os.Stdout, 1<<13)

	var n int
	var str string
	fmt.Fscan(reader, &n, &str)

	count := 0
	for i := 0; i < n; i++ {
		if str[i] == '>' {
			break
		}
		count++
	}

	for i := n - 1; i >= 0; i-- {
		if str[i] == '<' {
			break
		}
		count++
	}

	fmt.Fprintln(writer, count)
	writer.Flush()
}

func ReadInt(reader *bufio.Reader) int {
	b, err := reader.ReadByte()
	for !isValid(b, err) {
		b, err = reader.ReadByte()
	}
	res := 0
	for isValid(b, err) {
		res = res*10 + int(b-'0')
		b, err = reader.ReadByte()
	}
	return res
}

func isValid(b byte, err error) bool {
	return err == nil && (('0' <= b && b <= '9') || b == '<' || b == '>')
}

package main

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

func I(i interface{}, delim string) error {
	_, err := fmt.Fscanf(r, "%v"+delim, i)
	return err
}

func O(o interface{}, delim string) {
	fmt.Fprintf(w, "%v"+delim, o)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.txt"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	var n int
	for I(&n, "\n") == nil {
		solve(n)
	}
}

func solve(n int) {
	var s string
	I(&s, "\n")
	ans := 0
	for i := 0; i < n; i++ {
		if s[i] == '<' {
			ans++
		} else {
			break
		}
	}
	for i := n - 1; i >= 0; i-- {
		if s[i] == '>' {
			ans++
		} else {
			break
		}
	}
	O(ans, "\n")
}

package main

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

func solve() {
    n, s := readInt(), readString()
    i, j := 0, n - 1
    for i < n && s[i] == "<"[0] {
        i++;
    }
    for j >= 0 && s[j] == ">"[0] {
        j--;
    }

    fmt.Println(i-j+n-1)
}

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func main() {
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

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

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

func min(x, y int) int {
	return x + y - max(x, y)
}

// IO

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

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

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

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

package main

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

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

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

	var s string
	var n int
	fmt.Fscanf(bufin, "%d\n", &n)
	fmt.Fscanf(bufin, "%s\n", &s)

	res := 0
	for i := 0; (i < n) && (s[i] == '<'); i++ {
		res++
	}
	for i := (n - 1); (i >= 0) && (s[i] == '>'); i-- {
		res++
	}
	fmt.Fprintf(bufout, "%d\n", res)
}

package main

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

var (
  n, result int
  s string
  seen, leaves []bool
)

func explore(i int) bool {
  if i < 0 || i == n {
    return true
  }
  if seen[i] {
    return leaves[i]
  }
  seen[i] = true
  if s[i] == '<' {
    leaves[i] = explore(i - 1)
  } else {
    leaves[i] = explore(i + 1)
  }
  if leaves[i] {
    result++
  }
  return leaves[i]
}

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

  line, _ := reader.ReadString('\n')
  fmt.Sscanf(line, "%d", &n)
  line, _ = reader.ReadString('\n')
  s = strings.TrimSpace(line)
  seen = make([]bool, n)
  leaves = make([]bool, n)
  result = 0
  for i := range s {
    explore(i)
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

// http://acm.timus.ru/problem.aspx?space=1&num=1741
package main

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

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

const (
	MOD = 1e9 + 7
)

type (

)

func main () {
	var (
		n int
		str string
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)

	fmt.Fscanln(input, &n)
	fmt.Fscanln(input, &str)

	ans := 0

	for i := 0; i < n; i++ {
		if str[i] == '<' {
			ans++
		} else {
			break
		}
	}

	for i := n - 1; i >= 0; i-- {
		if str[i] == '>' {
			ans++
		} else {
			break
		}
	}

	fmt.Println(ans)
}

package main

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

import "strings"

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")

	text, _ = reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	total := 0
	for i := 0; i < len(text); i++ {
		if text[i] == '<' {
			total += 1
		} else {
			break
		}
	}
	for i := len(text) - 1; i >= 0; i-- {
		if text[i] != '>' {
			break
		}
		total += 1
	}
	fmt.Println(total)

}

package main

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

func I(i interface{}, delim string) error {
	_, err := fmt.Fscanf(r, "%v"+delim, i)
	return err
}

func O(o interface{}, delim string) {
	fmt.Fprintf(w, "%v"+delim, o)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.txt"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	var n int
	for I(&n, "\n") == nil {
		solve(n)
	}
}

func solve(n int) {
	var s string
	I(&s, "\n")
	o := strings.Count(s, ">") - strings.Count(s, "<")
	ans := o
	if o < 0 {
		ans = -o
	}
	O(ans, "\n")
}


In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$.A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel.You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$$$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \dots, r_n$$$ $$$(1 \le r_i \le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \le x, y \le n$$$, $$$x \ne y)$$$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.

Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.

NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 2048*2048), 2048*2048)
	scanner.Split(bufio.ScanWords)

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

	scanner.Scan()
	k, _ := strconv.Atoi(scanner.Text())

	r := make([]int, n)
	c := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		r[i], _ = strconv.Atoi(scanner.Text())
		c[i] = r[i]
	}

	sort.Ints(c)

	p := make([]int, n)

	for i := 0; i < k; i++ {
		scanner.Scan()
		x, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		y, _ := strconv.Atoi(scanner.Text())
		x--
		y--
		if r[x] > r[y] {
			p[x]++
		}
		if r[x] < r[y] {
			p[y]++
		}
	}

	for i := 0; i < n; i++ {
		pred := NewPred(r[i])
		l := 0
		h := n - 1
		for l < h {
			m := l + (h-l+1)/2
			if pred(c[m]) {
				h = m - 1
			} else {
				l = m
			}
		}
		if pred(c[l]) {
			fmt.Printf("%d ", 0)
			continue
		}
		//fmt.Println(l, r[i], i)
		fmt.Printf("%d ", l+1-p[i])
	}
	fmt.Println()
}

func NewPred(target int) func(int) bool {
	return func(x int) bool {
		return x >= target
	}
}

package main

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

type pro struct {
	pos int
	r int
	v int
}

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

	var n, k, u, v int
	fmt.Fscan(in, &n, &k)

	cnt := make([]int, n+1)
	p := make([]pro, n+1)

	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &u)
		p[i] = pro{i, u, 0}
	}
	for i := 0; i < k; i++ {
		fmt.Fscan(in, &u, &v)
		if p[u].r > p[v].r {
			cnt[u]++
		} else if p[u].r < p[v].r {
			cnt[v]++
		}
	}

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

	l, r := 1, 1
	for l <= n {
		for r <= n && p[l].r == p[r].r {
			r++
		}
		for i := l ; i < r; i++ {
			p[i].v = l-1 - cnt[p[i].pos]
		}
		l = r
	}

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

	fmt.Fprintf(out, "%d", p[1].v)
	for i := 2; i <= n; i++ {
		fmt.Fprintf(out, " %d", p[i].v)
	}
}

package main

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

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

	var n, m, v, w int
	Fscan(in, &n, &m)
	a := make([]int, n)
	g := make([][]int, n)
	for i := range a {
		Fscan(in, &a[i])
		g[i] = []int{a[i]}
	}
	for ; m > 0; m-- {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], a[w])
		g[w] = append(g[w], a[v])
	}
	for _, vs := range g {
		sort.Ints(vs)
	}
	b := make([]int, n)
	copy(b, a)
	sort.Ints(b)
	for i, v := range a {
		Fprint(out, sort.SearchInts(b, v)-sort.SearchInts(g[i], v), " ")
	}
}

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

package main

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

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

	var n, m, v, w int
	Fscan(in, &n, &m)
	a := make([]int, n)
	g := make([][]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	for ; m > 0; m-- {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], a[w])
		g[w] = append(g[w], a[v])
	}
	for _, vs := range g {
		sort.Ints(vs)
	}
	b := make([]int, n)
	copy(b, a)
	sort.Ints(b)
	for i, v := range a {
		Fprint(out, sort.SearchInts(b, v)-sort.SearchInts(g[i], v), " ")
	}
}

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

// Codeforces 911 C done
package main

import (
	"bufio"
	"fmt"
	"strings"
	"strconv"
	"os"
	"sort"
)
var in *bufio.Reader

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

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

type programmer struct {
	skill int
	idx int
	nLessEnemies int
}
type Progs []*programmer

var pros Progs
var proga []programmer

func (ps Progs) Len() int {
	return len(ps)
}
func (ps Progs) Less(i, j int) bool {
	return ps[i].skill < ps[j].skill
}
func (ps Progs) Swap(i, j int) {
	ps[i], ps[j] = ps[j], ps[i]
}

var n,k int
var r []int
var res []int

func readData() {
	in = bufio.NewReader(os.Stdin)
	// reading n, k
	n, k, _, _, _ = readFive()
	// reading r
	r = readLineNumbs(n)
	// creating programmers
	proga = make([]programmer, n)
	pros = make([]*programmer, n)
	res = make([]int, n)
	for i:=0; i<n; i++ {
		proga[i].skill = r[i]
		proga[i].nLessEnemies = 0
		proga[i].idx = i
		pros[i] = &(proga[i])
	}
	sort.Sort(pros)
	// reading quarels
	for i:=0; i<k; i++ {
		a,b,_,_,_ := readFive()
		a--; b--
		if proga[a].skill < proga[b].skill {
			proga[b].nLessEnemies++
		} else if proga[b].skill < proga[a].skill {
			proga[a].nLessEnemies++
		}
	}
}

func solve() {
	last := -1
	nLess := 0
	for i:=0; i<n; i++ {
		if pros[i].skill > last {
			nLess = i;
			last = pros[i].skill
		}
		res[pros[i].idx] = nLess - pros[i].nLessEnemies
	}
}

func printRes() {
	for i:=0; i<n; i++ {
		fmt.Print(" ", res[i])
	}
    fmt.Println()
}

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

package main

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

type prog struct {
	v, index int
}

var n, k int
var a []prog
var c []int
var ans []int

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(inBuf, "%d %d\n", &n, &k)
	a = make([]prog, n)
	c = make([]int, n)
	ans = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(inBuf, "%d", &a[i].v)
		a[i].index = i
	}
	fmt.Fscanf(inBuf, "\n")
	for i := 0; i < k; i++ {
		var t1, t2 int
		fmt.Fscanf(inBuf, "%d %d\n", &t1, &t2)
		t1--
		t2--
		if a[t1].v > a[t2].v {
			c[t1]++
		} else if a[t1].v < a[t2].v {
			c[t2]++
		}
	}
	sort.Slice(a, func(i, j int) bool {
		return a[i].v < a[j].v
	})
	for i := 0; i < n; i++ {
		ind := sort.Search(i, func(n int) bool {
			return a[n].v >= a[i].v
		})
		ans[a[i].index] = ind - c[a[i].index]
	}

	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	for i := 0; i < n; i++ {
		fmt.Printf("%d ", ans[i])
	}
}

package main

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

type pair struct {
	a, b int
}

type lol []pair

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

func (p lol) Less(xx, yy int) bool {
	x, y := p[xx], p[yy]
	if x.a != y.a {
		return x.a < y.a
	}

	return x.b < y.b
}

func (p lol) Swap(x, y int) {
	p[x], p[y] = p[y], p[x]
}

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

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

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

	qua := make([]pair, k)

	for i := 0; i < k; i++ {
		fmt.Fscan(in, &qua[i].a, &qua[i].b)
		qua[i].a--
		qua[i].b--
	}

	res := make([]int, n)
	for i := 0; i < k; i++ {
		a, b := qua[i].a, qua[i].b
		if skill[a] < skill[b] {
			res[b]--
		} else if skill[a] > skill[b] {
			res[a]--
		}
	}

	sorted := make([]pair, n)
	for i := 0; i < n; i++ {
		sorted[i] = pair{skill[i], i}
	}

	sort.Sort(lol(sorted))

	eq := 0
	v := -1
	for i := 0; i < n; i++ {
		ski, id := sorted[i].a, sorted[i].b
		if ski == v {
			eq++
		} else {
			eq = 0
		}

		res[id] += i - eq

		v = sorted[i].a
	}

	for i := 0; i < n; i++ {
		fmt.Fprint(out, res[i], " ")
	}
	fmt.Fprintln(out)

}

package main

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

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

	var n, m, v, w int
	Fscan(in, &n, &m)
	fa := make([]int, n)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(from, to int) { fa[find(from)] = find(to) }
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	b := make([]int, n)
	copy(b, a)
	sort.Ints(b)
	for ; m > 0; m-- {
		Fscan(in, &v, &w)
		merge(v-1, w-1)
	}
	g := make([][]int, n)
	for i, v := range a {
		f := find(i)
		g[f] = append(g[f], v)
	}
	for _, vs := range g {
		sort.Ints(vs)
	}
	for i, v := range a {
		vs := g[fa[i]]
		Fprint(out, sort.SearchInts(b, v)-sort.SearchInts(vs, v), " ")
	}
}

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


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 $$$x_i$$$ and $$$y_i$$$. They are also both given the same $$$m$$$ by $$$k$$$ grid of values $$$a_{ij}$$$ such that $$$m\cdot 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 $$$a_{ij}$$$ values that domino covers. Dominoes can be rotated arbitrarily before being placed on the grid, so the domino $$$(x_i, y_i)$$$ is equivalent to the domino $$$(y_i, x_i)$$$.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.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3\cdot 10^5$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le 2n$$$).

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\cdot k = 2n$$$. The $$$i$$$-th of the next $$$m$$$ lines should contain $$$k$$$ integers, the $$$j$$$-th of which is $$$a_{ij}$$$. 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.

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

NoteExtra blank lines are added to the output for clarity, but are not required.The third sample case corresponds to the image from the statement.

// 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))
	}
}


We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following:   Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?

The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$  — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case output the minimum number of operations needed.

NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.

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


This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$:  $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list);  $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if:  it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$;  and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t<c_t$$$. For example:  $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$,  $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$,  $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.

Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.

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


Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.

The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).  Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.

Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.

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"
	"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]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])
}


An array is called beautiful if all the elements in the array are equal.You can transform an array using the following steps any number of times:   Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i,j \leq n$$$), and an integer $$$x$$$ ($$$1 \leq x \leq a_i$$$). Let $$$i$$$ be the source index and $$$j$$$ be the sink index.  Decrease the $$$i$$$-th element by $$$x$$$, and increase the $$$j$$$-th element by $$$x$$$. The resulting values at $$$i$$$-th and $$$j$$$-th index are $$$a_i-x$$$ and $$$a_j+x$$$ respectively.  The cost of this operation is $$$x \cdot |j-i| $$$.  Now the $$$i$$$-th index can no longer be the sink and the $$$j$$$-th index can no longer be the source.  The total cost of a transformation is the sum of all the costs in step $$$3$$$.For example, array $$$[0, 2, 3, 3]$$$ can be transformed into a beautiful array $$$[2, 2, 2, 2]$$$ with total cost $$$1 \cdot |1-3| + 1 \cdot |1-4| = 5$$$.An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.You are given an array $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo $$$10^9 + 7$$$.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of the array.  The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).

Output a single integer — the number of balanced permutations modulo $$$10^9+7$$$.

NoteIn the first example, $$$[1, 2, 3]$$$ is a valid permutation as we can consider the index with value $$$3$$$ as the source and index with value $$$1$$$ as the sink. Thus, after conversion we get a beautiful array $$$[2, 2, 2]$$$, and the total cost would be $$$2$$$. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.In the second example, $$$[0, 0, 4, 4]$$$ and $$$[4, 4, 0, 0]$$$ are balanced permutations.In the third example, all permutations are balanced.

package main

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

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

	const mod int64 = 1e9 + 7
	const mx int = 3e5
	F := [mx + 1]int64{1}
	for i := 1; i <= mx; i++ {
		F[i] = F[i-1] * int64(i) % mod
	}
	pow := func(x, n int64) (res int64) {
		//x %= mod
		res = 1
		for ; n > 0; n >>= 1 {
			if n&1 == 1 {
				res = res * x % mod
			}
			x = x * x % mod
		}
		return res
	}
	invF := [...]int64{mx: pow(F[mx], mod-2)}
	for i := mx; i > 0; i-- {
		invF[i-1] = invF[i] * int64(i) % mod
	}
	C := func(n, k int) int64 {
		return F[n] * invF[k] % mod * invF[n-k] % mod
	}
	H := func(n, k int) int64 { return C(n+k-1, k) }

	inv := func(a int64) int64 { return pow(a, mod-2) }
	div := func(a, b int64) int64 { return a % mod * inv(b) % mod }

	var n, s int64
	Fscan(in, &n)
	a := make([]int64, n)
	for i := range a {
		Fscan(in, &a[i])
		s += a[i]
	}

	if s%n > 0 {
		Fprintln(out, 0)
		return
	}

	avg := s / n

	cnt := map[int64]int{}
	for _, v := range a {
		cnt[v]++
	}
	less := 0
	gr := 0
	for v, c := range cnt {
		if v < avg {
			less += c
		} else if v > avg {
			gr += c
		}
	}

	ans := int64(1)

	if less == 1 || gr == 1 {
		m := F[n]
		m2 := int64(1)
		for _, c := range cnt {
			m2 = m2 * F[c] % mod
		}
		m = div(m, m2)
		ans = m
	} else {
		ans = int64(2)

		m := F[less]
		m2 := int64(1)
		for v, c := range cnt {
			if v < avg {
				m2 = m2 * F[c] % mod
			}
		}
		m = div(m, m2)

		ans = ans * m % mod

		m = F[gr]
		m2 = int64(1)
		for v, c := range cnt {
			if v > avg {
				m2 = m2 * F[c] % mod
			}
		}
		m = div(m, m2)

		ans = ans * m % mod
		if c := cnt[avg]; c > 0 {
			if c == int(n) {
				Fprintln(out, 1)
				return
			}
			res := H(int(n)-c+1, c)
			ans = ans * res % mod
		}
	}

	Fprintln(out, ans)
}

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

package main

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

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

	const mod int64 = 1e9 + 7
	const mx int = 3e5
	F := [mx + 1]int64{1}
	for i := 1; i <= mx; i++ {
		F[i] = F[i-1] * int64(i) % mod
	}
	pow := func(x, n int64) (res int64) {
		//x %= mod
		res = 1
		for ; n > 0; n >>= 1 {
			if n&1 == 1 {
				res = res * x % mod
			}
			x = x * x % mod
		}
		return res
	}
	invF := [...]int64{mx: pow(F[mx], mod-2)}
	for i := mx; i > 0; i-- {
		invF[i-1] = invF[i] * int64(i) % mod
	}
	C := func(n, k int) int64 {
		return F[n] * invF[k] % mod * invF[n-k] % mod
	}
	H := func(n, k int) int64 { return C(n+k-1, k) }

	inv := func(a int64) int64 { return pow(a, mod-2) }
	div := func(a, b int64) int64 { return a % mod * inv(b) % mod }

	var n, s int64
	Fscan(in, &n)
	a := make([]int64, n)
	for i := range a {
		Fscan(in, &a[i])
		s += a[i]
	}

	if s%n > 0 {
		Fprintln(out, 0)
		return
	}

	avg := s / n

	cnt := map[int64]int{}
	for _, v := range a {
		cnt[v]++
	}
	less := 0
	gr := 0
	for v, c := range cnt {
		if v < avg {
			less += c
		} else if v > avg {
			gr += c
		}
	}

	ans := int64(1)

	if less == 1 || gr == 1 {
		ans = F[n]
	}  else {
		ans = int64(2)

		m := F[less]
		m2 := int64(1)
		for v, c := range cnt {
			if v < avg {
				m2 = m2 * F[c] % mod
			}
		}
		m = div(m, m2)

		ans = ans * m % mod

		m = F[gr]
		m2 = int64(1)
		for v, c := range cnt {
			if v > avg {
				m2 = m2 * F[c] % mod
			}
		}
		m = div(m, m2)

		ans = ans * m % mod
		if c := cnt[avg]; c > 0 {
			if c == int(n) {
				Fprintln(out, 1)
				return
			}
			res := H(int(n)-c+1, c)
			ans = ans * res % mod
		}
	}

	Fprintln(out, ans)
}

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


You have a set of $$$n$$$ discs, the $$$i$$$-th disc has radius $$$i$$$. Initially, these discs are split among $$$m$$$ towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top.You would like to assemble one tower containing all of those discs. To do so, you may choose two different towers $$$i$$$ and $$$j$$$ (each containing at least one disc), take several (possibly all) top discs from the tower $$$i$$$ and put them on top of the tower $$$j$$$ in the same order, as long as the top disc of tower $$$j$$$ is bigger than each of the discs you move. You may perform this operation any number of times.For example, if you have two towers containing discs $$$[6, 4, 2, 1]$$$ and $$$[8, 7, 5, 3]$$$ (in order from bottom to top), there are only two possible operations:  move disc $$$1$$$ from the first tower to the second tower, so the towers are $$$[6, 4, 2]$$$ and $$$[8, 7, 5, 3, 1]$$$;  move discs $$$[2, 1]$$$ from the first tower to the second tower, so the towers are $$$[6, 4]$$$ and $$$[8, 7, 5, 3, 2, 1]$$$. Let the difficulty of some set of towers be the minimum number of operations required to assemble one tower containing all of the discs. For example, the difficulty of the set of towers $$$[[3, 1], [2]]$$$ is $$$2$$$: you may move the disc $$$1$$$ to the second tower, and then move both discs from the second tower to the first tower.You are given $$$m - 1$$$ queries. Each query is denoted by two numbers $$$a_i$$$ and $$$b_i$$$, and means "merge the towers $$$a_i$$$ and $$$b_i$$$" (that is, take all discs from these two towers and assemble a new tower containing all of them in descending order of their radii from top to bottom). The resulting tower gets index $$$a_i$$$.For each $$$k \in [0, m - 1]$$$, calculate the difficulty of the set of towers after the first $$$k$$$ queries are performed.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le m \le n \le 2 \cdot 10^5$$$) — the number of discs and the number of towers, respectively. The second line contains $$$n$$$ integers $$$t_1$$$, $$$t_2$$$, ..., $$$t_n$$$ ($$$1 \le t_i \le m$$$), where $$$t_i$$$ is the index of the tower disc $$$i$$$ belongs to. Each value from $$$1$$$ to $$$m$$$ appears in this sequence at least once. Then $$$m - 1$$$ lines follow, denoting the queries. Each query is represented by two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le m$$$, $$$a_i \ne b_i$$$), meaning that, during the $$$i$$$-th query, the towers with indices $$$a_i$$$ and $$$b_i$$$ are merged ($$$a_i$$$ and $$$b_i$$$ are chosen in such a way that these towers exist before the $$$i$$$-th query).

Print $$$m$$$ integers. The $$$k$$$-th integer ($$$0$$$-indexed) should be equal to the difficulty of the set of towers after the first $$$k$$$ queries are performed.

NoteThe towers in the example are:  before the queries: $$$[[5, 1], [2], [7, 4, 3], [6]]$$$;  after the first query: $$$[[2], [7, 5, 4, 3, 1], [6]]$$$;  after the second query: $$$[[7, 5, 4, 3, 2, 1], [6]]$$$;  after the third query, there is only one tower: $$$[7, 6, 5, 4, 3, 2, 1]$$$.

package main

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

const (
	GRAPH_EDGE_SIZE    = 400010
	GRAPH_VERTICE_SIZE = 400010
)

type edge struct {
	v, next int
}

var (
	e    [GRAPH_EDGE_SIZE]edge
	head [GRAPH_VERTICE_SIZE]int
	cnt  int
)

func adde(u, v int) {
	e[cnt].v = v
	e[cnt].next = head[u]
	head[u] = cnt
	cnt++
}
func graph_init(N int) {
	cnt = 0
	for i := 0; i <= N; i++ {
		head[i] = -1
	}
}

var (
	n, m, ans int
	t, p, ct  [200010]int
	//LCA
	dep [400010]int
	f   [400010][20]int
)

func dfs(u, fa int) {
	dep[u] = dep[fa] + 1
	f[u][0] = fa
	for i := 1; dep[u] > (1 << i); i++ {
		f[u][i] = f[f[u][i-1]][i-1]
	}

	for i := head[u]; i != -1; i = e[i].next {
		v := e[i].v
		dfs(v, u)
	}
}
func LCA(u, v int) int {
	if dep[u] < dep[v] {
		u, v = v, u
	}
	for i := 19; i >= 0; i-- {
		if (1 << i) > dep[u]-dep[v] {
			continue
		}
		u = f[u][i]
	}
	if u == v {
		return u
	}
	for i := 19; i >= 0; i-- {
		if (1 << i) >= dep[u] {
			continue
		}
		if f[u][i] == f[v][i] {
			continue
		}
		u, v = f[u][i], f[v][i]
	}
	return f[u][0]
}

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

	Fscan(in, &n, &m)
	graph_init(2*m - 1)

	for i := 1; i <= n; i++ {
		Fscan(in, &t[i])
	}
	for i := 1; i <= m; i++ {
		p[i] = i
	}
	for i := 1; i < m; i++ {
		var u, v int
		Fscan(in, &u, &v)
		adde(m+i, p[u])
		adde(m+i, p[v])
		p[u] = m + i
	}
	dep[0] = 0
	dfs(2*m-1, 0)
	ans = n - 1
	for i := 1; i < n; i++ {
		if t[i] == t[i+1] {
			ct[0]++
		} else {
			ct[LCA(t[i], t[i+1])-m]++
		}
	}
	for i := 0; i < m; i++ {
		ans -= ct[i]
		Fprintln(out, ans)
	}
}