Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire.  Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.

The first line of the input contains an integer n, (1 ≤ n ≤ 100). The next line contains a list of space-separated integers a1, a2, ..., an, (0 ≤ ai ≤ 100).  The third line contains an integer m, (0 ≤ m ≤ 100). Each of the next m lines contains two integers xi and yi. The integers mean that for the i-th time Shaass shoot the yi-th (from left) bird on the xi-th wire, (1 ≤ xi ≤ n, 1 ≤ yi). It's guaranteed there will be at least yi birds on the xi-th wire at that moment.

On the i-th line of the output print the number of birds on the i-th wire.

package main
import (
       	"fmt"
)
func main() {
       	var n,m,x,y int
       	var a [102]int
       	fmt.Scan(&n)
       	for i:=1;i<=n;i++ {
       		fmt.Scan(&a[i])
       	}
       	fmt.Scan(&m)
       	for i:=0;i<m;i++ {
       		fmt.Scan(&x,&y)
       		a[x-1]+=(y-1)
       		a[x+1]+=(a[x]-y)
       		a[x]=0
       	}
       	for i:=1;i<=n;i++ {
       		fmt.Println(a[i])
       	}

}

package main

import "fmt"

func main() {
    var n,m,x,y int
    var a [105]int
    fmt.Scan(&n)
    for i := 1; i <= n; i++ { fmt.Scan(&a[i]) }
    fmt.Scan(&m)
    for i := 0; i < m; i++ {
        fmt.Scan(&x,&y)
        if x != 1 { a[x-1] += y-1 }
        if x != n { a[x+1] += a[x]-y }
        a[x] = 0
    }
    for i := 1; i <= n; i++ { fmt.Println(a[i]) }
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	birds := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&birds[i])
	}

	var m int
	fmt.Scan(&m)
	// fmt.Println("m::", m)
	for i := 0; i < m; i++ {
		var y, x int
		fmt.Scan(&x)
		fmt.Scan(&y)
		x -= 1
		// fmt.Println(y, x)
		if x > 0 {
			birds[x-1] += y - 1
		}
		// fmt.Println("check:", x, m-1, x < m, birds[x]-y)
		if x < n-1 {
			birds[x+1] += birds[x] - y
		}
		birds[x] = 0
		// fmt.Println("ans:", birds[x-1], birds[x], birds[x+1])
	}
	// fmt.Println(birds)
	// fmt.Println(n, m)
	for _, i := range birds {
		fmt.Println(i)
	}
}

package main
import "fmt"

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

	var arr = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&arr[i])
	}

	var m int
	var x, y int
	fmt.Scan(&m)

	for i := 0; i < m; i++ {
		fmt.Scan(&x,&y)
		if x == 1 {
			if x < n{
				arr[x]= arr[x] + (arr[x-1] - y)
			}
			arr[x-1] = 0
		}else if x == n {
			if x-2 >= 0 {
				arr[x-2] = arr[x-2] + (y - 1)
			}
			arr[x-1] = 0
		}else{
			if x-2 >= 0 {
				arr[x-2] = arr[x-2] + (y -1)
			}
			if x < n{
				arr[x]= arr[x] + (arr[x-1] - y)
			}
			arr[x-1]= 0
		}
	}
	for i := 0; i < n; i++ {
		fmt.Println(arr[i])
	}

}

package main

import "fmt"

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

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

	var m int
	fmt.Scan(&m)

	var x, y int
	for i := 0; i < m; i++ {
		fmt.Scan(&x, &y)
		if x <= n-1 {
			an[x] += an[x-1] - y
		}
		if x > 1 {
			an[x-2] += y - 1
		}
		an[x-1] = 0
	}

	for i := 0; i < n; i++ {
		fmt.Println(an[i])
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var numberOfBirdLines int
	fmt.Fscan(reader, &numberOfBirdLines)
	birdsNumberArray := make([]int, numberOfBirdLines)
	for index := 0; index < numberOfBirdLines; index++ {
		fmt.Fscan(reader, &birdsNumberArray[index])
	}
	var numberOfShoots, shootedLine, shootedBird int
	fmt.Fscan(reader, &numberOfShoots)
	for index := 0; index < numberOfShoots; index++ {
		fmt.Fscan(reader, &shootedLine)
		fmt.Fscan(reader, &shootedBird)

		if shootedLine != 1 {
			birdsNumberArray[shootedLine-2] += (shootedBird - 1)
		}
		if shootedLine != numberOfBirdLines {
			birdsNumberArray[shootedLine] += (birdsNumberArray[shootedLine-1] - shootedBird)
		}
		birdsNumberArray[shootedLine-1] = 0
	}
	for _, elemenet := range birdsNumberArray {
		fmt.Println(elemenet)
	}
}

package main

import "fmt"

func main()  {
	var noOfWires int
	fmt.Scan(&noOfWires)
	var noOfBirdsBerWire [] int
	for index := 0; index < noOfWires; index++ {
		var noOfBirds int
		fmt.Scan(&noOfBirds)
		noOfBirdsBerWire = append(noOfBirdsBerWire, noOfBirds)
	}
	var noOfShoots int
	fmt.Scan(&noOfShoots)
	for index := 0; index < noOfShoots; index++ {
		var rowNo int
		fmt.Scan(&rowNo)
		var birdNo int
		fmt.Scan(&birdNo)
		targetRow := rowNo - 1
		noOfBirdsInTargetRow := noOfBirdsBerWire[targetRow]
		leftBirdsNo := birdNo - 1
		rightBirdsNo := noOfBirdsInTargetRow - birdNo
		if birdNo == 1 {
			leftBirdsNo = 0
		}
		if birdNo == noOfBirdsInTargetRow {
			rightBirdsNo = 0
		}
		noOfBirdsBerWire[targetRow] = 0
		if (targetRow != 0 ){
			noOfBirdsBerWire[targetRow - 1] = leftBirdsNo +  noOfBirdsBerWire[targetRow-1]
		}
		if (targetRow + 1 < noOfWires) {
			noOfBirdsBerWire[targetRow + 1] = rightBirdsNo +  noOfBirdsBerWire[targetRow+1]
		}
	}
	for index := 0; index < len(noOfBirdsBerWire); index++ {
		fmt.Println(noOfBirdsBerWire[index])
	}
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	birds := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&birds[i])
	}

	var m int
	fmt.Scan(&m)
	// fmt.Println("m::", m)
	for i := 0; i < m; i++ {
		var y, x int
		fmt.Scan(&x)
		fmt.Scan(&y)
		x -= 1
		// fmt.Println(y, x)
		if x > 0 {
			birds[x-1] += y - 1
		}
		// fmt.Println("check:", x, m-1, x < m, birds[x]-y)
		if x < m {
			birds[x+1] += birds[x] - y
		}
		birds[x] = 0
		// fmt.Println("ans:", birds[x-1], birds[x], birds[x+1])
	}
	// fmt.Println(birds)
	// fmt.Println(n, m)
	for _, i := range birds {
		fmt.Println(i)
	}
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	birds := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&birds[i])
	}

	var m int
	fmt.Scan(&m)
	// fmt.Println(m)
	for i := 0; i < m; i++ {
		var y, x int
		fmt.Scan(&x)
		fmt.Scan(&y)
		x -= 1
		// fmt.Println(y, x)
		if x != 0 {
			birds[x-1] += y - 1
		}
		if x != m-1 {
			birds[x+1] += birds[x] - y
		}
		birds[x] = 0
	}
	// fmt.Println(birds)
	// fmt.Println(n, m)
	for _, i := range birds {
		fmt.Println(i)
	}
}


Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 > c_1$$$, then to some other city $$$c_3 > c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k > c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey:  $$$c = [1, 2, 4]$$$;  $$$c = [3, 5, 6, 8]$$$;  $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.

Print one integer — the maximum beauty of a journey Tanya can choose.

NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
	"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 main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, 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()
	b := make([][2]int, n)
	var maxSum int64
	for i := 0; i < n; i++ {
		b[i][0] = NextInt()
		if i == 0 || int64(b[i][0]) > maxSum {
			maxSum = int64(b[i][0])
		}
		b[i][1] = i + 1
	}
	sort.Slice(b, func(i, j int) bool {
		return b[i][0]-b[i][1] <= b[j][0]-b[j][1]
	})

	var lastValue int
	var curSum int64
	for i := 0; i < n; i++ {
		if i == 0 || b[i][0]-b[i][1] != lastValue {
			lastValue = b[i][0] - b[i][1]
			curSum = int64(0)
		}
		curSum += int64(b[i][0])
		if curSum > maxSum {
			maxSum = curSum
		}
	}
	fmt.Fprintln(out, maxSum)
}

package main

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

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

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

	mp := make(map[int]int64)
	best := int64(0)
	for i := 0; i < n; i++ {
		var b int
		fmt.Fscanf(r, "%d", &b)
		b -= i
		mp[b] += int64(b + i)
		best = max(best, mp[b])
	}

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

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

package main

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

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	if n == 1 {
		Fprintln(out, a[0])
		return
	}

	mp := map[int64]int64{}

	for i, v := range a {
		mp[v-int64(i)]+=v
	}

	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}
	ans := int64(0)
	for _, v := range mp {
		ans = max(ans, v)
	}
	Fprintln(out, ans)

}

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

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanWords)

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

	n := in()
	a := make([]int, n)

	for i := range a {
		a[i] = in()
	}

	m := make(map[int][]int)

	for i := range a {
		val := a[i] - i

		if m[val] == nil {
			m[val] = make([]int, 0)
		}

		m[val] = append(m[val], i)
	}

	maxsum := int64(0)

	for k, l := range m {
		sum := int64(k) * int64(len(l))

		for i := range l {
			sum += int64(l[i])
		}

		if sum > maxsum {
			maxsum = sum
		}
	}

	fmt.Println(maxsum)
}

/*
URL:
https://codeforces.com/problemset/problem/1320/A
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	n int
	B []int64

	memo map[int64]int64
)

func main() {
	n = ReadInt()
	B = ReadInt64Slice(n)

	memo = make(map[int64]int64)
	for i := 0; i < n; i++ {
		memo[B[i]-int64(i)] += B[i]
	}

	ans := int64(0)
	for _, v := range memo {
		ChMax(&ans, v)
	}
	fmt.Println(ans)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(r, &n)
	b := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(r, &b[i])
	}
	rls := solve(n, b)
	fmt.Println(rls)
}

func solve(n int, b []int) int64 {
	mp := make(map[int]int64)
	for i := 0; i < n; i++ {
		mp[b[i]-i] += int64(b[i])
	}
	rls := int64(0)
	for _, v := range mp {
		if rls < v {
			rls = v
		}
	}
	return rls
}

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(r, &n)

	rls := int64(0)
	mp := make(map[int]int64)
	for i := 0; i < n; i++ {
		var b int
		fmt.Fscan(r, &b)
		b -= i
		mp[b] += int64(b + i)
		if rls < mp[b] {
			rls = mp[b]
		}
	}
	fmt.Println(rls)
}

package main

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

var a[600005] int64
var ans int64
func main() {

	n:=ReadInt()
	for i:=1;i<=n;i++ {
		x:=ReadInt()
		a[x+200000-i]+=int64(x)
		ans=max(ans,a[x+200000-i])
	}
	fmt.Println(ans)
}
////////////////////////////////////

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

var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup

func ReadString() string {
	in.Scan()
	return in.Text()
}
func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}
func ReadInt() int {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 32)
	return int(i)
}
func ReadIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt()
	}
	return arr
}
func init() {
	//set input
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	//set output
	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(write *bufio.Writer) {
		defer outWg.Done()
		defer write.Flush()

		for line := range out {
			write.WriteString(line + "\n")
		}
	}(writer)
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanWords)

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

	n := in()
	a := make([]int, n)

	for i := range a {
		a[i] = in()
	}

	m := make(map[int][]int)

	for i := range a {
		val := a[i] - i

		if m[val] == nil {
			m[val] = make([]int, 0)
		}

		m[val] = append(m[val], i)
	}

	maxsum := 0

	for k, l := range m {
		sum := k * len(l)

		for i := range l {
			sum += l[i]
		}

		if sum > maxsum {
			maxsum = sum
		}
	}

	fmt.Println(maxsum)
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanWords)

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

	n := in()
	a := make([]int, n)

	for i := range a {
		a[i] = in()
	}

	m := make(map[int][]int)

	for i := range a {
		val := a[i] - i

		if m[val] == nil {
			m[val] = make([]int, 0)
		}

		m[val] = append(m[val], i)
	}

	maxsum := int64(0)

	for k, l := range m {
		sum := k * len(l)

		for i := range l {
			sum += l[i]
		}

		if int64(sum) > maxsum {
			maxsum = int64(sum)
		}
	}

	fmt.Println(maxsum)
}

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scan(r, &n)

	rls := int64(0)
	mp := make(map[int]int64)
	for i := 0; i < n; i++ {
		var b int
		fmt.Scan(r, &b)
		b -= i
		mp[b] += int64(b + i)
		if rls < mp[b] {
			rls = mp[b]
		}
	}
	fmt.Println(rls)
}

package main

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

var a[600005] int
var ans int
func main() {

	n:=ReadInt()
	for i:=1;i<=n;i++ {
		x:=ReadInt()
		a[x+200000-i]+=x
		ans=max(ans,a[x+200000-i])
	}
	fmt.Println(ans)
}
////////////////////////////////////

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

var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup

func ReadString() string {
	in.Scan()
	return in.Text()
}
func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}
func ReadInt() int {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 32)
	return int(i)
}
func ReadIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt()
	}
	return arr
}
func init() {
	//set input
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	//set output
	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(write *bufio.Writer) {
		defer outWg.Done()
		defer write.Flush()

		for line := range out {
			write.WriteString(line + "\n")
		}
	}(writer)
}


You are given a description of a depot. It is a rectangular checkered field of n × m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y.You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the depot field.  The next n lines contain m symbols "." and "*" each — the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall.

If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line — the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them.

package main

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

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

var n, m, walls int
var a []string
var row, col []int

func solution() {
	for i := range a {
		for j, c := range a[i] {
			bomb := row[i] + col[j]
			if c == '*' {
				bomb--
			}
			if bomb == walls {
				fmt.Fprintln(bufout, "YES")
				fmt.Fprintln(bufout, i+1, j+1)
				return
			}
		}
	}
	fmt.Fprintln(bufout, "NO")
}

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

	fmt.Fscan(bufin, &n, &m)

	a = make([]string, n)
	row = make([]int, n)
	col = make([]int, m)

	for i := range row {
		row[i] = 0
	}
	for i := range col {
		col[i] = 0
	}
	walls = 0

	for i := range a {
		fmt.Fscan(bufin, &a[i])
		for j, c := range a[i] {
			if c == '*' {
				walls++
				row[i]++
				col[j]++
			}
		}
	}

	solution()
}

package main

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

func findFirst(rows []string) (int, int, bool) {
	for i, row := range rows {
		for j, ch := range row {
			if ch == '*' {
				return i, j, true
			}
		}
	}
	return 0, 0, false
}

func combForRow(rows []string, ti int) (int, bool) {
	tj := -1
	for i, row := range rows {
		for j, ch := range row {
			if ch == '*' && i != ti && j != tj {
				if tj < 0 {
					tj = j
				} else {
					return 0, false
				}
			}
		}
	}
	if tj >= 0 {
		return tj, true
	}
	return 0, true
}

func combForColumn(rows []string, tj int) (int, bool) {
	ti := -1
	for i, row := range rows {
		for j, ch := range row {
			if ch == '*' && i != ti && j != tj {
				if ti < 0 {
					ti = i
				} else {
					return 0, false
				}
			}
		}
	}
	if ti >= 0 {
		return ti, true
	}
	return 0, true
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)

	scanner.Scan()
	var n, m int
	fmt.Sscanf(scanner.Text(), "%d%d", &n, &m)

	rows := make([]string, n)
	for i := range rows {
		scanner.Scan()
		rows[i] = scanner.Text()
	}

	fi, fj, found := findFirst(rows)
	if !found {
		fmt.Println("YES")
		fmt.Println("1 1")
		return
	}

	if tj, found := combForRow(rows, fi); found {
		fmt.Println("YES")
		fmt.Printf("%d %d\n", fi+1, tj+1)
		return
	}
	if ti, found := combForColumn(rows, fj); found {
		fmt.Println("YES")
		fmt.Printf("%d %d\n", ti+1, fj+1)
		return
	}
	fmt.Println("NO")
}


Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!

The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, ) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively. Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.

Print the maximum total friendship factir that can be reached.

NoteIn the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.In the second sample test we can take all the friends.

package main

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

type Friend struct {
	Money int
	FFactor uint64
}

type FriendList []Friend

func (f FriendList) Len() int {
	return len(f)
}

func (f FriendList) Less(i, j int) bool {
	return f[i].Money < f[j].Money
}

func (f FriendList) Swap(i, j int) {
	f[i], f[j] = f[j], f[i]
}

func BruteForce() {
	scanner := bufio.NewScanner(os.Stdin)

	var n, m int
	fmt.Scan(&n, &m)
	scanner.Split(bufio.ScanWords)

	friends := make(FriendList, n)

	for i := 0; i < n; i++ {
		for scanner.Scan() {
			if scanner.Text() != "" { break }
		}

		money, _ := strconv.Atoi(scanner.Text())

		scanner.Scan()
		ffactor, _ := (strconv.ParseInt(scanner.Text(), 10, 64))

		friends[i] = Friend{money, uint64(ffactor)}
	}

	maxTotal := uint64(0)
	for i := 0; i < n; i++ {
		total := friends[i].FFactor
		for j := 0; j < n; j++ {
			if i == j {
				continue
			}

			diff := friends[j].Money - friends[i].Money
			if diff < m && diff > -m {
				total += friends[j].FFactor
			}
		}
		if total > maxTotal {
			maxTotal = total
		}
	}

	fmt.Println(maxTotal)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)

	var n, m int
	fmt.Scan(&n, &m)
	scanner.Split(bufio.ScanWords)

	friends := make(FriendList, n)

	for i := 0; i < n; i++ {
		for scanner.Scan() {
			if scanner.Text() != "" { break }
		}

		money, _ := strconv.Atoi(scanner.Text())

		scanner.Scan()
		ffactor, _ := strconv.ParseInt(scanner.Text(), 10, 64)

		friends[i] = Friend{money, uint64(ffactor)}
	}
	sort.Sort(friends)

	maxTotal := uint64(0)
	total := uint64(0)
	left, right := 0, 0

	for i := 0; i < n; i++ {
		for left < right && friends[i].Money - friends[left].Money >= m {
			total -= friends[left].FFactor
			left++
		}

		for right < n && friends[right].Money - friends[left].Money < m {
			total += friends[right].FFactor
			right++
		}

		if total > maxTotal {
			maxTotal = total
		}
	}

	fmt.Println(maxTotal)
}

package main

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

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

type Friend struct {
	money, fFactor int64
}

type ByMoney []Friend

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

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n, d := nextInt(), nextInt64()
	friends := make([]Friend, n)

	for i := range friends {
		friends[i].money = nextInt64()
		friends[i].fFactor = nextInt64()
	}

	var last, curFac, maxFac int64

	sort.Sort(ByMoney(friends))

	for i := 0; i < n; i++ {
		curFac += friends[i].fFactor

		for friends[i].money-friends[last].money >= d {
			curFac -= friends[last].fFactor
			last++
		}

		if curFac > maxFac {
			maxFac = curFac
		}
	}

	println(maxFac)
}

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

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

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

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

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

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

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	// Read n and d
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())
	if err != nil {
		return
	}
	scanner.Scan()
	d, err := strconv.Atoi(scanner.Text())
	if err != nil {
		return
	}

	// Read money and friendship
	money := make([]int, n)
	friendship := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		m, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		money[i] = m

		scanner.Scan()
		s, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		friendship[i] = s
	}

	if n == 1 {
		fmt.Println(friendship[0])
		return
	}

	merge_sort(money, friendship, 0, n-1)

	var max_ffactor int64 = 0
	var ffactor int64 = int64(friendship[0])

	start := 0
	end := 1
	for end < n && money[end] < money[start]+d {
		ffactor += int64(friendship[end])
		end++
	}
	max_ffactor = ffactor
	for end < n {
		// Move start pointer forward
		p := start
		for p < n && money[p] == money[start] {
			ffactor -= int64(friendship[p])
			p++
		}
		start = p
		// Move end pointer forward
		for end < n && money[end] < money[start]+d {
			ffactor += int64(friendship[end])
			end++
		}
		// See if ffactor gets larger
		if ffactor > max_ffactor {
			max_ffactor = ffactor
		}
	}

	fmt.Println(max_ffactor)
}

func merge_sort(buffer, company []int, start, end int) {
	if end > start {
		middle := (end + start) / 2
		merge_sort(buffer, company, start, middle)
		merge_sort(buffer, company, middle+1, end)
		merge(buffer, company, start, middle, end)
	}
}

func merge(buffer, company []int, start, middle, end int) {
	sorted := make([]int, end-start+1)
	c := make([]int, end-start+1)

	i := start
	j := middle + 1
	k := 0
	for i <= middle && j <= end {
		if buffer[i] <= buffer[j] {
			sorted[k] = buffer[i]
			c[k] = company[i]
			i++
		} else {
			sorted[k] = buffer[j]
			c[k] = company[j]
			j++
		}
		k++
	}
	for i <= middle {
		sorted[k] = buffer[i]
		c[k] = company[i]
		k++
		i++
	}
	for j <= end {
		sorted[k] = buffer[j]
		c[k] = company[j]
		k++
		j++
	}

	i = start
	k = 0
	for i <= end {
		buffer[i] = sorted[k]
		company[i] = c[k]
		i++
		k++
	}
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	// Read n and d
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())
	if err != nil {
		return
	}
	scanner.Scan()
	d, err := strconv.Atoi(scanner.Text())
	if err != nil {
		return
	}

	// Read friends
	money := make([]int, n)
	friendship := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		m, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		money[i] = m

		scanner.Scan()
		s, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		friendship[i] = s
	}

	if n == 1 {
		fmt.Println(friendship[0])
		return
	}

	merge_sort(money, friendship, 0, n-1)

	var max_ffactor int64 = 0
	var ffactor int64 = int64(friendship[0])

	start := 0
	end := 1
	for end < n && money[end] < money[start]+d {
		ffactor += int64(friendship[end])
		end++
	}
	max_ffactor = ffactor
	for end < n {
		// Move start pointer forward
		p := start
		for p < n && money[p] == money[start] {
			ffactor -= int64(friendship[p])
			p++
		}
		start = p
		// Move end pointer forward
		for end < n && money[end] < money[start]+d {
			ffactor += int64(friendship[end])
			end++
		}
		// See if ffactor gets larger
		if ffactor > max_ffactor {
			max_ffactor = ffactor
		}
	}

	fmt.Println(max_ffactor)
}

func merge_sort(buffer, company []int, start, end int) {
	if end > start {
		middle := (end + start) / 2
		merge_sort(buffer, company, start, middle)
		merge_sort(buffer, company, middle+1, end)
		merge(buffer, company, start, middle, end)
	}
}

func merge(buffer, company []int, start, middle, end int) {
	sorted := make([]int, end-start+1)
	c := make([]int, end-start+1)

	i := start
	j := middle + 1
	k := 0
	for i <= middle && j <= end {
		if buffer[i] <= buffer[j] {
			sorted[k] = buffer[i]
			c[k] = company[i]
			i++
		} else {
			sorted[k] = buffer[j]
			c[k] = company[j]
			j++
		}
		k++
	}
	for i <= middle {
		sorted[k] = buffer[i]
		c[k] = company[i]
		k++
		i++
	}
	for j <= end {
		sorted[k] = buffer[j]
		c[k] = company[j]
		k++
		j++
	}

	i = start
	k = 0
	for i <= end {
		buffer[i] = sorted[k]
		company[i] = c[k]
		i++
		k++
	}
}

package main

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

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

func init() {
	in.Split(bufio.ScanWords)
	buf := make([]byte, 2500000, 2500000)
	in.Buffer(buf, 0)
}
func exit() {
	out.Flush()
}

// io
func nextInt() int {
	in.Scan()
	ret, _ := strconv.Atoi(in.Text())
	return ret
}

func nextString() string {
	in.Scan()
	return in.Text()
}
func nextBytes() []byte {
	in.Scan()
	return in.Bytes()
}

/*
 */
var nums int
var fear int

type weapon struct {
	crary int
	force int
}
type weapons []weapon

var w weapons

func (wps weapons) Len() int {
	return len(wps)
}
func (wps weapons) Less(i, j int) bool {
	return wps[i].crary < wps[j].crary
}
func (wps weapons) Swap(i, j int) {
	wps[i], wps[j] = wps[j], wps[i]
}
func main() {
	defer exit()
	nums = nextInt()
	fear = nextInt()
	w = make(weapons, nums+1, nums+1)
	for i := 1; i != nums+1; i++ {
		w[i].crary = nextInt()
		w[i].force = nextInt()
	}
	sort.Sort(w[1:])
	lastLeft := -1
	myLastForce := int64(-1)
	leftForce := int64(0)
	for i := 1; i != nums+1; i++ {
		l := i
		r := nums
		for {
			if l == r {
				break
			}
			mid := (l + r + 1) / 2
			midv := (w[mid].crary - w[i].crary - fear) < 0
			if midv {
				l = mid
			} else {
				r = mid - 1
			}
		}
		var tempForce int64
		if l > lastLeft {
			tempForce = leftForce - int64(w[i-1].force)
			for j := lastLeft + 1; j != l+1; j++ {
				tempForce += int64(w[j].force)
			}
			leftForce = tempForce
		} else {
			tempForce = leftForce - int64(w[i-1].force)
			leftForce = tempForce
		}
		lastLeft = l
		if myLastForce < leftForce {
			myLastForce = leftForce
		}
	}
	fmt.Fprintf(out, "%d\n", myLastForce)
}

package main

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

type Friend struct {
	money, lvl int
}

type Friends []Friend

func (c Friends) Len() int           { return len(c) }
func (c Friends) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c Friends) Less(i, j int) bool { return c[i].money < c[j].money }

func main() {
	reader := bufio.NewReader(os.Stdin)
	var fr, d int
	fmt.Fscan(reader, &fr, &d)
	friends := make(Friends, fr)

	for i := 0; i < fr; i++ {
		fmt.Fscan(reader, &friends[i].money, &friends[i].lvl)
	}

	var cnt, mx int64
	j := 0
	sort.Sort(friends)
	for i := 0; i < fr; i++ {
		for ; j < fr && friends[i].money+d > friends[j].money; j++ {
			mx += int64(friends[j].lvl)
		}
		if cnt < mx {
			cnt = mx
		}
		if j == fr {
			break
		}
		mx -= int64(friends[i].lvl)
	}

	fmt.Println(cnt)
}

package main

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

type friend struct {
	m, s int
}

type bym []friend

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

func handleInput() (int, []friend) {
	n, d := nextInt(), nextInt()
	friends := make([]friend, n)
	for i := 0; i < n; i++ {
		friends[i].m, friends[i].s = nextInt(), nextInt()
	}
	return d, friends
}

func solve(d int, friends []friend) int64 {
	var max int64

	sort.Sort(bym(friends))
	sums := make([]int64, len(friends)+1)
	for i, f := range friends {
		sums[i+1] = sums[i] + int64(f.s)
	}
	for i, f := range friends {
		subfriends := friends[i:]
		j := sort.Search(len(subfriends),
			func(k int) bool {
				return subfriends[k].m >= f.m+d
			}) + i

		sum := sums[j] - sums[i]
		if max < sum {
			max = sum
		}

		if j == len(friends) {
			break
		}
	}
	return max
}

func main() {
	//defer profile.Start(profile.ProfilePath(".")).Stop()
	defer flush()
	printn(solve(handleInput()))
}

func init() {
	scanner.Split(bufio.ScanWords)
}

var scanner = bufio.NewScanner(os.Stdin)

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

func nextWord() string {
	return next()
}

func nextLine() string {
	defer scanner.Split(bufio.ScanWords)
	scanner.Split(bufio.ScanLines)
	return strings.TrimSpace(next())
}

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

var stdout = bufio.NewWriter(os.Stdout)

func printa(a ...interface{}) (int, error) {
	return fmt.Fprint(stdout, a...)
}

func printn(a ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, a...)
}

func printf(format string, a ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, format, a...)
}

func flush() error {
	return stdout.Flush()
}

package main

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

type friend struct {
	m, s int
}

type bym []friend

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

func handleInput() (int, []friend) {
	var n, d int
	stdin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(stdin, "%d %d\n", &n, &d)
	friends := make([]friend, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(stdin, "%d %d\n", &(friends[i].m), &(friends[i].s))
	}
	return d, friends
}

func solve(d int, friends []friend) int64 {
	var max int64

	sort.Sort(bym(friends))
	sums := make([]int64, len(friends)+1)
	for i, f := range friends {
		sums[i+1] = sums[i] + int64(f.s)
	}
	for i, f := range friends {
		subfriends := friends[i:]
		j := sort.Search(len(subfriends),
			func(k int) bool {
				return subfriends[k].m >= f.m+d
			}) + i

		sum := sums[j] - sums[i]
		if max < sum {
			max = sum
		}

		if j == len(friends) {
			break
		}
	}
	return max
}

func main() {
	fmt.Println(solve(handleInput()))
}

package main

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

type fr struct {
	m uint32
	s uint64
}

func _580B() {

	var n int
	var d uint32
	var max_fs, fs uint64

	r := bufio.NewReader(os.Stdin)
	fmt.Fscanf(r, "%d %d\n", &n, &d)
	fl := make([]fr, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &fl[i].m, &fl[i].s)
	}

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

	j := 0
	for i := 0; i < n && j < n; fs, i = fs-fl[i].s, i+1 {

		for j < n && fl[j].m-fl[i].m < d {
			fs += fl[j].s
			j++
		}
		if fs > max_fs {
			max_fs = fs
		}

	}
	fmt.Println(max_fs)
}

func main() {
	_580B()
}

package main

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

type Pair struct{ first, second int }
type Pairs []Pair

func (p Pairs) Len() int           { return len(p) }
func (p Pairs) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p Pairs) Less(i, j int) bool { return p[i].first < p[j].first }

var (
	n, d int
	a    Pairs
)

func main() {
	// file, _ := os.Open("input.txt")
	file := os.Stdin
	f := bufio.NewReader(file)
	fmt.Fscanf(f, "%d %d\n", &n, &d)
	a = make([]Pair, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%d %d\n", &a[i].first, &a[i].second)
	}
	sort.Sort(a)
	var current_total_money, current_total_factor int64 = 0, 0
	var total_factor int64 = 0
	j := 0
	for i := 0; i < n; i++ {
		for ; j < n && a[i].first+d > a[j].first; j++ {
			current_total_money += int64(a[j].first)
			current_total_factor += int64(a[j].second)
		}
		if total_factor < current_total_factor {
			total_factor = current_total_factor
		}
		current_total_money -= int64(a[i].first)
		current_total_factor -= int64(a[i].second)
	}
	fmt.Println(total_factor)
}

// cf580b project main.go
package main

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

type I6 [][]int64

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

func ReadInt32() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}
func ReadInt64() int64 {
	scanner.Scan()
	ans, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return ans
}
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)
	n := ReadInt32()
	d := ReadInt32()
	var l [][]int64
	for i := 0; i < n; i++ {
		l = append(l, []int64{ReadInt64(), ReadInt64()})
	}

	sort.Sort(I6(l))
	/*
		for i := n - 1; i >= 0; i-- {
			for j := 0; j < i; j++ {
				if l[j][0] > l[j+1][0] {
					l[j], l[j+1] = l[j+1], l[j]
				}
			}
		}

	*/
	var k, j int64
	s := 0
	for e := -1; e < n-1; {
		e++
		j += l[e][1]
		for ; l[e][0]-l[s][0] >= int64(d); s++ {
			j -= l[s][1]
		}

		if j > k {
			k = j
		}
	}

	fmt.Println(k)

}

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

package main

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

type Friend struct {
	Money int
	FFactor int
}

type FriendList []Friend

func (f FriendList) Len() int {
	return len(f)
}

func (f FriendList) Less(i, j int) bool {
	return f[i].Money < f[j].Money
}

func (f FriendList) Swap(i, j int) {
	f[i], f[j] = f[j], f[i]
}

func BruteForce() {
	scanner := bufio.NewScanner(os.Stdin)

	var n, m int
	fmt.Scan(&n, &m)
	scanner.Split(bufio.ScanWords)

	friends := make(FriendList, n)

	for i := 0; i < n; i++ {
		for scanner.Scan() {
			if scanner.Text() != "" { break }
		}

		money, _ := strconv.Atoi(scanner.Text())

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

		friends[i] = Friend{money, ffactor}
	}

	maxTotal := 0
	for i := 0; i < n; i++ {
		total := friends[i].FFactor
		for j := 0; j < n; j++ {
			if i == j {
				continue
			}

			diff := friends[j].Money - friends[i].Money
			if diff < m && diff > -m {
				total += friends[j].FFactor
			}
		}
		if total > maxTotal {
			maxTotal = total
		}
	}

	fmt.Println(maxTotal)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)

	var n, m int
	fmt.Scan(&n, &m)
	scanner.Split(bufio.ScanWords)

	friends := make(FriendList, n)

	for i := 0; i < n; i++ {
		for scanner.Scan() {
			if scanner.Text() != "" { break }
		}

		money, _ := strconv.Atoi(scanner.Text())

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

		friends[i] = Friend{money, ffactor}
	}
	sort.Sort(friends)

	maxTotal := 0
	total := 0
	left, right := 0, 0

	for i := 0; i < n; i++ {
		for left < right && friends[i].Money - friends[left].Money >= m {
			total -= friends[left].FFactor
			left++
		}

		for right < n && friends[right].Money - friends[left].Money < m {
			total += friends[right].FFactor
			right++
		}

		if total > maxTotal {
			maxTotal = total
		}
	}

	fmt.Println(maxTotal)
}

package main

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

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

type Friend struct {
	money, fFactor int
}

type ByMoney []Friend

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

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n, d := nextInt(), nextInt()
	friends := make([]Friend, n)

	for i := range friends {
		friends[i].money = nextInt()
		friends[i].fFactor = nextInt()
	}

	last := 0
	curFac, maxFac := 0, 0

	sort.Sort(ByMoney(friends))

	for i := 0; i < n; i++ {
		curFac += friends[i].fFactor

		for friends[i].money-friends[last].money >= d {
			curFac -= friends[last].fFactor
			last++
		}

		if curFac > maxFac {
			maxFac = curFac
		}
	}

	println(maxFac)
}

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

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

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

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

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

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

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	// Read n and d
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())
	if err != nil {
		return
	}
	scanner.Scan()
	d, err := strconv.Atoi(scanner.Text())
	if err != nil {
		return
	}

	// Read friends
	money := make([]int, n)
	friendship := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		m, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		money[i] = m

		scanner.Scan()
		s, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		friendship[i] = s
	}

	if n == 1 {
		fmt.Println(friendship[0])
		return
	}

	quick_sort(money, friendship, 0, n-1)

	max_ffactor := 0

	ffactor := friendship[0]
	start := 0
	end := 1
	for end < n && money[end] < money[start]+d {
		ffactor += friendship[end]
		end++
	}
	max_ffactor = ffactor
	for end < n {
		// Move start pointer forward
		p := start
		for p < n && money[p] == money[start] {
			ffactor -= friendship[p]
			p++
		}
		start = p
		for end < n && money[end] < money[start]+d {
			ffactor += friendship[end]
			end++
		}
		if ffactor > max_ffactor {
			max_ffactor = ffactor
		}
	}
	if ffactor > max_ffactor {
		max_ffactor = ffactor
	}

	fmt.Println(max_ffactor)
}

func quick_sort(array, company []int, start, end int) {
	if start < end {
		p := partition(array, company, start, end)
		quick_sort(array, company, start, p-1)
		quick_sort(array, company, p+1, end)
	}
}

func partition(array, company []int, start, end int) int {
	pivot := array[end]
	i := start
	for j := start; j < end; j++ {
		if array[j] <= pivot {
			swap(array, i, j)
			swap(company, i, j)
			i++
		}
	}
	swap(array, i, end)
	swap(company, i, end)
	return i
}

func swap(array []int, i, j int) {
	if i != j {
		tmp := array[i]
		array[i] = array[j]
		array[j] = tmp
	}
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	// Read n and d
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())
	if err != nil {
		return
	}
	scanner.Scan()
	d, err := strconv.Atoi(scanner.Text())
	if err != nil {
		return
	}

	// Read friends
	money := make([]int, n)
	friendship := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		m, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		money[i] = m

		scanner.Scan()
		s, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		friendship[i] = s
	}

	if n == 1 {
		fmt.Println(friendship[0])
		return
	} else {
		fmt.Println(friendship[0])
		return
	}

	quick_sort(money, friendship, 0, n-1)

	var max_ffactor int64 = 0
	var ffactor int64 = int64(friendship[0])

	start := 0
	end := 1
	for end < n && money[end] < money[start]+d {
		ffactor += int64(friendship[end])
		end++
	}
	max_ffactor = ffactor
	for end < n {
		// Move start pointer forward
		p := start
		for p < n && money[p] == money[start] {
			ffactor -= int64(friendship[p])
			p++
		}
		start = p
		for end < n && money[end] < money[start]+d {
			ffactor += int64(friendship[end])
			end++
		}
		if ffactor > max_ffactor {
			max_ffactor = ffactor
		}
	}
	if ffactor > max_ffactor {
		max_ffactor = ffactor
	}

	fmt.Println(max_ffactor)
}

func quick_sort(array, company []int, start, end int) {
	if start < end {
		p := partition(array, company, start, end)
		quick_sort(array, company, start, p-1)
		quick_sort(array, company, p+1, end)
	}
}

func partition(array, company []int, start, end int) int {
	pivot := array[end]
	i := start
	for j := start; j < end; j++ {
		if array[j] <= pivot {
			swap(array, i, j)
			swap(company, i, j)
			i++
		}
	}
	swap(array, i, end)
	swap(company, i, end)
	return i
}

func swap(array []int, i, j int) {
	if i != j {
		tmp := array[i]
		array[i] = array[j]
		array[j] = tmp
	}
}

package main

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

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

func init() {
	in.Split(bufio.ScanWords)
	buf := make([]byte, 2500000, 2500000)
	in.Buffer(buf, 0)
}
func exit() {
	out.Flush()
}

// io
func nextInt() int {
	in.Scan()
	ret, _ := strconv.Atoi(in.Text())
	return ret
}

func nextString() string {
	in.Scan()
	return in.Text()
}
func nextBytes() []byte {
	in.Scan()
	return in.Bytes()
}

/*
 */
var nums int
var fear int

type weapon struct {
	crary int
	force int
}
type weapons []weapon

var w weapons

func (wps weapons) Len() int {
	return len(wps)
}
func (wps weapons) Less(i, j int) bool {
	return wps[i].crary < wps[j].crary
}
func (wps weapons) Swap(i, j int) {
	wps[i], wps[j] = wps[j], wps[i]
}
func main() {
	defer exit()
	nums = nextInt()
	fear = nextInt()
	w = make(weapons, nums+1, nums+1)
	myGoodLeft := make([]int, nums+1, nums+1)
	for i := 1; i != nums+1; i++ {
		w[i].crary = nextInt()
		w[i].force = nextInt()
	}
	sort.Sort(w[1:])
	myGoodLeft[1] = 1
	myLastForce := -1
	lll := 0
	for i := 1; i != nums+1; i++ {
		if myGoodLeft[i] == 0 {
			myGoodLeft[i] = i
		}
		l := i
		r := nums
		for {
			if l == r {
				break
			}
			mid := (l + r + 1) / 2
			midv := (w[mid].crary - w[i].crary - fear) < 0
			if midv {
				l = mid
			} else {
				r = mid - 1
			}
		}
		for j := i + 1; j != l+1; j++ {
			if myGoodLeft[j] == 0 {
				myGoodLeft[j] = i
			}
		}
		// update the lastForce
		tempForce := 0
		for k := myGoodLeft[i]; k != l+1; k++ {
			tempForce += (w[k].force)
		}
		if tempForce > myLastForce {
			myLastForce = tempForce
		}
		lll = l
	}
	if myLastForce == -1 {
		fmt.Fprintf(out, "%d %d\n", lll, myLastForce)
		return
	}
	fmt.Fprintf(out, "%d\n", myLastForce)
}

package main

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

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

func init() {
	in.Split(bufio.ScanWords)
	buf := make([]byte, 2500000, 2500000)
	in.Buffer(buf, 0)
}
func exit() {
	out.Flush()
}

// io
func nextInt() int {
	in.Scan()
	ret, _ := strconv.Atoi(in.Text())
	return ret
}

func nextString() string {
	in.Scan()
	return in.Text()
}
func nextBytes() []byte {
	in.Scan()
	return in.Bytes()
}

/*
 */
var nums int
var fear int

type weapon struct {
	crary int
	force int
}
type weapons []weapon

var w weapons

func (wps weapons) Len() int {
	return len(wps)
}
func (wps weapons) Less(i, j int) bool {
	return wps[i].crary < wps[j].crary
}
func (wps weapons) Swap(i, j int) {
	wps[i], wps[j] = wps[j], wps[i]
}
func main() {
	defer exit()
	nums = nextInt()
	fear = nextInt()
	w = make(weapons, nums+1, nums+1)
	myGoodLeft := make([]int, nums+1, nums+1)
	for i := 1; i != nums+1; i++ {
		w[i].crary = nextInt()
		w[i].force = nextInt()
	}
	sort.Sort(w[1:])
	myGoodLeft[1] = 1
	myLastForce := int64(-1)
	for i := 1; i != nums+1; i++ {
		if myGoodLeft[i] == 0 {
			myGoodLeft[i] = i
		}
		l := i
		r := nums
		for {
			if l == r {
				break
			}
			mid := (l + r + 1) / 2
			midv := (w[mid].crary - w[i].crary - fear) < 0
			if midv {
				l = mid
			} else {
				r = mid - 1
			}
		}
		for j := i + 1; j != l+1; j++ {
			if myGoodLeft[j] == 0 {
				myGoodLeft[j] = i
			}
		}
		// update the lastForce
		tempForce := int64(0)
		for k := myGoodLeft[i]; k != l+1; k++ {
			tempForce += int64(w[k].force)
		}
		if tempForce > myLastForce {
			myLastForce = tempForce
		}
	}
	fmt.Fprintf(out, "%d\n", myLastForce)
}

package main

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

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

func init() {
	in.Split(bufio.ScanWords)
	buf := make([]byte, 2500000, 2500000)
	in.Buffer(buf, 0)
}
func exit() {
	out.Flush()
}

// io
func nextInt() int {
	in.Scan()
	ret, _ := strconv.Atoi(in.Text())
	return ret
}

func nextString() string {
	in.Scan()
	return in.Text()
}
func nextBytes() []byte {
	in.Scan()
	return in.Bytes()
}

/*
 */
var nums int
var fear int

type weapon struct {
	crary int
	force int
}
type weapons []weapon

var w weapons

func (wps weapons) Len() int {
	return len(wps)
}
func (wps weapons) Less(i, j int) bool {
	return wps[i].crary < wps[j].crary
}
func (wps weapons) Swap(i, j int) {
	wps[i], wps[j] = wps[j], wps[i]
}
func main() {
	defer exit()
	nums = nextInt()
	fear = nextInt()
	w = make(weapons, nums+1, nums+1)
	myGoodLeft := make([]int, nums+1, nums+1)
	for i := 1; i != nums+1; i++ {
		w[i].crary = nextInt()
		w[i].force = nextInt()
	}
	sort.Sort(w[1:])
	myGoodLeft[1] = 1
	myLastForce := -1
	testthing := make([]int, nums+1, nums+1)
	for i := 1; i != nums+1; i++ {
		if myGoodLeft[i] == 0 {
			myGoodLeft[i] = i
		}
		l := i
		r := nums
		for {
			if l == r {
				break
			}
			mid := (l + r + 1) / 2
			midv := (w[mid].crary - w[i].crary - fear) < 0
			if midv {
				l = mid
			} else {
				r = mid - 1
			}
		}
		for j := i + 1; j != l+1; j++ {
			if myGoodLeft[j] == 0 {
				myGoodLeft[j] = i
			}
		}
		// update the lastForce
		tempForce := 0
		for k := myGoodLeft[i]; k != l+1; k++ {
			tempForce += (w[k].force)
		}
		testthing[i] = tempForce
		if tempForce > myLastForce {
			myLastForce = tempForce
		}
	}
	if myLastForce == -1 {
		fmt.Fprintf(out, "%v \n", testthing)
		return
	}
	fmt.Fprintf(out, "%d\n", myLastForce)
}

package main

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

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

func init() {
	in.Split(bufio.ScanWords)
	buf := make([]byte, 2500000, 2500000)
	in.Buffer(buf, 0)
}
func exit() {
	out.Flush()
}

// io
func nextInt() int {
	in.Scan()
	ret, _ := strconv.Atoi(in.Text())
	return ret
}

func nextString() string {
	in.Scan()
	return in.Text()
}
func nextBytes() []byte {
	in.Scan()
	return in.Bytes()
}

/*
 */
var nums int
var fear int

type weapon struct {
	crary int
	force int
}
type weapons []weapon

var w weapons

func (wps weapons) Len() int {
	return len(wps)
}
func (wps weapons) Less(i, j int) bool {
	return wps[i].crary < wps[j].crary
}
func (wps weapons) Swap(i, j int) {
	wps[i], wps[j] = wps[j], wps[i]
}
func main() {
	defer exit()
	nums = nextInt()
	fear = nextInt()
	w = make(weapons, nums+1, nums+1)
	myGoodLeft := make([]int, nums+1, nums+1)
	for i := 1; i != nums+1; i++ {
		w[i].crary = nextInt()
		w[i].force = nextInt()
	}
	sort.Sort(w[1:])
	myGoodLeft[1] = 1
	myLastForce := -1
	for i := 1; i != nums+1; i++ {
		l := i
		r := nums
		for {
			if l == r {
				break
			}
			mid := (l + r + 1) / 2
			midv := (w[mid].crary - w[i].crary - fear) < 0
			if midv {
				l = mid
			} else {
				r = mid - 1
			}
		}
		for j := i + 1; j != l+1; j++ {
			if myGoodLeft[j] == 0 {
				myGoodLeft[j] = i
			}
		}
		// update the lastForce
		tempForce := 0
		for k := myGoodLeft[i]; k != l+1; k++ {
			tempForce += (w[k].force)
		}
		if tempForce > myLastForce {
			myLastForce = tempForce
		}
	}
	fmt.Fprintf(out, "%d\n", myLastForce)
}

package main

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

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

func init() {
	in.Split(bufio.ScanWords)
	buf := make([]byte, 2500000, 2500000)
	in.Buffer(buf, 0)
}
func exit() {
	out.Flush()
}

// io
func nextInt() int {
	in.Scan()
	ret, _ := strconv.Atoi(in.Text())
	return ret
}

func nextString() string {
	in.Scan()
	return in.Text()
}
func nextBytes() []byte {
	in.Scan()
	return in.Bytes()
}

/*
 */
var nums int
var fear int

type weapon struct {
	crary int
	force int
}
type weapons []weapon

var w weapons

func (wps weapons) Len() int {
	return len(wps)
}
func (wps weapons) Less(i, j int) bool {
	return wps[i].crary < wps[j].crary
}
func (wps weapons) Swap(i, j int) {
	wps[i], wps[j] = wps[j], wps[i]
}
func main() {
	defer exit()
	nums = nextInt()
	fear = nextInt()
	w = make(weapons, nums+1, nums+1)
	myGoodLeft := make([]int, nums+1, nums+1)
	for i := 1; i != nums+1; i++ {
		w[i].crary = nextInt()
		w[i].force = nextInt()
	}
	sort.Sort(w[1:])
	myGoodLeft[1] = 1
	myLastForce := -1
	for i := 1; i != nums+1; i++ {
		l := i
		r := nums
		for {
			if l == r {
				break
			}
			mid := (l + r + 1) / 2
			midv := (w[mid].crary - w[i].crary - fear) < 0
			if midv {
				l = mid
			} else {
				r = mid - 1
			}
		}
		for j := i + 1; j != l+1; j++ {
			if myGoodLeft[j] == 0 {
				myGoodLeft[j] = i
			}
		}
		// update the lastForce
		tempForce := 0
		for k := i; k != l+1; k++ {
			tempForce += (w[k].force)
		}
		if tempForce > myLastForce {
			myLastForce = tempForce
		}
	}
	fmt.Fprintf(out, "%d\n", myLastForce)
}

package main

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

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

func init() {
	in.Split(bufio.ScanWords)
	buf := make([]byte, 2500000, 2500000)
	in.Buffer(buf, 0)
}
func exit() {
	out.Flush()
}

// io
func nextInt() int {
	in.Scan()
	ret, _ := strconv.Atoi(in.Text())
	return ret
}

func nextString() string {
	in.Scan()
	return in.Text()
}
func nextBytes() []byte {
	in.Scan()
	return in.Bytes()
}

/*
 */
var nums int
var fear int

type weapon struct {
	crary int
	force int
}
type weapons []weapon

var w weapons

func (wps weapons) Len() int {
	return len(wps)
}
func (wps weapons) Less(i, j int) bool {
	return wps[i].crary < wps[j].crary
}
func (wps weapons) Swap(i, j int) {
	wps[i], wps[j] = wps[j], wps[i]
}
func main() {
	defer exit()
	nums = nextInt()
	fear = nextInt()
	w = make(weapons, nums+1, nums+1)
	myGoodLeft := make([]int, nums+1, nums+1)
	for i := 1; i != nums+1; i++ {
		w[i].crary = nextInt()
		w[i].force = nextInt()
	}
	sort.Sort(w[1:])
	myGoodLeft[1] = 1
	myLastForce := -1
	for i := 1; i != nums+1; i++ {
		if myGoodLeft[i] == 0 {
			myGoodLeft[i] = i
		}
		l := i
		r := nums
		for {
			if l == r {
				break
			}
			mid := (l + r + 1) / 2
			midv := (w[mid].crary - w[i].crary - fear) < 0
			if midv {
				l = mid
			} else {
				r = mid - 1
			}
		}
		for j := i + 1; j != l+1; j++ {
			if myGoodLeft[j] == 0 {
				myGoodLeft[j] = i
			}
		}
		// update the lastForce
		tempForce := 0
		for k := myGoodLeft[i]; k != l+1; k++ {
			tempForce += (w[k].force)
		}
		if tempForce > myLastForce {
			myLastForce = tempForce
		}
	}
	fmt.Fprintf(out, "%d\n", myLastForce)
}

package main

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

type Friend struct {
	money, lvl int
}

type Friends []Friend

func (c Friends) Len() int           { return len(c) }
func (c Friends) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c Friends) Less(i, j int) bool { return c[i].money < c[j].money }

func main() {
	reader := bufio.NewReader(os.Stdin)
	var fr, d int
	fmt.Fscan(reader, &fr, &d)
	friends := make(Friends, fr)

	for i := 0; i < fr; i++ {
		fmt.Fscan(reader, &friends[i].money, &friends[i].lvl)
	}

	var cnt int
	sort.Sort(friends)
	for i := 0; i < fr; i++ {
		mx := 0
		for j := i; j < fr; j++ {
			if friends[i].money+d > friends[j].money {
				mx += friends[j].lvl
			}
		}
		if cnt < mx {
			cnt = mx
		}
	}

	fmt.Println(cnt)
}

package main

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

type Friend struct {
	money, lvl int
}

type Friends []Friend

func (c Friends) Len() int           { return len(c) }
func (c Friends) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c Friends) Less(i, j int) bool { return c[i].money < c[j].money }

func main() {
	reader := bufio.NewReader(os.Stdin)
	var fr, d int
	fmt.Fscan(reader, &fr, &d)
	friends := make(Friends, fr)

	for i := 0; i < fr; i++ {
		fmt.Fscan(reader, &friends[i].money, &friends[i].lvl)
	}

	var cnt int64
	j := 0
	sort.Sort(friends)
	for i := 0; i < fr; i++ {
		var mx int64 = 0
		for ; j < fr && friends[i].money+d > friends[j].money; j++ {
			mx += int64(friends[j].lvl)
		}
		if cnt < mx {
			cnt = mx
		}
		if j == fr {
			break
		}
	}

	fmt.Println(cnt)
}

package main

import (
	"fmt"
	"sort"
)

type friend struct {
	m, s int
}

type bym []friend

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

func handleInput() (int, []friend) {
	var n, d int
	fmt.Scanf("%d %d\n", &n, &d)
	friends := make([]friend, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d %d\n", &(friends[i].m), &(friends[i].s))
	}
	sort.Sort(bym(friends))
	return d, friends
}

func sumFactors(friends []friend) int {
	var sum = 0
	for _, f := range friends {
		sum += f.s
	}
	return sum
}

func main() {
	d, friends := handleInput()
	var max = 0
	for i, f := range friends {
		subfriends := friends[i:]
		j := sort.Search(len(subfriends),
			func(k int) bool {
				return subfriends[k].m > f.m+d
			})

		thisSum := sumFactors(subfriends[:j])
		if max < thisSum {
			max = thisSum
		}

		if j == len(subfriends) {
			fmt.Println(max)
			break
		}
	}
}

package main

import (
	"fmt"
	"sort"
)

type friend struct {
	m, s int
}

type bym []friend

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

func handleInput() (int, []friend) {
	var n, d int
	fmt.Scanf("%d %d\n", &n, &d)
	friends := make([]friend, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d %d\n", &(friends[i].m), &(friends[i].s))
	}
	sort.Sort(bym(friends))
	return d, friends
}

func sumFactors(friends []friend) int64 {
	var sum int64
	for _, f := range friends {
		sum += int64(f.s)
	}
	return sum
}

func solve(d int, friends []friend) int64 {
	var max int64
	for i, f := range friends {
		subfriends := friends[i:]
		j := sort.Search(len(subfriends),
			func(k int) bool {
				return subfriends[k].m > f.m+d
			})

		thisSum := sumFactors(subfriends[:j])
		if max < thisSum {
			max = thisSum
		}

		if j == len(subfriends) {
			break
		}
	}
	return max
}

func main() {
	fmt.Println(solve(handleInput()))
}

package main

import (
	"fmt"
	"sort"
)

type friend struct {
	m, s int
}

type bym []friend

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

func handleInput() (int, []friend) {
	var n, d int
	fmt.Scanf("%d %d\n", &n, &d)
	friends := make([]friend, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d %d\n", &(friends[i].m), &(friends[i].s))
	}
	return d, friends
}

func solve(d int, friends []friend) int64 {
	var max int64

	sort.Sort(bym(friends))
	sums := make([]int64, len(friends)+1)
	for i, f := range friends {
		sums[i+1] = sums[i] + int64(f.s)
	}
	for i, f := range friends {
		subfriends := friends[i:]
		j := sort.Search(len(subfriends),
			func(k int) bool {
				return subfriends[k].m >= f.m+d
			}) + i

		sum := sums[j] - sums[i]
		if max < sum {
			max = sum
		}

		if j == len(subfriends) {
			break
		}
	}
	return max
}

func main() {
	fmt.Println(solve(handleInput()))
}

package main

import (
	"fmt"
	"sort"
)

type friend struct {
	m, s int
}

type bym []friend

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

func handleInput() (int, []friend) {
	var n, d int
	fmt.Scanf("%d %d\n", &n, &d)
	friends := make([]friend, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d %d\n", &(friends[i].m), &(friends[i].s))
	}
	sort.Sort(bym(friends))
	return d, friends
}

func sumFactors(friends []friend) int {
	var sum = 0
	for _, f := range friends {
		sum += f.s
	}
	return sum
}

func solve(d int, friends []friend) int {
	var max = 0
	for i, f := range friends {
		subfriends := friends[i:]
		j := sort.Search(len(subfriends),
			func(k int) bool {
				return subfriends[k].m >= f.m+d
			})

		thisSum := sumFactors(subfriends[:j])
		if max < thisSum {
			max = thisSum
		}

		if j == len(subfriends) {
			break
		}
	}
	return max
}

func main() {
	fmt.Println(solve(handleInput()))
}

package main

import (
	"fmt"
	"math"
	"sort"
)

type fr struct {
	m int64
	s int64
}

func _580B() {

	var n int
	var d uint64

	fmt.Scan(&n, &d)
	fl := make([]fr, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&fl[i].m, &fl[i].s)
	}

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

	max_fs := int64(0)
	fs := int64(0)
	j := 0
	for i := 0; i < n; i++ {

		if i > 0 {
			fs -= fl[i-1].s
		}

		for j < n && math.Abs(float64(fl[i].m-fl[j].m)) < float64(d) {
			fs += fl[j].s
			j++
		}

		if fs > max_fs {
			max_fs = fs
		}

	}
	fmt.Println(max_fs)
}

func main() {
	_580B()
}

package main

import (
	"fmt"
	"sort"
)

type fr struct {
	m uint32
	s uint32
}

func _580B() {

	var n int
	var d uint32
	var max_fs, fs uint32

	fmt.Scan(&n, &d)
	fl := make([]fr, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&fl[i].m, &fl[i].s)
	}

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

	j := 0
	for i := 0; i < n && j < n; fs, i = fs-fl[i].s, i+1 {

		for j < n && fl[j].m-fl[i].m < d {
			fs += fl[j].s
			j++
		}
		if fs > max_fs {
			max_fs = fs
		}

	}
	fmt.Println(max_fs)
}

func main() {
	_580B()
}

package main

import (
	"fmt"
	"math"
	"sort"
)

type fr struct {
	m int
	s int
}

func _580B() {

	var n, d int

	fmt.Scan(&n, &d)
	fl := make([]fr, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&fl[i].m, &fl[i].s)
	}

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

	max_fs := 0
	fs := 0
	j := 0
	for i := 0; i < n; i++ {

		if i > 0 {
			fs -= fl[i-1].s
		}

		for j < n && math.Abs(float64(fl[i].m-fl[j].m)) < float64(d) {
			fs += fl[j].s
			j++
		}

		if fs > max_fs {
			max_fs = fs
		}

	}
	fmt.Println(max_fs)
}

func main() {
	_580B()
}

package main

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

type Pair struct{ first, second int }
type Pairs []Pair

func (p Pairs) Len() int           { return len(p) }
func (p Pairs) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p Pairs) Less(i, j int) bool { return p[i].first < p[j].first }

var (
	n, d int
	a    Pairs
)

func main() {
	// file, _ := os.Open("input.txt")
	file := os.Stdin
	f := bufio.NewReader(file)
	fmt.Fscanf(f, "%d %d\n", &n, &d)
	a = make([]Pair, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%d %d\n", &a[i].first, &a[i].second)
	}
	sort.Sort(a)
	current_total_money, current_total_factor := 0, 0
	total_factor := 0
	j := 0
	for i := 0; i < n; i++ {
		for ; j < n && a[i].first+d >= a[j].first; j++ {
			current_total_money += a[j].first
			current_total_factor += a[j].second
		}
		if total_factor < current_total_factor {
			total_factor = current_total_factor
		}
		current_total_money -= a[i].first
		current_total_factor -= a[i].second
	}
	fmt.Println(total_factor)
}

package main

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

type Pair struct{ first, second int }
type Pairs []Pair

func (p Pairs) Len() int           { return len(p) }
func (p Pairs) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p Pairs) Less(i, j int) bool { return p[i].first < p[j].first }

var (
	n, d int
	a    Pairs
)

func main() {
	// file, _ := os.Open("input.txt")
	file := os.Stdin
	f := bufio.NewReader(file)
	fmt.Fscanf(f, "%d %d\n", &n, &d)
	a = make([]Pair, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%d %d\n", &a[i].first, &a[i].second)
	}
	sort.Sort(a)
	var current_total_money, current_total_factor int64 = 0, 0
	var total_factor int64 = 0
	j := 0
	for i := 0; i < n; i++ {
		for ; j < n && a[i].first+d >= a[j].first; j++ {
			current_total_money += int64(a[j].first)
			current_total_factor += int64(a[j].second)
		}
		if total_factor < current_total_factor {
			total_factor = current_total_factor
		}
		current_total_money -= int64(a[i].first)
		current_total_factor -= int64(a[i].second)
	}
	fmt.Println(total_factor)
}

// cf580b project main.go
package main

import (
	"fmt"
)

func main() {
	var n, d int
	fmt.Scan(&n, &d)
	l := make(map[int64]int64)
	ls := make([]int64, n)
	for i := 0; i < n; i++ {
		var h, m int64
		fmt.Scan(&m, &h)
		l[m] = h
		ls[i] = m
	}
	for i := n - 1; i >= 0; i-- {
		for j := 0; j < i; j++ {
			if ls[j] > ls[j+1] {
				ls[j], ls[j+1] = ls[j+1], ls[j]
			}
		}
	}
	var k int64
	for i, a := range ls {
		var j int64
		for y := i; y < n && a+int64(d) > ls[y]; y++ {
			j += l[ls[y]]
		}
		if k < j {
			k = j
		}
	}
	fmt.Println(k)

}

// cf580b project main.go
package main

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

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

func ReadInt32() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}
func ReadInt64() int64 {
	scanner.Scan()
	ans, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return ans
}
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)
	n := ReadInt32()
	d := ReadInt32()
	l := make([][]int64, n)
	for i := 0; i < n; i++ {
		l[i] = []int64{ReadInt64(), ReadInt64()}
	}
	for i := n - 1; i >= 0; i-- {
		for j := 0; j < i; j++ {
			if l[j][0] > l[j+1][0] {
				l[j], l[j+1] = l[j+1], l[j]
			}
		}
	}
	var k, j int64
	s := 0
	for e := -1; e < n-1; {
		e++
		j += l[e][1]
		for ; l[e][0]-l[s][0] > int64(d); s++ {
			j -= l[s][1]
		}

		if j > k {
			k = j
		}
	}

	fmt.Println(k)

}

// cf580b project main.go
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, d int
	fmt.Scan(&n, &d)
	l := make(map[int]int)
	ls := make([]int, n)
	for i := 0; i < n; i++ {
		var h, m int
		fmt.Scan(&m, &h)
		l[m] = h
		ls[i] = m
	}
	sort.Ints(ls)
	k := 0
	for i, a := range ls {
		j := 0
		for y := i; y < n && a+d > ls[y]; y++ {
			j += l[ls[y]]
		}
		if k < j {
			k = j
		}
	}
	fmt.Println(k)

}

// cf580b project main.go
package main

import (
	"fmt"
)

func main() {
	var n, d int
	fmt.Scan(&n, &d)
	l := make(map[int64]int64)
	ls := make([]int64, n)
	for i := 0; i < n; i++ {
		var h, m int64
		fmt.Scan(&m, &h)
		l[m] = h
		ls[i] = m
	}
	for i := n - 2; i >= 0; i-- {
		for j := 0; j < i; j++ {
			if ls[j] > ls[j+1] {
				ls[j], ls[j+1] = ls[j+1], ls[j]
			}
		}
	}
	var k int64
	for i, a := range ls {
		var j int64
		for y := i; y < n && a+int64(d) > ls[y]; y++ {
			j += l[ls[y]]
		}
		if k < j {
			k = j
		}
	}
	fmt.Println(k)

}


Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $$$0$$$. Also, let's say that the train will visit $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$ along its way, and that Alexey destination is the station $$$n$$$.Alexey learned from the train schedule $$$n$$$ integer pairs $$$(a_i, b_i)$$$ where $$$a_i$$$ is the expected time of train's arrival at the $$$i$$$-th station and $$$b_i$$$ is the expected time of departure.Also, using all information he has, Alexey was able to calculate $$$n$$$ integers $$$tm_1, tm_2, \dots, tm_n$$$ where $$$tm_i$$$ is the extra time the train need to travel from the station $$$i - 1$$$ to the station $$$i$$$. Formally, the train needs exactly $$$a_i - b_{i-1} + tm_i$$$ time to travel from station $$$i - 1$$$ to station $$$i$$$ (if $$$i = 1$$$ then $$$b_0$$$ is the moment the train leave the terminal, and it's equal to $$$0$$$).The train leaves the station $$$i$$$, if both conditions are met:   it's on the station for at least $$$\left\lceil \frac{b_i - a_i}{2} \right\rceil$$$ units of time (division with ceiling);  current time $$$\ge b_i$$$. Since Alexey spent all his energy on prediction of time delays, help him to calculate the time of arrival at the station $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of stations. Next $$$n$$$ lines contain two integers each: $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i < b_i \le 10^6$$$). It's guaranteed that $$$b_i < a_{i+1}$$$.  Next line contains $$$n$$$ integers $$$tm_1, tm_2, \dots, tm_n$$$ ($$$0 \le tm_i \le 10^6$$$).

For each test case, print one integer — the time of Alexey's arrival at the last station.

NoteIn the first test case, Alexey arrives at station $$$1$$$ without any delay at the moment $$$a_1 = 2$$$ (since $$$tm_1 = 0$$$). After that, he departs at moment $$$b_1 = 4$$$. Finally, he arrives at station $$$2$$$ with $$$tm_2 = 2$$$ extra time, or at the moment $$$12$$$.In the second test case, Alexey arrives at the first station with $$$tm_1 = 1$$$ extra time, or at moment $$$2$$$. The train, from one side, should stay at the station at least $$$\left\lceil \frac{b_1 - a_1}{2} \right\rceil = 2$$$ units of time and from the other side should depart not earlier than at moment $$$b_1 = 4$$$. As a result, the trains departs right at the moment $$$4$$$.Using the same logic, we can figure out that the train arrives at the second station at the moment $$$9$$$ and departs at the moment $$$10$$$; at the third station: arrives at $$$14$$$ and departs at $$$15$$$; at the fourth: arrives at $$$22$$$ and departs at $$$23$$$. And, finally, arrives at the fifth station at $$$32$$$.

package main

import (
	"fmt"
	"math"
)

var (
	n,t,s int
	a,b,c [1e6+5]int
)

func main() {
	fmt.Scan(&t)
	for ;;t--{
		if t<=0{
			break
		}
		fmt.Scan(&n)
		s=0
		for i:=1;i<=n;i++{
			fmt.Scan(&a[i],&b[i])
		}
		for i:=1;i<=n;i++{
			fmt.Scan(&c[i])
		}
		for i:=1;i<=n;i++{
			s+=a[i]-b[i-1]+c[i]
			if i!=n{
				s+=(b[i]-a[i]+1)/2
				s=int(math.Max(float64(s), float64(b[i])))
			}
		}
		fmt.Println(s)
	}
}

package main
import (
    "os"
    "fmt"
    "bufio"
)
var rd = bufio.NewReader(os.Stdin)
func max(a, b int) int {
    if a > b {
        return a
    } else {
        return b
    }
}
func main() {
    q := 0
    fmt.Fscan(rd, &q)
    for t := 0; t < q; t++ {
        n := 0
        fmt.Fscan(rd, &n)
        a, b, tm := make([]int, n), make([]int, n), make([]int, n)
        for i := range a {
            fmt.Fscan(rd, &a[i], &b[i])
        }
        for i := range tm {
            fmt.Fscan(rd, &tm[i])
        }
        res := 0
        for i := range a {
            d := 0
            if i > 0 {
                d = b[i - 1]
            }
            res += a[i] - d + tm[i]
            if i < n - 1 {
                res = max(res + (b[i] - a[i] + 1) / 2, b[i])
            }
        }
        fmt.Println(res)
    }
}

package main

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

type Station struct {
	next *Station
	prev *Station
	expectedArrivalTime int
	arrivalTime int
	departureTime int
	expectedDepartureTime int
	delay int
}

func numbers(s string) []int {
	var n []int
	for _, f := range strings.Fields(s) {
		i, err := strconv.Atoi(f)
		if err == nil {
			n = append(n, i)
		}
	}
	return n
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	if text[len(text)-1] == '\n' || text[len(text)-1] == '\r' {
		text = text[:len(text)-1]
	}
	if text[len(text)-1] == '\n' || text[len(text)-1] == '\r' {
		text = text[:len(text)-1]
	}
	numTestCases, _ := strconv.Atoi(text)
	for i := 0; i < numTestCases; i++ {
		head := new(Station)
		head.next = nil
		head.prev = nil
		head.expectedDepartureTime = 0
		head.expectedArrivalTime = 0
		head.arrivalTime = 0
		head.departureTime = 0
		head.delay = 0
		tail := head
		text, _ := reader.ReadString('\n')
		if text[len(text)-1] == '\n' || text[len(text)-1] == '\r' {
			text = text[:len(text)-1]
		}
		if text[len(text)-1] == '\n' || text[len(text)-1] == '\r' {
			text = text[:len(text)-1]
		}
		numStations, _ := strconv.Atoi(text)
		for j := 0; j < numStations; j++ {
			text, _ := reader.ReadString('\n')
			if text[len(text)-1] == '\n' || text[len(text)-1] == '\r' {
				text = text[:len(text)-1]
			}
			if text[len(text)-1] == '\n' || text[len(text)-1] == '\r' {
				text = text[:len(text)-1]
			}
			var x, y int
			fmt.Sscanf(text, "%d %d", &x, &y)
			s := new(Station)
			s.prev = tail
			s.prev.next = s
			s.next = nil
			s.expectedArrivalTime = x
			s.expectedDepartureTime = y
			tail = s
		}
		var delays = make([]int, numStations, numStations)
		text, _ = reader.ReadString('\n')
		if text[len(text)-1] == '\n' || text[len(text)-1] == '\r' {
			text = text[:len(text)-1]
		}
		if text[len(text)-1] == '\n' || text[len(text)-1] == '\r' {
			text = text[:len(text)-1]
		}
		delays = numbers(text)
		current := head.next
		for _, delay := range delays {
			current.delay = delay
			current = current.next
		}
		current = head.next
		for ; current != nil; current = current.next {
			current.arrivalTime = current.expectedArrivalTime - current.prev.expectedDepartureTime + current.delay + current.prev.departureTime
			waitTime := int(math.Ceil(float64(current.expectedDepartureTime - current.expectedArrivalTime) / 2))
			if waitTime + current.arrivalTime > current.expectedDepartureTime {
				current.departureTime = waitTime + current.arrivalTime
			} else {
				current.departureTime = current.expectedDepartureTime
			}
		}
		fmt.Println(tail.arrivalTime)
	}

}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

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

func MKO(x, y int) int {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

func FLOOR(x, y int) int {

	if (x-y)%2 == 0 {
		return int((x - y) / 2)
	} else {
		return int((x - y + 1) / 2)

	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {

		var n int
		fmt.Fscan(input, &n)
		AIII := make([]int, n+1)
		MIII := make([]int, n+1)
		ArrayOfTimes := make([]int, n+1)

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

			fmt.Fscan(input, &AIII[i])
			fmt.Fscan(input, &MIII[i])

		}

		for i := 1; i < n+1; i++ {
			fmt.Fscan(input, &ArrayOfTimes[i])

		}

		Answer := AIII[1] + ArrayOfTimes[1]

		for i := 2; i < n+1; i++ {
			if Answer+FLOOR(MIII[i-1], AIII[i-1]) >= MIII[i-1] {
				Answer = Answer + FLOOR(MIII[i-1], AIII[i-1]) + AIII[i] - MIII[i-1] + ArrayOfTimes[i]
			} else {
				Answer = AIII[i] + ArrayOfTimes[i]
			}
		}
		fmt.Println(Answer)

	}
}

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n := 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		a, b, tm := make([]int, n), make([]int, n), make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(f, &a[j], &b[j])
		}
		for j := 0; j < n; j++ {
			fmt.Fscan(f, &tm[j])
		}
		tt, ar, d := 0, 0, 0
		for j := 0; j < n; j++ {
			if j == 0 {
				tt += a[j] + tm[j]
			} else {
				tt = a[j] - b[j-1] + tm[j]
			}
			ar = d + tt
			if ar+((b[j]-a[j]+1)>>1) >= b[j] {
				d = ar + ((b[j] - a[j] + 1) >> 1)
			} else {
				d = b[j]
			}
		}
		fmt.Fprintln(w, ar)
	}
	w.Flush()
}

func main() {
	solve()
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t, n   int
)

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

func ceilingDivide(x, y int) int {
	return (x + y - 1) / y
}

func solve(n int, a, b, tm []int) int {
	var c, d int
	for i := 0; i < n; i++ {
		if i == 0 {
			c = a[i] + tm[i]
		} else {
			d = max(c+ceilingDivide(b[i-1]-a[i-1], 2), b[i-1])
			c = a[i] - b[i-1] + tm[i] + d
		}
	}
	return c
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		a := make([]int, n)
		b := make([]int, n)
		tm := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i], &b[i])
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &tm[i])
		}
		fmt.Println(solve(n, a, b, tm))
	}
}

package main

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

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

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

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

func sint() int { // ~[-2e9, 2e9]
	s := sstring()
	i := 0
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int(r - '0')
	}
	return i
}

func sints(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = sint()
	}
	return a
}

func sint64() int64 { // ~[-9e18, 9e18]
	s := sstring()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

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

type Station struct {
	arr  int
	dep  int
	wait int
}

func (s Station) WaitUntil(from int) int {
	minWait := (s.dep - s.arr + 1) / 2 // ceildiv by 2
	return max(s.dep, from+minWait)
}

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

func main() {
	defer writer.Flush()
	for t := sint(); t > 0; t-- {
		n := sint()
		stations := make([]Station, n)
		for i := range stations {
			start := sint()
			depart := sint()
			stations[i] = Station{
				arr: start,
				dep: depart,
			}
		}
		for i := range stations {
			stations[i].wait = sint()
		}
		printf("%d\n", sol(stations))
	}
}

func sol(stations []Station) int {
	moment := stations[0].arr + stations[0].wait
	for i := range stations[:len(stations)-1] {
		depart := stations[i].WaitUntil(moment)
		duration := stations[i+1].arr - stations[i].dep + stations[i+1].wait
		moment = depart + duration
	}
  return moment
}

package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

var bytes []byte

func nextByte() byte {
	b := bytes[0]
	bytes = bytes[1:]
	return b
}

func ScanInt64() int64 {
	var negative bool
	var result int64

	b := nextByte()

	for ; b < '0' || b > '9'; b = nextByte() {
		if b == '-' {
			negative = true
		}
	}

	for ; '0' <= b && b <= '9'; b = nextByte() {
		result = (result << 3) + (result << 1) + int64(b-'0')
	}

	if negative {
		return -result
	} else {
		return result
	}
}

func ScanInt() int {
	return int(ScanInt64())
}

func ScanString() string {
	builder := strings.Builder{}

	for b := nextByte(); b != '\r'; b = nextByte() {
		if b != '\n' {
			builder.WriteByte(b)
		}
	}

	return builder.String()
}

func init() {
	f, err := os.Open("in.txt")

	if err == nil {
		defer f.Close()
	} else {
		f = os.Stdin
	}

	bytes, _ = ioutil.ReadAll(bufio.NewReader(f))
}

func main() {
	for t := ScanInt(); t > 0; t-- {
		n := ScanInt()
		travelTime, waitTime, departTime := make([]int, n), make([]int, n+1), make([]int, n+1)
		b := 0

		for i := 0; i < n; i++ {
			a := ScanInt()
			travelTime[i] = a - b
			b = ScanInt()
			waitTime[i+1] = (b-a)/2 + (b-a)%2
			departTime[i+1] = b
		}

		for i := 0; i < n; i++ {
			tm := ScanInt()
			travelTime[i] += tm
		}

		time := 0

		for i := 0; i < n; i++ {
			time += waitTime[i]

			if time < departTime[i] {
				time = departTime[i]
			}

			time += travelTime[i]
		}

		fmt.Println(time)
	}
}

package main

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

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

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

func main() {
	defer writer.Flush()
	//redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solveA()
	}
}

// --------------------------------------------------------------------- //

func solveA() {
	var n int
	scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	for i := range b {
		scan(&a[i])
		scan(&b[i])
	}
	tm := make([]int, n)
	for i := range tm {
		scan(&tm[i])
	}

	ans := 0
	prev := 0

	for i := range a {
		ans += a[i] - prev + tm[i]
		if i == n-1 {
			break
		}

		need := (b[i] - a[i] + 1) / 2
		stay := 0
		if ans < b[i] {
			stay = b[i] - ans
			ans = b[i]
		}
		if stay < need {
			ans += need - stay
		}

		prev = b[i]
	}

	printf("%d\n", ans)
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var T, n, time int
	var times []int
	var tm []int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		for i := 0; i < n; i++ {
			Fscan(in, &time)
			times = append(times, time)
			Fscan(in, &time)
			times = append(times, time)
		}
		for i := 0; i < n; i++ {
			Fscan(in, &time)
			tm = append(tm, time)
		}
		delay := 0
		add := 0
		for i := 0; i < n; i++ {
			wait := 0
			if (times[i+add+1]-times[i+add])%2 == 0 {
				wait = (times[i+add+1] - times[i+add]) / 2
			} else {
				wait = (times[i+add+1]-times[i+add])/2 + 1
			}
			dep := delay + tm[i] + times[i+add] + wait
			if dep > times[i+add+1] && i != len(tm)-1 {
				delay = dep - times[i+add+1]
			}
			add++
		}
		Fprintln(out, times[len(times)-2]+delay+tm[len(tm)-1])
		times = []int{}
		tm = []int{}
	}
}

package main

import (
	"fmt"
	"math"
)

var (
	n,t,s int
	a,b,c [1e6+5]int
)

func main() {
	fmt.Scan(&t)
	for ;;t--{
		if t<=0{
			break
		}
		fmt.Scan(&n)
		s=0
		for i:=1;i<=n;i++{
			fmt.Scan(&a[i],&b[i])
		}
		for i:=1;i<=n;i++{
			fmt.Scan(&c[i])
		}
		for i:=1;i<=n;i++{
			s+=a[i]-b[i-1]+c[i]
			if i!=n{
				s+=(b[i]-a[i]+1)/2
			}
			s=int(math.Max(float64(s), float64(b[i])))
		}
		fmt.Println(s)
	}
}

package main

import (
	"fmt"
	"math"
)

var (
	n,t,s int
)

func main() {
	a,b,c:=make([]int,1e6+5),make([]int,1e6+5),make([]int,1e6+5)
	fmt.Scan(&t)
	for ;;t--{
		if t<=0{
			break
		}
		fmt.Scan(&n)
		s=0
		for i:=1;i<=n;i++{
			fmt.Scanf("%d %d\n",&a[i],&b[i])
		}
		for i:=1;i<=n;i++{
			fmt.Scan(&c[i])
		}
		for i:=1;i<=n;i++{
			s+=a[i]-b[i-1]+c[i]
			if i!=n{
				s+=(b[i]-a[i]+1)/2
			}
			s=int(math.Max(float64(s), float64(b[i])))
		}
		fmt.Println(s)
	}
}

package main

import (
	"fmt"
	"math"
)

var (
	n,t,s int
)

func main() {
	a,b,c:=make([]int,1e6+5),make([]int,1e6+5),make([]int,1e6+5)
	fmt.Scan(&t)
	for ;;t--{
		if t<=0{
			break
		}
		fmt.Scan(&n)
		s=0
		for i:=1;i<=n;i++{
			fmt.Scanf("%d %d",&a[i],&b[i])
		}
		for i:=1;i<=n;i++{
			fmt.Scan(&c[i])
		}
		for i:=1;i<=n;i++{
			s+=a[i]-b[i-1]+c[i]
			if i!=n{
				s+=(b[i]-a[i]+1)/2
			}
			s=int(math.Max(float64(s), float64(b[i])))
		}
		fmt.Println(s)
	}
}

package main

import (
	"fmt"
	"math"
)

var (
	n,t,s int
	a,b,c [1e6+5]int
)

func main() {
	fmt.Scan(&t)
	for ;;t--{
		if t<=0{
			break
		}
		fmt.Scan(&n)
		s=0
		for i:=1;i<=n;i++{
			fmt.Scanf("%d %d",&a[i],&b[i])
		}
		for i:=1;i<=n;i++{
			fmt.Scan(&c[i])
		}
		for i:=1;i<=n;i++{
			s+=a[i]-b[i-1]+c[i]
			if i!=n{
				s+=(b[i]-a[i]+1)/2
			}
			s=int(math.Max(float64(s), float64(b[i])))
		}
		fmt.Println(s)
	}
}

package main
import (
    "os"
    "fmt"
    "bufio"
)
var rd = bufio.NewReader(os.Stdin)
func max(a, b int) int {
    if a < b {
        return a
    } else {
        return b
    }
}
func main() {
    q := 0
    fmt.Fscan(rd, &q)
    for t := 0; t < q; t++ {
        n := 0
        fmt.Fscan(rd, &n)
        a, b, tm := make([]int, n), make([]int, n), make([]int, n)
        for i := range a {
            fmt.Fscan(rd, &a[i], &b[i])
        }
        for i := range tm {
            fmt.Fscan(rd, &tm[i])
        }
        res := 0
        for i := range a {
            d := 0
            if i > 0 {
                d = b[i - 1]
            }
            res += a[i] - d + tm[i]
            if i < n - 1 {
                res = max(res + (b[i] - a[i] + 1) / 2, b[i])
            }
        }
        fmt.Println(res)
    }
}

package main

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

type Station struct {
	next *Station
	prev *Station
	expectedArrivalTime int
	arrivalTime int
	departureTime int
	expectedDepartureTime int
	delay int
}

func numbers(s string) []int {
	var n []int
	for _, f := range strings.Fields(s) {
		i, err := strconv.Atoi(f)
		if err == nil {
			n = append(n, i)
		}
	}
	return n
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = text[:len(text) - 1]
	numTestCases, _ := strconv.Atoi(text)
	for i := 0; i < numTestCases; i++ {
		head := new(Station)
		head.next = nil
		head.prev = nil
		head.expectedDepartureTime = 0
		head.expectedArrivalTime = 0
		head.arrivalTime = 0
		head.departureTime = 0
		head.delay = 0
		tail := head
		text, _ := reader.ReadString('\n')
		text = text[:len(text) - 1]
		numStations, _ := strconv.Atoi(text)
		for j := 0; j < numStations; j++ {
			text, _ := reader.ReadString('\n')
			var x, y int
			fmt.Sscanf(text, "%d %d\n", &x, &y)
			s := new(Station)
			s.prev = tail
			s.prev.next = s
			s.next = nil
			s.expectedArrivalTime = x
			s.expectedDepartureTime = y
			tail = s
		}
		var delays []int
		text, _ = reader.ReadString('\n')
		delays = numbers(text)
		current := head.next
		for _, delay := range delays {
			current.delay = delay
			current = current.next
		}
		current = head.next
		for ; current != nil; current = current.next {
			current.arrivalTime = current.expectedArrivalTime - current.prev.expectedDepartureTime + current.delay + current.prev.departureTime
			waitTime := int(math.Ceil(float64(current.expectedDepartureTime - current.expectedArrivalTime) / 2))
			if waitTime + current.arrivalTime > current.expectedDepartureTime {
				current.departureTime = waitTime + current.arrivalTime
			} else {
				current.departureTime = current.expectedDepartureTime
			}
		}
		fmt.Println(tail.arrivalTime)
	}

}

package main

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

type Station struct {
	next *Station
	prev *Station
	expectedArrivalTime int
	arrivalTime int
	departureTime int
	expectedDepartureTime int
	delay int
}

func numbers(s string) []int {
	var n []int
	for _, f := range strings.Fields(s) {
		i, err := strconv.Atoi(f)
		if err == nil {
			n = append(n, i)
		}
	}
	return n
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = text[:len(text) - 1]
	numTestCases, _ := strconv.Atoi(text)
	for i := 0; i < numTestCases; i++ {
		head := new(Station)
		head.next = nil
		head.prev = nil
		head.expectedDepartureTime = 0
		head.expectedArrivalTime = 0
		head.arrivalTime = 0
		head.departureTime = 0
		head.delay = 0
		tail := head
		text, _ := reader.ReadString('\n')
		text = text[:len(text) - 1]
		numStations, _ := strconv.Atoi(text)
		for j := 0; j < numStations; j++ {
			text, _ := reader.ReadString('\n')
			var x, y int
			fmt.Sscanf(text, "%d %d\n", &x, &y)
			s := new(Station)
			s.prev = tail
			s.prev.next = s
			s.next = nil
			s.expectedArrivalTime = x
			s.expectedDepartureTime = y
			tail = s
		}
		var delays []int
		scanner := bufio.NewScanner(os.Stdin)
		scanner.Scan()
		delays = numbers(scanner.Text())
		current := head.next
		for _, delay := range delays {
			current.delay = delay
			current = current.next
		}
		current = head.next
		for ; current != nil; current = current.next {
			current.arrivalTime = current.expectedArrivalTime - current.prev.expectedDepartureTime + current.delay + current.prev.departureTime
			waitTime := int(math.Ceil(float64(current.expectedDepartureTime - current.expectedArrivalTime) / 2))
			if waitTime + current.arrivalTime > current.expectedDepartureTime {
				current.departureTime = waitTime + current.arrivalTime
			} else {
				current.departureTime = current.expectedDepartureTime
			}
		}
		fmt.Println(tail.arrivalTime)
	}

}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

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

func MKO(x, y int) int {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

func FLOOR(x, y int) int {

	if (x-y)%2 == 0 {
		return int((x - y) / 2)
	} else {
		return int((x - y + 1) / 2)

	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {

		var n int
		fmt.Fscan(input, &n)
		AIII := make([]int, n+1)
		MIII := make([]int, n+1)
		ArrayOfTimes := make([]int, n+1)

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

			fmt.Fscan(input, &AIII[i])
			fmt.Fscan(input, &MIII[i])

		}

		for i := 1; i < n+1; i++ {
			fmt.Fscan(input, &ArrayOfTimes[i])

		}

		Answer := AIII[1] + ArrayOfTimes[1]
		for i := 2; i < n+1; i++ {
			if Answer+AIII[i]-MIII[i-1]+ArrayOfTimes[i]+FLOOR(MIII[i-1], AIII[i-1]) <= MIII[i] {
				Answer = MIII[i]
			} else {
				Answer = Answer + AIII[i] - MIII[i-1] + ArrayOfTimes[i] + FLOOR(MIII[i-1], AIII[i-1])
			}
		}
		fmt.Println(Answer)

	}
}