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"
	"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 := 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)
}


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


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

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)

}


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 (
	"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"
	"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)

	}
}