Alice and Bob are playing a game on a line with $$$n$$$ cells. There are $$$n$$$ cells labeled from $$$1$$$ through $$$n$$$. For each $$$i$$$ from $$$1$$$ to $$$n-1$$$, cells $$$i$$$ and $$$i+1$$$ are adjacent.Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers $$$x_1, x_2, \ldots, x_k$$$ in order. In the $$$i$$$-th question, Bob asks Alice if her token is currently on cell $$$x_i$$$. That is, Alice can answer either "YES" or "NO" to each Bob's question.At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.You are given $$$n$$$ and Bob's questions $$$x_1, \ldots, x_k$$$. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions. Let $$$(a,b)$$$ denote a scenario where Alice starts at cell $$$a$$$ and ends at cell $$$b$$$. Two scenarios $$$(a_i, b_i)$$$ and $$$(a_j, b_j)$$$ are different if $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n,k \leq 10^5$$$) — the number of cells and the number of questions Bob asked. The second line contains $$$k$$$ integers $$$x_1, x_2, \ldots, x_k$$$ ($$$1 \leq x_i \leq n$$$) — Bob's questions.

Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.

NoteThe notation $$$(i,j)$$$ denotes a scenario where Alice starts at cell $$$i$$$ and ends at cell $$$j$$$.In the first example, the valid scenarios are $$$(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$$$. For example, $$$(3,4)$$$ is valid since Alice can start at cell $$$3$$$, stay there for the first three questions, then move to cell $$$4$$$ after the last question. $$$(4,5)$$$ is valid since Alice can start at cell $$$4$$$, stay there for the first question, the move to cell $$$5$$$ for the next two questions. Note that $$$(4,5)$$$ is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.In the second example, Alice has no valid scenarios.In the last example, all $$$(i,j)$$$ where $$$|i-j| \leq 1$$$ except for $$$(42, 42)$$$ are valid scenarios.

package main

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

const (
	mod = uint64(1e9 + 7)
)

type slot struct {
	from uint64
	num  uint64
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, m := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &m)
	a := make([][]bool, n)
	for i := 0; i < n; i++ {
		a[i] = []bool{true, true, true}
	}
	a[0][1] = false
	a[n-1][2] = false
	ans := 0
	asked := make(map[int]bool)
	for i := 0; i < m; i++ {
		tmp := 0
		fmt.Fscanf(in, "%d", &tmp)
		tmp--
		asked[tmp] = true
		a[tmp][0] = false
		if asked[tmp-1] {
			a[tmp-1][2] = false
		}
		if asked[tmp+1] {
			a[tmp+1][1] = false
		}
	}
	for i := 0; i < n; i++ {
		if a[i][0] {
			ans++
		}
		if a[i][1] {
			ans++
		}
		if a[i][2] {
			ans++
		}
	}
	fmt.Fprintf(out, "%d\n", ans)
	return
}

func gcd(a, b uint64) uint64 {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func max(a, b uint64) uint64 {
	if a < b {
		return b
	}
	return a
}

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


The only difference between easy and hard versions is constraints.If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.A session has begun at Beland State University. Many students are taking exams.Polygraph Poligrafovich is going to examine a group of $$$n$$$ students. Students will take the exam one-by-one in order from $$$1$$$-th to $$$n$$$-th. Rules of the exam are following:  The $$$i$$$-th student randomly chooses a ticket.  if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.  if the student finds the ticket easy, he spends exactly $$$t_i$$$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.The duration of the whole exam for all students is $$$M$$$ minutes ($$$\max t_i \le M$$$), so students at the end of the list have a greater possibility to run out of time to pass the exam.For each student $$$i$$$, you should count the minimum possible number of students who need to fail the exam so the $$$i$$$-th student has enough time to pass the exam.For each student $$$i$$$, find the answer independently. That is, if when finding the answer for the student $$$i_1$$$ some student $$$j$$$ should leave, then while finding the answer for $$$i_2$$$ ($$$i_2>i_1$$$) the student $$$j$$$ student does not have to go home.

The first line of the input contains two integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le M \le 2 \cdot 10^7$$$) — the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $$$n$$$ integers $$$t_i$$$ ($$$1 \le t_i \le 100$$$) — time in minutes that $$$i$$$-th student spends to answer to a ticket. It's guaranteed that all values of $$$t_i$$$ are not greater than $$$M$$$.

Print $$$n$$$ numbers: the $$$i$$$-th number must be equal to the minimum number of students who have to leave the exam in order to $$$i$$$-th student has enough time to pass the exam.

NoteThe explanation for the example 1.Please note that the sum of the first five exam times does not exceed $$$M=15$$$ (the sum is $$$1+2+3+4+5=15$$$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $$$0$$$.In order for the $$$6$$$-th student to pass the exam, it is necessary that at least $$$2$$$ students must fail it before (for example, the $$$3$$$-rd and $$$4$$$-th, then the $$$6$$$-th will finish its exam in $$$1+2+5+6=14$$$ minutes, which does not exceed $$$M$$$).In order for the $$$7$$$-th student to pass the exam, it is necessary that at least $$$3$$$ students must fail it before (for example, the $$$2$$$-nd, $$$5$$$-th and $$$6$$$-th, then the $$$7$$$-th will finish its exam in $$$1+3+4+7=15$$$ minutes, which does not exceed $$$M$$$).

package main

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

var DEBUG = false
var reader *bufio.Reader
var writer *bufio.Writer
var times [101]int
var n, M, val int

func Printf(format string, a ...interface{}) {
	fmt.Fprintf(writer, format, a...)
}

func Scanf(format string, a ...interface{}) {
	fmt.Fscanf(reader, format, a...)
}

func calc(x int) int {
	total, passes := x, 1
	for i := 1; i <= 100; i++ {
		if times[i]*i+total <= M {
			passes += times[i]
			total += times[i] * i
		} else {
			passes += (M - total) / i
			break
		}
	}
	return passes
}

func main() {
	if DEBUG {
		f, _ := os.Open("input")
		reader = bufio.NewReader(f)
	} else {
		reader = bufio.NewReader(os.Stdin)
	}
	writer = bufio.NewWriter(os.Stdout)
	Scanf("%d %d\n", &n, &M)
	for i := 1; i <= n; i++ {
		Scanf("%d", &val)
		Printf("%d ", i-calc(val))
		times[val]++
	}
	Printf("\n")
	writer.Flush()
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, m := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &m)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &a[i])
	}
	cnt := make([]int, 101)
	sum := 0
	for i := 0; i < n; i++ {
		ans := 0
		sum += a[i]
		tmp := sum
		//fmt.Println("begin", i)
		for j := 100; j >= 1; j-- {
			if tmp <= m {
				break
			}
			if cnt[j] == 0 {
				continue
			}
			//fmt.Println(j, cnt[j], tmp)
			need := (tmp - m) / j
			if (tmp-m)%j != 0 {
				need++
			}
			if need <= cnt[j] {
				ans += need
				tmp -= need * j
			} else {
				ans += cnt[j]
				tmp -= cnt[j] * j
			}
		}
		cnt[a[i]]++
		if i != 0 {
			fmt.Fprintf(out, " ")
		}
		fmt.Fprintf(out, "%d", ans)
	}
	fmt.Fprintf(out, "\n")
	return
}

func gcd(a, b uint64) uint64 {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

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

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

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

func ok(a, b int) bool {
	if min(abs(a-b), abs(a+b)) <= min(abs(a), abs(b)) && max(abs(a+b), abs(a-b)) >= max(abs(a), abs(b)) {
		return true
	}
	return false
}


We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).

The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings. Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.

Print any suitable string s, or -1 if such string doesn't exist.

NoteIn the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.In the third example it's impossible to obtain given strings by aforementioned operations.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF903E(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, m int
	Fscan(in, &n, &m)
	a := make([][]byte, n)
	cnt := make([][26]int, n)
	has2 := make([]bool, n)
	for i := range a {
		Fscan(in, &a[i])
		for _, b := range a[i] {
			if cnt[i][b-'a']++; cnt[i][b-'a'] > 1 {
				has2[i] = true
			}
		}
		if cnt[i] != cnt[0] {
			Fprint(out, -1)
			return
		}
	}

	s0 := a[0]
	dis := make([]int, n)
	for i, s := range a {
		for j, b := range s {
			if b != s0[j] {
				dis[i]++
			}
		}
	}
	for l := 0; l < m; l++ {
	o:
		for r := l + 1; r < m; r++ {
			for i := 1; i < n; i++ {
				s, d := a[i], dis[i]
				if s[l] != s0[r] {
					d++
				}
				if s[r] != s0[l] {
					d++
				}
				if s[l] != s0[l] {
					d--
				}
				if s[r] != s0[r] {
					d--
				}
				if d > 2 || d == 0 && !has2[i] {
					continue o
				}
			}
			s0[l], s0[r] = s0[r], s0[l]
			Fprint(out, string(s0))
			return
		}
	}
	Fprint(out, -1)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	var n, m int
	Fscan(in, &n, &m)
	a := make([][]byte, n)
	cnt := make([][26]int, n)
	has2 := make([]bool, n)
	for i := range a {
		Fscan(in, &a[i])
		for _, b := range a[i] {
			if cnt[i][b-'a']++; cnt[i][b-'a'] > 1 {
				has2[i] = true
			}
		}
		if cnt[i] != cnt[0] {
			Print(-1)
			return
		}
	}

	s0 := a[0]
	dis := make([]int, n)
	for i, s := range a {
		for j, b := range s {
			if b != s0[j] {
				dis[i]++
			}
		}
	}
	for l := 0; l < m; l++ {
	o:
		for r := l + 1; r < m; r++ {
			for i := 1; i < n; i++ {
				s, d := a[i], dis[i]
				if s[l] != s0[r] {
					d++
				}
				if s[r] != s0[l] {
					d++
				}
				if s[l] != s0[l] {
					d--
				}
				if s[r] != s0[r] {
					d--
				}
				if d > 2 || d == 0 && !has2[i] {
					continue o
				}
			}
			s0[l], s0[r] = s0[r], s0[l]
			Print(string(s0))
			return
		}
	}
	Print(-1)
}


In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are ai people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.Help platform select such an hour, that the number of people who will participate in the contest is maximum.

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 10 000), where ai is the number of people in the i-th timezone who want to participate in the contest. The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).

Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.

NoteIn the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.In second example only people from the third and the fourth timezones will participate.

package main

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

func solve() {
	n := readInt()
	sum := make([]int64, n+10)
	for i := 1; i <= n; i++ {
		sum[i] += sum[i-1] + readInt64()
	}
	s := readInt()
	f := readInt()
	// fmt.Printf("sum = %+v\n", sum)
	best := int64(0)
	bestHour := 0
	for i := 1; i <= n; i++ {
		// fmt.Printf("i = %+v\n", i)
		from := s - i + 1
		to := f - i
		for from < 1 {
			from += n
			to += n
		}
		// fmt.Printf("from, to = %+v %+v\n", from, to)
		cur := int64(0)
		if to <= n {
			cur = sum[to] - sum[from-1]
		} else {
			cur = sum[to-n] + sum[n] - sum[from-1]
		}
		// fmt.Printf("cur = %+v\n", cur)
		if cur > best {
			best = cur
			bestHour = i
		}
	}
	fmt.Println(bestHour)
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

func solve() {
	n := readInt()
	a := readIntArray(n)
	s := readInt()
	f := readInt()
	dist := f - s - 1
	up := make([]int64, n*2+10)
	down := make([]int64, n*2+10)
	for i := 0; i < n; i++ {
		up[i+s] += int64(a[i])
		down[i+f] += int64(a[i])
	}
	cur := int64(0)
	best := int64(0)
	bestHour := 0
	for i := 0; i < len(up); i++ {
		cur -= down[i]
		cur += up[i]
		if cur > best {
			best = cur
			bestHour = i - dist
		}
	}
	fmt.Println(bestHour)
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

func solve() {
	n := readInt()
	a := readIntArray(n)
	s := readInt()
	f := readInt()
	up := make([]int64, n*2+10)
	down := make([]int64, n*2+10)
	for i := 0; i < n; i++ {
		up[i+s] += int64(a[i])
		down[i+f] -= int64(a[i])
	}
	cur := int64(0)
	best := int64(0)
	bestHour := 0
	for i := 0; i < len(up); i++ {
		cur += down[i]
		cur += up[i]
		if cur > best {
			best = cur
			bestHour = i
		}
	}
	fmt.Println(bestHour)
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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


Allen wants to enter a fan zone that occupies a round square and has $$$n$$$ entrances.There already is a queue of $$$a_i$$$ people in front of the $$$i$$$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.Allen uses the following strategy to enter the fan zone:   Initially he stands in the end of the queue in front of the first entrance.  Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of entrances. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of people in queues. These numbers do not include Allen.

Print a single integer — the number of entrance that Allen will use.

NoteIn the first example the number of people (not including Allen) changes as follows: $$$[\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]$$$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.In the second example the number of people (not including Allen) changes as follows: $$$[\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0]$$$.In the third example the number of people (not including Allen) changes as follows: $$$[\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2, \textbf{0}]$$$.

package main

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

var in *bufio.Scanner
var out *bufio.Writer

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

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan();
	n, _ := strconv.ParseInt(in.Text(), 10, 64);

	var res int64;
	var temp int64 = math.MaxInt64;

	for i:=int64(1); i<=n; i++ {
		in.Scan();
		a, _ := strconv.ParseInt(in.Text(), 10, 64);
		if (temp > (a-i+n)/n) {
			temp = (a-i+n)/n;
			res = i;
		}
	}

	out.WriteString(strconv.FormatInt(res, 10));
}

package main

import "fmt"
import "strconv"
import "os"
import "bufio"
import "strings"

func CheckArray(wait []int,lens int) int {
	e :=0
	m :=0
	min := 0
	for i,val := range wait  {
		if i == 0 || val < min {
			min = val
		}
	}
	e = min
	m = min - (min/lens)*lens
	for {
		if m == lens {
			m = 0
		}
		if e >= wait[m] {
			return m+1
		}
		 e ++
		 m++
	}
}

func main() {
	var entrance int
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	entrance, _ = strconv.Atoi(text)
	text, _ = reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	lo1 := strings.Split(text, " ")
	lines := []int{}
	for _, i := range lo1 {
		k, _ := strconv.Atoi(i)
		lines = append(lines, k)
	}
	fmt.Println(CheckArray(lines,entrance))
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var num int64
	var result int64
	fmt.Fscan(reader, &num)
	arrQueues := make([]int64, num)
	arrResult := make([]int64, num)
	var k float64
	var i int64
	var min int64
	for i = 0; i < num; i++ {
		fmt.Fscan(reader, &arrQueues[i])
		k = math.Ceil(float64(arrQueues[i]-i)/float64(num)) + 1
		arrResult[i] = int64(k)
		if arrResult[i] < min || i == 0 {
			min = arrResult[i]
			result = i + 1
		}
	}
	fmt.Println(result)

}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var num int64
	var result int64
	fmt.Fscan(reader, &num)
	listQueues := make([]int64, num)
	listResult := make([]int64, num)
	var k float64
	var i int64
	var min int64
	for i = 0; i < num; i++ {
		fmt.Fscan(reader, &listQueues[i])
		k = math.Ceil(float64(listQueues[i]-i)/float64(num)) + 1
		listResult[i] = int64(k)
		if listResult[i] < min || i == 0 {
			min = listResult[i]
			result = i + 1
		}
	}
	fmt.Println(result)

}

package main

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

func main() {
	var door int
	var people string
	_, err := fmt.Scanf("%d\n", &door)
	if err != nil {
		log.Fatal(err)
	}
	in := bufio.NewReader(os.Stdin)
	people, err = in.ReadString('\n')
	if err != nil {
		log.Fatal(err)
	}
	people = strings.TrimRight(people, "\n\r")
	people2 := strings.Split(people, " ")
	people3 := make([]int, len(people2))
	for i, p := range people2 {
		people3[i], err = strconv.Atoi(p)
		if err != nil {
			log.Fatal(err)
		}
	}
	var min int
	for i, e := range people3 {
		if i==0 || e < min {
			min = e
		}
	}
	for i := min; ; i++ {
		if people3[i%door] - i <= 0 {
			fmt.Println(i%door+1)
			break
		}
	}
	//flag := people3[0]
	//var res int
	//for i, p := range people3 {
	//	if flag < (p - i) {
	//		flag = p
	//		res = i
	//	}
	//}
	//fmt.Println(res+1)
}

package main

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

func main() {
	var n, rs int
	var tmp, min float64
	min = math.MaxFloat64
	reader := bufio.NewReader(os.Stdin)

	fmt.Fscan(reader, &n)

	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &tmp)
		tmp = math.Ceil((tmp - float64(i)) / float64(n))

		if tmp <= 0 {
			min = tmp
			rs = i + 1
			break
		}

		if tmp < min {
			min = tmp
			rs = i + 1
		}
	}

	fmt.Println(rs)
}

package main

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

const MaxN = 200005

var n int
var a [MaxN]int

func main() {
	stdin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(stdin, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(stdin, "%d ", &a[i])
	}

	minVal := 1000000001.0
	index := 1
	for i := 0; i < n; i++ {
		k := float64(i) + math.Ceil(math.Max(float64(a[i] - i), 0.0) / float64(n)) * float64(n)
		if k < minVal {
			index = i + 1
			minVal = k
		}
	}
	fmt.Printf("%d\n", index)
}

package main

import (
	"fmt"
	"sort"
)

func binarySearch(arr []int, l int, r int, x int) int {
	result :=0
	if arr[0] > x {
		return 0
	}
	if arr[len(arr)-1] < x || arr[len(arr)-1] == x {
		return len(arr)
	}

	for l <= r {
		mid := l + (r-l)/2
		if arr[mid] == x || arr[mid] < x {
			result = mid+1
			l = mid + 1
		} else {
			r = mid - 1
		}
	}
	return result

}

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

	priceOfShop := make([]int, numOfShop)

	for i := 0; i < numOfShop; i++ {
		fmt.Scan(&priceOfShop[i])
	}
	sort.Ints(priceOfShop)
	var numOfDay int
	fmt.Scan(&numOfDay)
	var coins int
	for i := 0; i < numOfDay; i++ {
		fmt.Scan(&coins)
		result := binarySearch(priceOfShop, 0, numOfShop-1, coins)
		fmt.Println(result)
	}

}

package main

import (
	"fmt"
	"sort"
)

func binarySearch(arr []int, l int, r int, x int) int {
	if arr[0] > x {
		return 0
	}
	if arr[len(arr)-1] < x || arr[len(arr)-1] == x {
		return len(arr)
	}

	for l <= r {
		mid := l + (r-l)/2
		if (arr[mid] == x && arr[mid+1] > x) || (arr[mid] < x && arr[mid+1] > x){
			return mid + 1
		}
		if arr[mid] > x && arr[mid-1] < x {
			return mid
		}
		if arr[mid] > x {
			r = mid - 1
		} else {
			l = mid + 1
		}

	}
	return 0

}

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

	priceOfShop := make([]int, numOfShop)

	for i := 0; i < numOfShop; i++ {
		fmt.Scan(&priceOfShop[i])
	}
	sort.Ints(priceOfShop)
	var numOfDay int
	fmt.Scan(&numOfDay)
	var coins int
	for i := 0; i < numOfDay; i++ {
		fmt.Scan(&coins)
		result := binarySearch(priceOfShop, 0, numOfShop-1, coins)
		fmt.Println(result)
	}

}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var door int
	var line []int
	var min int
	fmt.Scan(&door)
	line = make([]int, door)
	for i := 0; i < door; i++ {
		fmt.Scan(&line[i])
		//if line[i] < min || i == 0 {
		//	min = line[i]
		//}

	}
	sort.Ints(line[:])
	min = line[0]
	for i := min; ; i++ {
		if line[i%door]-i <= 0 {
			fmt.Println(i%door + 1)
			break
		}
	}
}


You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 998244353$$$) — inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.

Print $$$T$$$ lines, each line should contain the answer — two integers $$$x$$$ and $$$y$$$ such that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.

// Package main provides
//
// File:  a.go
// Author: ymiyamoto
//
// Created on Fri Dec 28 23:38:20 2018
//
package main

import "fmt"

func main() {
	var N int
	fmt.Scan(&N)
	for i := 0; i < N; i++ {
		var l, r int
		fmt.Scan(&l, &r)
		fmt.Println(l, 2*l)
	}
}

package main

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

func main() {
	stdin := bufio.NewScanner(os.Stdin)
	stdin.Scan()
	n, _ := strconv.Atoi(stdin.Text())
	for i := 0; i < n; i++ {
		stdin.Scan()
		fields := strings.Fields(stdin.Text())
		input, _ := strconv.Atoi(fields[0])
		fmt.Println(input, input*2)
	}
}

package main

import "fmt"

func main() {
	var n, l, r int
	fmt.Scanln(&n)
	for i := 0; i < n; i++ {
		fmt.Scanln(&l, &r)
		fmt.Println(l, l*2)
	}

}

package main

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

func main(){
	buf := bufio.NewReader(os.Stdin)
	var l,r,t int
	fmt.Fscanf(buf, "%d\n", &t)
	for i:= 1;i <= t;i++{
		fmt.Fscanf(buf, "%d %d\n", &l,&r)

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

}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	for i := 0; i < n; i++ {
		l, r := 0, 0
		fmt.Fscanf(in, "%d %d\n", &l, &r)
		fmt.Fprintf(out, "%d %d\n", l, l*2)
	}
	return
}

package main

import "fmt"

func main() {
	var T int
	var l, r int64
	fmt.Scanln(&T)
	for i := 0; i < T; i++ {
		fmt.Scanf("%d %d\n", &l, &r)
		fmt.Printf("%d %d\n", l, l*2)
	}
}

package main
import "fmt"
func main() {
	var t, a, b int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&a,&b)
		fmt.Println(a,a*2)
	}
}

package main

import(
	"fmt"
)

func main() {

	var n int

	fmt.Scan(&n)

	for ;n > 0; n-- {
		var l,r int
		fmt.Scan(&l, &r)

		fmt.Println(l, 2*l)
	}

}

package main

import "fmt"

func main() {
    T := 0
    fmt.Scanf("%d\n", &T)

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

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

// Package main provides
//
// File:  a.go
// Author: ymiyamoto
//
// Created on Fri Dec 28 23:38:20 2018
//
package main

import "fmt"

func main() {
	var l, r int
	fmt.Scan(&l, &r)
	fmt.Println(l, 2*l)
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	s := ""
	fmt.Fscanf(in, "%s\n", &s)
	fmt.Fprintf(out, "%s\n", recover(s))
	return
}

func recover(s string) string {
	if len(s) == 1 {
		return s
	}
	if len(s)%2 == 0 {
		return recover(s[:len(s)-1]) + string(s[len(s)-1])
	} else {
		return recover(s[1:]) + string(s[0])
	}
}

package main

import "fmt"

func main() {
	var T int
	var l, r int64
	fmt.Scan(&T)
	for i := 0; i < T; i++ {
		fmt.Scanf("%d %d\n", &l, &r)
		fmt.Printf("%d %d\n", l, l*2)
	}
}

package main

import "fmt"

func main() {
    T := 0
    fmt.Scanf("%d\n", &T)

    for i := 0; i < T; i++ {
        l := 0
        r := 0
        fmt.Scanf("%d %d", &l, &r)

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

package main

import "fmt"

func main() {
    T := 0
    fmt.Scanf("%d", &T)

    for i := 0; i < T; i++ {
        l := 0
        r := 0
        fmt.Scanf("%d%d", &l, &r)

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

package main

import "fmt"

func main() {
    T := 0
    fmt.Scanf("%d", &T)

    for i := 0; i < T; i++ {
        l := 0
        r := 0
        fmt.Scanf("%d %d", &l, &r)

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


The only difference between easy and hard versions is the constraint on $$$k$$$.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for $$$n$$$ days, starting from day $$$1$$$ to day $$$n$$$. The forest can be divided into $$$m$$$ areas, numbered from $$$1$$$ to $$$m$$$. He'll use the cameras in the following way:   On every odd day ($$$1$$$-st, $$$3$$$-rd, $$$5$$$-th, ...), bring the red camera to the forest and record a video for $$$2$$$ days.  On every even day ($$$2$$$-nd, $$$4$$$-th, $$$6$$$-th, ...), bring the blue camera to the forest and record a video for $$$2$$$ days.  If he starts recording on the $$$n$$$-th day with one of the cameras, the camera records for only one day. Each camera can observe $$$k$$$ consecutive areas of the forest. For example, if $$$m=5$$$ and $$$k=3$$$, he can put a camera to observe one of these three ranges of areas for two days: $$$[1,3]$$$, $$$[2,4]$$$, and $$$[3,5]$$$.Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for $$$n$$$ days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.

The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le m \le 2 \cdot 10^4$$$, $$$1 \le k \le m$$$) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively. Next $$$n$$$ lines contain $$$m$$$ integers each. The $$$j$$$-th integer in the $$$i+1$$$-st line is the number of animals that can be seen on the $$$i$$$-th day in the $$$j$$$-th area. Each number of animals is between $$$0$$$ and $$$1000$$$, inclusive.

Print one integer – the maximum number of animals that can be observed.

NoteThe optimal way to observe animals in the four examples are as follows:Example 1:   Example 2:   Example 3:   Example 4:

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

var segNoOverlap [100000]int
var segLeftOverlap [100000]int
var segRightOverlap [100000]int

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

func insert(seg *[100000]int, index, l, r, pos, value int) {
	if l == pos && r == pos {
		seg[index] = value
		return
	}
	mid := (l + r) / 2
	if pos <= mid {
		insert(seg, index*2+1, l, mid, pos, value)
	} else {
		insert(seg, index*2+2, mid+1, r, pos, value)
	}
	seg[index] = max(seg[index*2+1], seg[index*2+2])
}

func query(seg *[100000]int, index, l, r, left, right int) int {
	if l == left && r == right {
		return seg[index]
	}
	mid := (l + r) / 2
	if right <= mid {
		return query(seg, index*2+1, l, mid, left, right)
	} else if left > mid {
		return query(seg, index*2+2, mid+1, r, left, right)
	} else {
		return max(query(seg, index*2+1, l, mid, left, mid), query(seg, index*2+2, mid+1, r, mid+1, right))
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewReader(bs)
	var n, m, k int
	fmt.Fscanf(reader, "%d %d %d\n", &n, &m, &k)
	prefixSum := make([][]int, n+1)
	for i := 0; i < n; i++ {
		prefixSum[i] = make([]int, m+1)
		for j := 1; j < m; j++ {
			fmt.Fscanf(reader, "%d ", &prefixSum[i][j])
			prefixSum[i][j] += prefixSum[i][j-1]
		}
		fmt.Fscanf(reader, "%d\n", &prefixSum[i][m])
		prefixSum[i][m] += prefixSum[i][m-1]
	}
	prefixSum[n] = make([]int, m+1)
	for i := 1; i <= m-k+1; i++ {
		sum := prefixSum[0][i+k-1] - prefixSum[0][i-1]
		insert(&segNoOverlap, 0, 1, m-k+1, i, sum+prefixSum[1][i+k-1]-prefixSum[1][i-1])
		insert(&segLeftOverlap, 0, 1, m-k+1, i, sum-prefixSum[1][i-1])
		insert(&segRightOverlap, 0, 1, m-k+1, i, sum+prefixSum[1][i+k-1])
	}
	dp := make([]int, m-k+2)
	for i := 1; i < n; i++ {
		for j := 1; j <= m-k+1; j++ {
			ans := -99999999
			if j > k {
				ans = max(ans, prefixSum[i][j+k-1]-prefixSum[i][j-1]+query(&segNoOverlap, 0, 1, m-k+1, 1, j-k))
			}
			if j+2*k-1 <= m {
				ans = max(ans, prefixSum[i][j+k-1]-prefixSum[i][j-1]+query(&segNoOverlap, 0, 1, m-k+1, j+k, m-k+1))
			}
			if j >= k {
				ans = max(ans, prefixSum[i][j+k-1]+query(&segLeftOverlap, 0, 1, m-k+1, j-k+1, j))
			} else {
				ans = max(ans, prefixSum[i][j+k-1]+query(&segLeftOverlap, 0, 1, m-k+1, 1, j))
			}
			if j+2*k-2 <= m {
				ans = max(ans, -prefixSum[i][j-1]+query(&segRightOverlap, 0, 1, m-k+1, j, j+k-1))
			} else {
				ans = max(ans, -prefixSum[i][j-1]+query(&segRightOverlap, 0, 1, m-k+1, j, m-k+1))
			}
			dp[j] = ans
		}
		for j := 1; j <= m-k+1; j++ {
			insert(&segNoOverlap, 0, 1, m-k+1, j, dp[j]+prefixSum[i+1][j+k-1]-prefixSum[i+1][j-1])
			insert(&segLeftOverlap, 0, 1, m-k+1, j, dp[j]-prefixSum[i+1][j-1])
			insert(&segRightOverlap, 0, 1, m-k+1, j, dp[j]+prefixSum[i+1][j+k-1])
		}
	}
	fmt.Printf("%d", segNoOverlap[0])
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

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 maxi16(a, b int) int {
	if a > b {
		return a
	}
	return b
}

type Tree struct {
	a              []int
	propagate      []int
	sz             int
	undefinedValue int
}

func (t *Tree) Upd(v int) {
	if v < t.sz {
		t.a[v] = max(t.a[v<<1], t.a[(v<<1)|1])
	}
}

func (t *Tree) Propagate(v int) {
	prp := t.propagate[v]
	if prp == 0 {
		return
	}
	if v < t.sz {
		t.propagate[v<<1] += prp
		t.propagate[(v<<1)|1] += prp
	}
	t.a[v] += prp
	t.propagate[v] = 0
}

func (t *Tree) GoAdd(v, x, l, r, L, R int) {
	t.Propagate(v)
	if l > r {
		return
	}
	if r < L || l > R {
		return
	}
	if l <= L && R <= r {
		t.propagate[v] += x
		t.Propagate(v)
		return
	}
	t.GoAdd(v<<1, x, l, r, L, (L+R)>>1)
	t.GoAdd((v<<1)|1, x, l, r, (L+R)/2+1, R)
	t.Upd(v)
}

func (t *Tree) GoSet(v, value, k, L, R int) {
	t.Propagate(v)
	if k < L || k > R {
		return
	}
	if L == k && k == R {
		t.a[v] = value
		return
	}
	t.GoSet(v<<1, value, k, L, (L+R)>>1)
	t.GoSet((v<<1)|1, value, k, (L+R)/2+1, R)
	t.Upd(v)
}

func (t *Tree) GoMax(v, l, r, L, R int) int {
	t.Propagate(v)
	if l > r {
		return t.undefinedValue
	}
	if r < L || l > R {
		return t.undefinedValue
	}
	if l <= L && R <= r {
		return t.a[v]
	}
	r1 := t.GoMax(v<<1, l, r, L, (L+R)>>1)
	r2 := t.GoMax((v<<1)|1, l, r, (L+R)/2+1, R)
	t.Upd(v)
	return max(r1, r2)
}

func (t *Tree) Add(l, r int, value int) {
	l = max(l, 0)
	r = min(r, t.sz-1)
	if l > r {
		return
	}
	t.GoAdd(1, value, l, r, 0, t.sz-1)
}

func (t *Tree) Max(l, r int) int {
	if l > r {
		return 0
	}
	res := t.GoMax(1, l, r, 0, t.sz-1)
	if res == t.undefinedValue {
		return 0
	}
	return res
}

func (t *Tree) Set(k, v int) {
	if k < 0 || k >= t.sz {
		return
	}
	t.GoSet(1, v, k, 0, t.sz-1)
}

func (t *Tree) Get(k int) int {
	return t.Max(k, k)
}

func NewTree(n int) *Tree {
	sz := 1
	for sz < n {
		sz <<= 1
	}
	a := make([]int, 2*sz+1)
	propagate := make([]int, 2*sz+1)
	return &Tree{a, propagate, sz, -20000001}
}

func main() {
	inf := os.Stdin
	out := os.Stdout
	// f, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)
	n := NextInt()
	m := NextInt()
	k := NextInt()
	a := make([][]int, n)

	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		for j := 0; j < m; j++ {
			a[i][j] = NextInt()
		}
	}

	var f [2]*Tree
	f[0] = NewTree(m)
	f[1] = NewTree(m)
	total := 0

	for i := 0; i < n; i++ {
		ind := i & 1
		pind := ind ^ 1
		bs := 0
		ns := 0
		r := 0
		if i > 0 {
			for l := 0; l < k; l++ {
				f[pind].Add(l-k+1, l, -a[i][l])
			}
		}

		for l := 0; l < m; l++ {
			if l > 0 {
				bs -= a[i][l-1]
				if i+1 < n {
					ns -= a[i+1][l-1]
				}
			}
			for r < l+k && r < m {
				bs += a[i][r]
				if i+1 < n {
					ns += a[i+1][r]
				}
				r++
			}
			if l-1 >= 0 && i > 0 {
				// stderr("\tadd for left part", l-k, l-1, a[i][l-1])
				f[pind].Add(l-k, l-1, a[i][l-1])
			}
			if l+k-1 < m && l > 0 && i > 0 {
				// stderr("\tadd for right part", l, l+k-1, -a[i][l+k-1])
				f[pind].Add(l, l+k-1, -a[i][l+k-1])
			}

			res := f[pind].Max(0, m-1) + bs

			f[ind].Set(l, res+ns)

			// stderr("res", i, l, "is ", res, "bs", bs, "ns", ns, "k=", k)
			total = max(total, res+ns)
		}
	}
	fmt.Fprintln(out, total)
}


A and B are preparing themselves for programming contests.The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.

The first line contains integer n (1 ≤ n ≤ 105) — the number of rooms in the University. The next n - 1 lines describe the corridors. The i-th of these lines (1 ≤ i ≤ n - 1) contains two integers ai and bi (1 ≤ ai, bi ≤ n), showing that the i-th corridor connects rooms ai and bi. The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Next m lines describe the queries. The j-th of these lines (1 ≤ j ≤ m) contains two integers xj and yj (1 ≤ xj, yj ≤ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.

In the i-th (1 ≤ i ≤ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.

Notein the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 1.

package main

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

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

	var n, v, w, q int
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	const mx = 17
	pa := make([][mx]int, n)
	dep := make([]int, n)
	size := make([]int, n)
	var f func(v, p, d int) int
	f = func(v, p, d int) int {
		pa[v][0] = p
		dep[v] = d
		sz := 1
		for _, w := range g[v] {
			if w != p {
				sz += f(w, v, d+1)
			}
		}
		size[v] = sz
		return sz
	}
	f(0, -1, 0)
	for k := 0; k+1 < mx; k++ {
		for v := range pa {
			if p := pa[v][k]; p != -1 {
				pa[v][k+1] = pa[p][k]
			} else {
				pa[v][k+1] = -1
			}
		}
	}
	uptoDep := func(v, d int) int {
		for k := 0; k < mx; k++ {
			if (dep[v]-d)>>k&1 == 1 {
				v = pa[v][k]
			}
		}
		return v
	}
	_lca := func(v, w int) int {
		if dep[v] > dep[w] {
			v, w = w, v
		}
		w = uptoDep(w, dep[v])
		if v == w {
			return v
		}
		for k := mx - 1; k >= 0; k-- {
			if pa[v][k] != pa[w][k] {
				v, w = pa[v][k], pa[w][k]
			}
		}
		return pa[v][0]
	}

	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &w)
		if v == w {
			Fprintln(out, n)
			continue
		}
		v--
		w--
		if dep[v] > dep[w] {
			v, w = w, v
		}
		lca := _lca(v, w)
		d := dep[v] + dep[w] - dep[lca]<<1
		if d&1 == 1 {
			Fprintln(out, 0)
			continue
		}
		uw := uptoDep(w, dep[w]-d>>1+1)
		if p := pa[uw][0]; p != lca {
			Fprintln(out, size[p]-size[uw])
		} else {
			uv := uptoDep(v, dep[v]-d>>1+1)
			Fprintln(out, n-size[uv]-size[uw])
		}
	}
}

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

package main

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

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

	var n, v, w, q int
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	const mx = 18
	pa := make([][mx]int, n)
	dep := make([]int, n)
	size := make([]int, n)
	var f func(v, p, d int) int
	f = func(v, p, d int) int {
		pa[v][0] = p
		dep[v] = d
		sz := 1
		for _, w := range g[v] {
			if w != p {
				sz += f(w, v, d+1)
			}
		}
		size[v] = sz
		return sz
	}
	f(0, -1, 0)
	for k := 0; k+1 < mx; k++ {
		for v := range pa {
			if p := pa[v][k]; p != -1 {
				pa[v][k+1] = pa[p][k]
			} else {
				pa[v][k+1] = -1
			}
		}
	}
	uptoDep := func(v, d int) int {
		for k := 0; k < mx; k++ {
			if (dep[v]-d)>>k&1 == 1 {
				v = pa[v][k]
			}
		}
		return v
	}
	_lca := func(v, w int) int {
		if dep[v] > dep[w] {
			v, w = w, v
		}
		w = uptoDep(w, dep[v])
		if v == w {
			return v
		}
		for k := mx - 1; k >= 0; k-- {
			if pa[v][k] != pa[w][k] {
				v, w = pa[v][k], pa[w][k]
			}
		}
		return pa[v][0]
	}

	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &w)
		if v == w {
			Fprintln(out, n)
			continue
		}
		v--
		w--
		if dep[v] > dep[w] {
			v, w = w, v
		}
		lca := _lca(v, w)
		d := dep[v] + dep[w] - dep[lca]<<1
		if d&1 == 1 {
			Fprintln(out, 0)
			continue
		}
		uw := uptoDep(w, dep[w]-d>>1+1)
		if p := pa[uw][0]; p == lca {
			uv := uptoDep(v, dep[v]-d>>1+1)
			Fprintln(out, n-size[uv]-size[uw])
		} else {
			Fprintln(out, size[p]-size[uw])
		}
	}
}

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

package main

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

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

	var n, v, w, q int
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	const mx = 18
	pa := make([][mx]int, n)
	dep := make([]int, n)
	size := make([]int, n)
	var f func(v, p, d int) int
	f = func(v, p, d int) int {
		pa[v][0] = p
		dep[v] = d
		sz := 1
		for _, w := range g[v] {
			if w != p {
				sz += f(w, v, d+1)
			}
		}
		size[v] = sz
		return sz
	}
	f(0, -1, 0)
	for k := 0; k+1 < mx; k++ {
		for v := range pa {
			if p := pa[v][k]; p != -1 {
				pa[v][k+1] = pa[p][k]
			} else {
				pa[v][k+1] = -1
			}
		}
	}
	uptoDep := func(v, d int) int {
		for k := 0; k < mx; k++ {
			if (dep[v]-d)>>k&1 == 1 {
				v = pa[v][k]
			}
		}
		return v
	}
	_lca := func(v, w int) int {
		if dep[v] > dep[w] {
			v, w = w, v
		}
		w = uptoDep(w, dep[v])
		if v == w {
			return v
		}
		for k := mx - 1; k >= 0; k-- {
			if pa[v][k] != pa[w][k] {
				v, w = pa[v][k], pa[w][k]
			}
		}
		return pa[v][0]
	}

	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &w)
		if v == w {
			Fprintln(out, n)
			continue
		}
		v--
		w--
		if dep[v] > dep[w] {
			v, w = w, v
		}
		lca := _lca(v, w)
		d := dep[v] + dep[w] - dep[lca]<<1
		if d&1 == 1 {
			Fprintln(out, 0)
			continue
		}
		m := uptoDep(w, dep[w]-d>>1+1)
		if p := pa[m][0]; p == lca {
			Fprintln(out, n-size[p]+1)
		} else {
			Fprintln(out, size[p]-size[m])
		}
	}
}

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


One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.

The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).

In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var n, k int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	r.Scan()
	k, _ = strconv.Atoi(r.Text())
	if n < 2*k+1 {
		w.WriteString("-1\n")
	} else {
		w.WriteString(strconv.Itoa(n*k)+"\n")
		for i:=1; i<=n; i++ {
			for j:=i+1; j<=i+k; j++ {
				w.WriteString(strconv.Itoa(i)+" ")
				if j>n {
					w.WriteString(strconv.Itoa(j-n)+"\n")
				} else {
					w.WriteString(strconv.Itoa(j)+"\n")
				}
			}
		}
	}
	w.Flush()
}

// 417C
package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	var n, i, j, k int64
	fmt.Fscan(in, &n, &k)
	if 2*k >= n {
		fmt.Println("-1")
		return
	}
	fmt.Fprintln(out, n*k)
	for i = 1; i <= n; i++ {
		for j = i + 1; j <= i+k; j++ {
			fmt.Fprintln(out, i, (j-1)%n+1)
		}
	}
	out.Flush()
}

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var n, k int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	r.Scan()
	k, _ = strconv.Atoi(r.Text())
	if n < 2*k+1 {
		w.WriteString("-1\n")
	} else {
		w.WriteString(strconv.Itoa(n*k)+"\n")
		for i:=1; i<=n; i++ {
			for j:=i+1; j<=i+k; j++ {
				w.WriteString(strconv.Itoa(i)+" ")
				if j>n {
					w.WriteString(strconv.Itoa(j-n)+"\n")
				} else {
					w.WriteString(strconv.Itoa(j)+"\n")
				}
			}
		}
		w.Flush()
	}
}

// 417C
package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	var n, i, j, k int64
	fmt.Fscan(in, &n, &k)
	if 2*k >= n {
		fmt.Println("-1")
		return
	}
	fmt.Fprintln(out, n*k)
	for i = 1; i <= n; i++ {
		for j = i + 1; j <= i+k; j++ {
			fmt.Fprintln(out, i, (j-1)%n+1)
		}
	}
}


You have a long stick, consisting of $$$m$$$ segments enumerated from $$$1$$$ to $$$m$$$. Each segment is $$$1$$$ centimeter long. Sadly, some segments are broken and need to be repaired.You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $$$t$$$ placed at some position $$$s$$$ will cover segments $$$s, s+1, \ldots, s+t-1$$$.You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.Time is money, so you want to cut at most $$$k$$$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$n \le m \le 10^9$$$, $$$1 \le k \le n$$$) — the number of broken segments, the length of the stick and the maximum number of pieces you can use. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le m$$$) — the positions of the broken segments. These integers are given in increasing order, that is, $$$b_1 < b_2 < \ldots < b_n$$$.

Print the minimum total length of the pieces.

NoteIn the first example, you can use a piece of length $$$11$$$ to cover the broken segments $$$20$$$ and $$$30$$$, and another piece of length $$$6$$$ to cover $$$75$$$ and $$$80$$$, for a total length of $$$17$$$.In the second example, you can use a piece of length $$$4$$$ to cover broken segments $$$1$$$, $$$2$$$ and $$$4$$$, and two pieces of length $$$1$$$ to cover broken segments $$$60$$$ and $$$87$$$.

package main

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

var in = bufio.NewReaderSize(os.Stdin, 2<<16)

func main() {
	var n, m, k int
	fmt.Fscan(in, &n, &m, &k)
	var first, next int
	fmt.Fscan(in, &first)
	last := first
	var save []int
	for i := 1; i < n; i++ {
		fmt.Fscan(in, &next)
		if cur := next - last - 1; cur > 0 {
			save = append(save, -cur)
		}
		last = next
	}
	sort.Ints(save)
	ans := last - first + 1
	for i := range save {
		if k == 1 {
			break
		}
		ans += save[i]
		k--
	}
	fmt.Println(ans)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, m, k int
	fmt.Fscan(reader, &n, &m, &k)
	list := make([]int, n-1)
	previous := 1
	for i := 0; i < n; i++ {
		var a int
		fmt.Fscan(reader, &a)
		if i == 0 {
			previous = a
			continue
		}
		list[i-1] = a - previous
		previous = a
	}
	sort.Ints(list)
	total := 0
	for i := 0; i < n-k; i++ {
		total += list[i]
	}
	total += 1 * k
	fmt.Println(total)
}

package main

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

type inputData struct {
	brokenCount   int
	stickLength   int
	maxPieceCount int
	brokenPos     []int
}

func main() {
	inputData, err := readInputData(os.Stdin)
	if err != nil {
		panic(err)
	}
	fmt.Println(minTapeLength(inputData))
}

func minTapeLength(data inputData) int {
	segments := make([]int, data.brokenCount-1)

	for i := 0; i < data.brokenCount-1; i++ {
		segments[i] = data.brokenPos[i+1] - data.brokenPos[i]
	}

	sort.Ints(segments)

	sum := data.brokenCount

	for i := 0; i < data.brokenCount-data.maxPieceCount; i++ {
		sum += segments[i] - 1
	}

	return sum
}

func readInputData(input io.Reader) (inputData, error) {
	reader := bufio.NewReader(input)

	firstLine, err := readInts(reader)
	if err != nil {
		return inputData{}, err
	}

	secondLine, err := readInts(reader)
	if err != nil {
		return inputData{}, err
	}

	return inputData{
		brokenCount:   firstLine[0],
		stickLength:   firstLine[1],
		maxPieceCount: firstLine[2],
		brokenPos:     secondLine,
	}, nil
}

func readInts(reader *bufio.Reader) ([]int, error) {
	var err error
	str, err := reader.ReadString('\n')
	if err != nil && err != io.EOF {
		return nil, fmt.Errorf("could not read line: %v", err)
	}
	fields := strings.Fields(str)

	count := len(fields)
	ints := make([]int, count)

	for i, s := range fields {
		if ints[i], err = strconv.Atoi(s); err != nil {
			return nil, fmt.Errorf("could not convert input line to ints: %v", err)
		}
	}
	return ints, nil
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func main() {
	defer writer.Flush()

	var n, m, k, t1, last int

	ans := 0

	scanf("%d %d %d\n", &n, &m, &k)

	ans = n

	scanf("%d", &last)

	arr := []int{}

	for i := 0; i < n-1; i++ {
		scanf("%d", &t1)
		arr = append(arr, t1-last-1)
		last = t1
	}

	sort.Ints(arr)

	cur := n

	for cur > k {
		cur--
		t1 = arr[0]
		arr = arr[1:]
		ans += t1
	}

	printf("%d", ans)

}

package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"math/big"
	"os"
	"sort"
)

var reader *bufio.Reader
var writer *bufio.Writer

var inputFile = flag.String("input", "", "")

func init() {
	flag.Parse()
	var i io.Reader
	if *inputFile != "" {
		i, _ = os.Open(*inputFile)
	} else {
		i = os.Stdin
	}
	reader = bufio.NewReaderSize(i, 1<<20)
	writer = bufio.NewWriterSize(os.Stdout, 1<<20)
}

func println(a ...interface{}) {
	_, _ = fmt.Fprintln(writer, a...)
}

func printf(format string, a ...interface{}) {
	_, _ = fmt.Fprintf(writer, format, a...)
}

func scanf(format string, a ...interface{}) {
	_, _ = fmt.Fscanf(reader, format, a...)
}

func scan(a interface{}) {
	_, _ = fmt.Fscan(reader, a)
}

func NextInt64() int64 {
	var res int64
	scan(&res)
	return res
}

func NextInt() int {
	var res int
	scan(&res)
	return res
}

func NextIntArray(n int) []int {
	res := make([]int, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextString() string {
	var res string
	scan(&res)
	return res
}

func NextBigInt() *big.Int {
	n := new(big.Int)
	n, _ = n.SetString(NextString(), 10)
	return n
}

func main() {
	defer writer.Flush()

	n := NextInt()
	_ = NextInt()
	k := NextInt()

	answer := n

	a := NextIntArray(n)

	b := make([]int, n - 1)

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

	sort.Ints(b)

	for ; len(b) >= k; {
		answer += b[0]
		b = b[1:]
	}

	println(answer)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, m, k int
	fmt.Fscan(reader, &n, &m, &k)
	list := make([]int, n)
	previous := 0
	for i := 0; i < n; i++ {
		var a int
		fmt.Fscan(reader, &a)
		list[i] = a - previous
		previous = a
	}
	sort.Ints(list)
	total := 0
	for i := 0; i < n-k; i++ {
		total += list[i] - 1
	}
	total += 2 * k
	fmt.Println(total)
}

package main

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

type inputData struct {
	brokenCount   int
	stickLength   int
	maxPieceCount int
	brokenPos     []int
}

func main() {
	fmt.Println(minTapeLength(os.Stdin))
}

func minTapeLength(input io.Reader) int {
	data, err := readInputData(input)
	if err != nil {
		panic(err)
	}

	segments := make([]int, data.brokenCount-1)

	for i := 0; i < data.brokenCount-1; i++ {
		segments[i] = data.brokenPos[i+1] - data.brokenPos[i]
	}

	sort.Ints(segments)

	sum := data.brokenCount - data.maxPieceCount

	for i := 0; i < data.brokenCount-data.maxPieceCount; i++ {
		sum += segments[i]
	}

	return sum
}

func readInputData(input io.Reader) (inputData, error) {
	scanner := bufio.NewScanner(input)

	firstLine, err := readInts(scanner, 3)
	if err != nil {
		return inputData{}, err
	}

	secondLine, err := readInts(scanner, firstLine[0])
	if err != nil {
		return inputData{}, err
	}

	return inputData{
		brokenCount:   firstLine[0],
		stickLength:   firstLine[1],
		maxPieceCount: firstLine[2],
		brokenPos:     secondLine,
	}, nil
}

func readInts(scanner *bufio.Scanner, expected int) ([]int, error) {
	if !scanner.Scan() {
		return nil, errors.New("could not read line")
	}
	fields := strings.Fields(scanner.Text())

	count := len(fields)
	if count != expected {
		return nil, fmt.Errorf("invalid field count; expected %d, got %d", expected, count)
	}

	ints := make([]int, count)
	var err error

	for i, s := range fields {
		if ints[i], err = strconv.Atoi(s); err != nil {
			return nil, fmt.Errorf("could not convert input line to ints: %v", err)
		}
	}
	return ints, nil
}


Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ au.Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.

The first line contains single integer n (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers written in the vertices. The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 ≤ pi ≤ n, 1 ≤ wi ≤ 109) — the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1). It is guaranteed that the given graph is a tree.

Print n integers — the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.

NoteIn the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).

package main

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

func Init() {
}

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

	nodes := make([]*Node, N + 1)
	for i := 1; i <= N; i++ {
	  A := io.NextLong()

	  nodes[i] = NewNode(A)
	}

	for i := 2; i <= N; i++ {
	  P := io.NextInt()
	  W := io.NextLong()

	  nodes[P].children = append(nodes[P].children, NewEdge(W, nodes[i]))
	}

	UpdateDepths(nodes[1], 0)
	UpdateSize(nodes[1])
	CountLoss(nodes[1], make([]*Node, 0))

// 	for i := 1; i <= N; i++ {
// 	  fmt.Printf("%d: size = %d, loss = %d, depth = %d\n", i, nodes[i].size, nodes[i].loss, nodes[i].depth)
// 	}
	UpdateLoss(nodes[1])

	for i := 1; i <= N; i++ {
	  io.Printf("%d ", nodes[i].size - nodes[i].loss - 1)
	}
	io.Println()
}

type Node struct {
  children []*Edge
  value int64
  loss int
  size int
  depth int64
}

func NewNode(v int64) *Node {
  return &Node{
    children: make([]*Edge, 0),
    value: v,
  }
}

func UpdateDepths(u *Node, d int64) {
  if u == nil {
    return
  }
  u.depth = d
  for _, e := range u.children {
    UpdateDepths(e.dest, d + e.weight)
  }
}

func UpdateSize(u *Node) {
  if u == nil {
    return
  }
  u.size = 1
  for _, e := range u.children {
    UpdateSize(e.dest)
    u.size += e.dest.size
  }
}

func findDepth(path []*Node, d int64) *Node {
  L := 0
  R := len(path) - 1
  var good *Node
  // for _, u := range path {
  //   fmt.Printf("%d -> ", u.depth)
  // }
  // fmt.Println()
  for L <= R {
    M := (L + R) >> 1
    if path[M].depth < d {
      // fmt.Printf("  M = %d, depth = %d, want = %d\n", M, path[M].depth, d)
      L = M + 1
      good = path[M]
    } else {
      R = M - 1
    }
  }
  return good
}

func CountLoss(u *Node, path []*Node) {
  which := findDepth(path, u.depth - u.value)
  // fmt.Printf("curr depth = %d, search = %d, which = %+v\n", u.depth, u.depth - u.value, which)
  if which != nil {
    which.loss++
  }
  path = append(path, u)
  for _, e := range u.children {
    CountLoss(e.dest, path)
  }
  path = path[:len(path)-1]
}

func UpdateLoss(u *Node) {
  if u == nil {
    return
  }
  for _, e := range u.children {
    UpdateLoss(e.dest)
    u.loss += e.dest.loss
  }
}

type Edge struct {
  weight int64
  dest *Node
}

func NewEdge(w int64, d *Node) *Edge {
  return &Edge{
    weight: w,
    dest: d,
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

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

type Edge struct {
    to int
    w  int64
}

func solve() {
    n := readInt()
    a, adj := readInt64Array(n), make([][]Edge, n)
    for i := 1; i < n; i++ {
        p, w := readInt()-1, readInt64()
        adj[p] = append(adj[p], Edge{i, w})
    }

    depth, stack, lim, ans := make([]int64, n), []int{0}, make([]int, n), make([]int, n)

    var dfs func() int
    dfs = func() int {
        curI := len(stack) - 1
        cur := stack[curI]

        l, r := 0, curI
        for l < r {
            if mid := (l+r) / 2; depth[stack[mid]] >= depth[cur]-a[cur] {
                r = mid
            } else {
                l = mid+1
            }
        }
        //fmt.Println(depth, stack, r)
        lim[stack[r]]++

        res := 0
        for _, ch := range adj[cur] {
            depth[ch.to] = depth[cur]+ch.w
            stack = append(stack, ch.to)
            res += dfs()
        }
        ans[cur] = res
        res += 1-lim[cur]
        stack = stack[:curI]
        //fmt.Println(cur, "=>", res)
        return res
    }
    dfs()

    for _, c := range ans {
        fmt.Print(c, " ")
    }
    fmt.Println()

}

// Helpers

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 {
	if x < y {
		return x
	}
	return y
}

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

func (a Ints64) Len() int           { return len(a) }
func (a Ints64) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a Ints64) Less(i, j int) bool { return a[i] < a[j] }

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

type v struct {
	edges []*edge
	id    int
}

type edge struct {
	v int
	w int
}

type pair struct {
	v   int
	sum int64
}

var ans []int
var a []int
var g []*v
var x []int

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for scanner.Scan() {
		n, _ := strconv.Atoi(scanner.Text())
		a = make([]int, n)
		ans = make([]int, n)
		x = make([]int, n)
		g = make([]*v, n, n)
		for i := 0; i < n; i++ {
			scanner.Scan()
			a[i], _ = strconv.Atoi(scanner.Text())
			g[i] = &v{make([]*edge, 0), i}
		}
		for i := 0; i < n-1; i++ {
			scanner.Scan()
			var p, w int
			p, _ = strconv.Atoi(scanner.Text())
			scanner.Scan()
			w, _ = strconv.Atoi(scanner.Text())
			g[p-1].edges = append(g[p-1].edges, &edge{i + 1, w})
		}
		root := 0
		stack := make([]*pair, 1)
		stack[0] = &pair{
			v:   root,
			sum: 0,
		}
		dfs(root, stack)
		for i := 0; i < n; i++ {
			fmt.Printf("%d ", ans[i])
		}
		fmt.Print("\n")
	}
}

func dfs(cur int, stack []*pair) {
	l := 0
	r := len(stack) - 1
	totalsum := stack[len(stack)-1].sum
	for l < r {
		mid := (l + r + 1) / 2
		cursum := stack[mid].sum
		if totalsum-cursum <= int64(a[cur]) {
			r = mid - 1
		} else {
			l = mid
		}
	}
	if totalsum-stack[l].sum > int64(a[cur]) {
		x[stack[l].v]--
	}
	t := 0
	lastsum := stack[len(stack)-1].sum
	for _, edge := range g[cur].edges {
		stack = append(stack, &pair{edge.v, lastsum + int64(edge.w)})
		dfs(edge.v, stack)
		stack = stack[:len(stack)-1]
		t += ans[edge.v] + 1
	}
	t += x[cur]
	ans[cur] = t
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF740D(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}
	type edge struct{ to, l int }

	n := read()
	a := make([]int64, n)
	for i := range a {
		a[i] = int64(read())
	}
	const mx = 19
	pa := make([][mx]int, n)
	pa[0][0] = -1
	g := make([][]edge, n)
	for w := 1; w < n; w++ {
		v := read() - 1
		g[v] = append(g[v], edge{w, read()})
		pa[w][0] = v
	}
	for k := 0; k+1 < mx; k++ {
		for v := range pa {
			if p := pa[v][k]; p != -1 {
				pa[v][k+1] = pa[p][k]
			} else {
				pa[v][k+1] = -1
			}
		}
	}

	dep := make([]int64, n)
	var f func(int, int64)
	f = func(v int, d int64) {
		dep[v] = d
		for _, e := range g[v] {
			f(e.to, d+int64(e.l))
		}
	}
	f(0, 0)

	diff := make([]int, n)
	for v, val := range a {
		u := v
		dv := dep[v]
		for i := mx - 1; i >= 0; i-- {
			if p := pa[u][i]; p != -1 && dv-dep[p] <= val {
				u = p
			}
		}
		diff[v]++
		diff[u]--
	}

	ans := make([]interface{}, n)
	var f2 func(int) int
	f2 = func(v int) (sum int) {
		for _, e := range g[v] {
			sum += f2(e.to)
		}
		ans[v] = sum
		return sum + diff[v]
	}
	f2(0)
	Fprint(out, ans...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF740D(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	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)
	for i := range a {
		a[i] = read()
	}
	type pair struct{ to, l int }
	g := make([][]pair, n)
	for w := 1; w < n; w++ {
		v, l := read()-1, read()
		g[v] = append(g[v], pair{w, l})
	}

	const mx = 19
	pa := make([][mx]int, n)
	dep := make([]int64, n)
	var f func(int, int64)
	f = func(v int, d int64) {
		dep[v] = d
		for _, e := range g[v] {
			w := e.to
			pa[w][0] = v
			f(w, d+int64(e.l))
		}
	}
	pa[0][0] = -1
	f(0, 0)
	for k := 0; k+1 < mx; k++ {
		for v := range pa {
			if p := pa[v][k]; p != -1 {
				pa[v][k+1] = pa[p][k]
			} else {
				pa[v][k+1] = -1
			}
		}
	}

	diff := make([]int, n)
	for v, _val := range a {
		val := int64(_val)
		down := v
	o:
		for {
			ps := pa[v]
			dv := dep[v]
			for i, p := range ps {
				if p == -1 || dv-dep[p] > val {
					if i == 0 {
						break o
					}
					break
				}
				v = p
			}
			val -= dv - dep[v]
		}
		diff[v]--
		diff[down]++
	}

	ans := make([]interface{}, n)
	var f2 func(int) int
	f2 = func(v int) (sum int) {
		for _, e := range g[v] {
			sum += f2(e.to)
		}
		ans[v] = sum
		return sum + diff[v]
	}
	f2(0)
	Fprint(out, ans...)
}

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

package main

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

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

	var n, v, l int
	Fscan(in, &n)
	a := make([]int64, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	type pair struct{ to, l int }
	g := make([][]pair, n)
	for w := 1; w < n; w++ {
		Fscan(in, &v, &l)
		v--
		g[v] = append(g[v], pair{w, l})
	}

	const mx = 19
	pa := make([][mx]int, n)
	dep := make([]int64, n)
	var f func(int, int64)
	f = func(v int, d int64) {
		dep[v] = d
		for _, e := range g[v] {
			w := e.to
			pa[w][0] = v
			f(w, d+int64(e.l))
		}
	}
	pa[0][0] = -1
	f(0, 0)
	for k := 0; k+1 < mx; k++ {
		for v := range pa {
			if p := pa[v][k]; p != -1 {
				pa[v][k+1] = pa[p][k]
			} else {
				pa[v][k+1] = -1
			}
		}
	}

	diff := make([]int, n)
	for v, val := range a {
		down := v
	o:
		for {
			ps := pa[v]
			dv := dep[v]
			for i, p := range ps {
				if p == -1 || dv-dep[p] > val {
					if i == 0 {
						break o
					}
					break
				}
				v = p
			}
			val -= dv - dep[v]
		}
		diff[v]--
		diff[down]++
	}

	ans := make([]int, n)
	var f2 func(int) int
	f2 = func(v int) (sum int) {
		for _, e := range g[v] {
			sum += f2(e.to)
		}
		ans[v] = sum
		return sum + diff[v]
	}
	f2(0)
	for _, v := range ans {
		Fprint(out, v, " ")
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF740D(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	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)
	for i := range a {
		a[i] = read()
	}
	type pair struct{ to, l int }
	g := make([][]pair, n)
	for w := 1; w < n; w++ {
		v, l := read()-1, read()
		g[v] = append(g[v], pair{w, l})
	}

	const mx = 19
	pa := make([][mx]int, n)
	dep := make([]int64, n)
	var f func(int, int64)
	f = func(v int, d int64) {
		dep[v] = d
		for _, e := range g[v] {
			w := e.to
			pa[w][0] = v
			f(w, d+int64(e.l))
		}
	}
	pa[0][0] = -1
	f(0, 0)
	for k := 0; k+1 < mx; k++ {
		for v := range pa {
			if p := pa[v][k]; p != -1 {
				pa[v][k+1] = pa[p][k]
			} else {
				pa[v][k+1] = -1
			}
		}
	}

	diff := make([]int, n)
	for v, _val := range a {
		val := int64(_val)
		down := v
	o:
		for {
			ps := pa[v]
			dv := dep[v]
			for i, p := range ps {
				if p == -1 || dv-dep[p] > val {
					if i == 0 {
						break o
					}
					break
				}
				v = p
			}
			val -= dv - dep[v]
		}
		diff[v]--
		diff[down]++
	}

	ans := make([]int, n)
	var f2 func(int) int
	f2 = func(v int) (sum int) {
		for _, e := range g[v] {
			sum += f2(e.to)
		}
		ans[v] = sum
		return sum + diff[v]
	}
	f2(0)
	for _, v := range ans {
		Fprint(out, v, " ")
	}
}

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

package main

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

func Init() {
}

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

	nodes := make([]*Node, N + 1)
	for i := 1; i <= N; i++ {
	  A := io.NextLong()

	  nodes[i] = NewNode(A)
	}

	for i := 2; i <= N; i++ {
	  P := io.NextInt()
	  W := io.NextLong()

	  nodes[P].children = append(nodes[P].children, NewEdge(W, nodes[i]))
	}

	UpdateDepths(nodes[1], 0)
	UpdateSize(nodes[1])
	CountLoss(nodes[1], make([]*Node, 0))

	for i := 1; i <= N; i++ {
	  fmt.Printf("%d: size = %d, loss = %d, depth = %d\n", i, nodes[i].size, nodes[i].loss, nodes[i].depth)
	}
	UpdateLoss(nodes[1])

	for i := 1; i <= N; i++ {
	  io.Printf("%d ", nodes[i].size - nodes[i].loss - 1)
	}
	io.Println()
}

type Node struct {
  children []*Edge
  value int64
  loss int
  size int
  depth int64
}

func NewNode(v int64) *Node {
  return &Node{
    children: make([]*Edge, 0),
    value: v,
  }
}

func UpdateDepths(u *Node, d int64) {
  if u == nil {
    return
  }
  u.depth = d
  for _, e := range u.children {
    UpdateDepths(e.dest, d + e.weight)
  }
}

func UpdateSize(u *Node) {
  if u == nil {
    return
  }
  u.size = 1
  for _, e := range u.children {
    UpdateSize(e.dest)
    u.size += e.dest.size
  }
}

func findDepth(path []*Node, d int64) *Node {
  L := 0
  R := len(path) - 1
  var good *Node
  // for _, u := range path {
  //   fmt.Printf("%d -> ", u.depth)
  // }
  // fmt.Println()
  for L <= R {
    M := (L + R) >> 1
    if path[M].depth < d {
      // fmt.Printf("  M = %d, depth = %d, want = %d\n", M, path[M].depth, d)
      L = M + 1
      good = path[M]
    } else {
      R = M - 1
    }
  }
  return good
}

func CountLoss(u *Node, path []*Node) {
  which := findDepth(path, u.depth - u.value)
  // fmt.Printf("curr depth = %d, search = %d, which = %+v\n", u.depth, u.depth - u.value, which)
  if which != nil {
    which.loss++
  }
  path = append(path, u)
  for _, e := range u.children {
    CountLoss(e.dest, path)
  }
  path = path[:len(path)-1]
}

func UpdateLoss(u *Node) {
  if u == nil {
    return
  }
  for _, e := range u.children {
    UpdateLoss(e.dest)
    u.loss += e.dest.loss
  }
}

type Edge struct {
  weight int64
  dest *Node
}

func NewEdge(w int64, d *Node) *Edge {
  return &Edge{
    weight: w,
    dest: d,
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

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

type v struct {
	edges []*edge
	id    int
}

type edge struct {
	v int
	w int
}

type pair struct {
	v   int
	sum int
}

var ans []int
var a []int
var g []*v
var x []int

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for scanner.Scan() {
		n, _ := strconv.Atoi(scanner.Text())
		a = make([]int, n)
		ans = make([]int, n)
		x = make([]int, n)
		g = make([]*v, n, n)
		for i := 0; i < n; i++ {
			scanner.Scan()
			a[i], _ = strconv.Atoi(scanner.Text())
			g[i] = &v{make([]*edge, 0), i}
		}
		for i := 0; i < n-1; i++ {
			scanner.Scan()
			var p, w int
			p, _ = strconv.Atoi(scanner.Text())
			scanner.Scan()
			w, _ = strconv.Atoi(scanner.Text())
			g[p-1].edges = append(g[p-1].edges, &edge{i + 1, w})
		}
		root := 0
		stack := make([]*pair, 1)
		stack[0] = &pair{
			v:   root,
			sum: 0,
		}
		dfs(root, stack)
		for i := 0; i < n; i++ {
			fmt.Printf("%d ", ans[i])
		}
		fmt.Print("\n")
	}
}

func dfs(cur int, stack []*pair) {
	l := 0
	r := len(stack) - 1
	totalsum := stack[len(stack)-1].sum
	for l < r {
		mid := (l + r + 1) / 2
		cursum := stack[mid].sum
		if totalsum-cursum <= a[cur] {
			r = mid - 1
		} else {
			l = mid
		}
	}
	if totalsum-stack[l].sum > a[cur] {
		x[stack[l].v]--
	}
	t := 0
	lastsum := stack[len(stack)-1].sum
	for _, edge := range g[cur].edges {
		stack = append(stack, &pair{edge.v, lastsum + edge.w})
		dfs(edge.v, stack)
		stack = stack[:len(stack)-1]
		t += ans[edge.v] + 1
	}
	t += x[cur]
	ans[cur] = t
}