Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.

The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish.

Print a single integer — the minimum number of times Valera will need to wash a plate/bowl.

NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.

package main

import "fmt"

func main() {
	var n, a, b int
	fmt.Scan(&n, &a, &b)
	ans := 0
	for i := 0; i < n; i++{
		var t int
		fmt.Scan(&t)
		if t == 1 {
			if a > 0 {
				a--
			} else {
				ans++
			}
		} else {
			if b > 0 {
				b--
			} else {
				if a > 0 {
					a--
				} else {
					ans++
				}
			}
		}
	}
	fmt.Print(ans)
}

package main
import (
	"fmt"
)
func main() {
	var n,m,k int
	t,nf,ns,nn := 0,0,0,0
	fmt.Scan(&n,&m,&k)
	for i:=0; i<n;i++ {
		fmt.Scan(&t)
		if t==1 {
			nf++
		} else { ns++}
	}
	if nf>m {
		nn = nf-m
		m=0
	}else {
		m-=nf
	}
	if ns>k+m {
		nn+= ns-k-m
	}
	fmt.Println(nn)

}

package main

import "fmt"

func main() {
    var n,m,k,a int
    fmt.Scan(&n,&m,&k)
    ans := 0
    for i := 0; i < n; i++ {
        fmt.Scan(&a)
        if (a == 2) && (k > 0) {
            k--
        } else if (m > 0) {
            m--
        } else {
            ans++
        }
    }
    fmt.Println(ans)
}

package main

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

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

	wash := 0
	bowls := m
	plates := k

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; scanner.Scan() && i < n; i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}

		if a == 1 {
			if bowls > 0 {
				bowls--
			} else {
				wash++
			}
		} else if a == 2 {
			if plates > 0 {
				plates--
			} else if bowls > 0 {
				bowls--
			} else {
				wash++
			}
		} else {
			return
		}
	}

	fmt.Println(wash)
}

package main

import (
    "fmt"
)

func main() {
    var n, m, k, ans int
    fmt.Scan(&n, &m, &k)

    for i := 0; i < n;i++ {
        var t int
        fmt.Scan(&t)
        if t == 1 {
            if m > 0 {
                m--
            } else {
                ans++
            }
        } else {
            if k > 0 {
                k--
            } else if m > 0 {
                m--
            } else {
                ans++
            }
        }
    }

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

package main

import (
	"fmt"
)

func main() {
	var n, m, k, a int
	fmt.Scan(&n, &m, &k)

	first := 0
	second := 0
	for i := 0; i < n; i++ {
		fmt.Scan(&a)
		if a == 1 {
			first++
		} else {
			second++
		}
	}
	ans := 0
	if m < first {
		ans += first - m
	} else {
		k += m - first
	}

	if k < second {
		ans += second - k
	}

	fmt.Println(ans)
}

package main

import (
	"fmt"
)

func main(){
	var n,a,b,k,ans int
	fmt.Scan(&n,&a,&b)
	//fmt.Scanf("%d%d%d",&n,&a,&b)
	ans = 0
	for i:=0;i<n;i++{
		fmt.Scan(&k)
		if k==1{
			if a >0 {
				a --
			}else{
				ans ++
			}
		}else {
			if b > 0 {
				b --
			}else if a > 0{
				a --
			}else{
				ans ++
			}
		}
	}
	fmt.Printf("%d\n",ans)
}

/*2017-11-05 13:41:18.541*/

package main

import "fmt"

func main() {
	var n, a, b int
    fmt.Scan(&n, &a, &b)
	ans := 0
	for i := 0; i < n; i++{
		var t int
		fmt.Scan(&t)
		if t == 1 {
			if a > 0 {
				a--
			} else {
				ans++
			}
		} else {
			if b > 0 {
				b--
			} else {
				if a > 0 {
					a--
				} else {
					ans++
				}
			}
		}
	}
	print(ans)
}

package main

import (
	"fmt"
)

func main() {
	var n, m, k, a int
	fmt.Scan(&n, &m, &k)

	ans := 0
	for i := 0; i < n; i++ {
		fmt.Scan(&a)
		if a == 1 {
			if m == 0 {
				ans++
			} else {
				m--
			}
		} else {
			if m == 0 && k == 0 {
				ans++
			} else {
				if m > k {
					m--
				} else {
					k--
				}
			}
		}
	}

	fmt.Println(ans)
}

package main

import (
	"fmt"
)

func get_lucky_digits_num(num string) int {
	ret := 0
	for i := 0; i < len(num); i++ {
		if num[i] == '4' || num[i] == '7' {
			ret++
		}
	}

	return ret
}

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

	var num string
	ans := 0
	for i := 0; i < n; i++ {
		fmt.Scan(&num)
		if get_lucky_digits_num(num) <= k {
			ans++
		}
	}

	fmt.Println(ans)
}

package main

import (
	"fmt"
)

func main(){
	var n,a,b,k,ans int
	fmt.Scanf("%d%d%d",&n,&a,&b)
	ans = 0
	for i:=0;i<n;i++{
		fmt.Scanf("%d",&k)
		if k==1{
			if a==0 {
				ans ++
			}else{
				a --
			}
		}else {
			if a+b == 0 {
				ans ++
			} else if b != 0 {
				b--
			} else {
				a--
			}
		}
	}
	fmt.Print(ans)
}

/*2017-11-05 13:18:13.771*/


Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i < 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).

Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.

NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

/*********** DP sub-functions ***********/

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

// 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 *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

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

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var A []int64
var B []int

type group struct {
	bits    int64
	members []int
}

type Item struct {
	key int64
	a   int64
	b   int
	idx int
}
type ItemList []*Item
type byKey struct {
	ItemList
}

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

func (l byKey) Less(i, j int) bool {
	return l.ItemList[i].key < l.ItemList[j].key
}

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

var flags []bool

func main() {
	n = ReadInt()
	A = ReadInt64Slice(n)
	B = ReadIntSlice(n)
	flags = make([]bool, n)

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

	L := make(ItemList, 0, 200000)
	for i := 0; i < n; i++ {
		L = append(L, &Item{key: A[i], a: A[i], b: B[i], idx: i})
	}
	sort.Stable(byKey{L})

	// 2以上のサイズのメモ
	memo := make(map[int64]int)
	for i := 0; i < len(L); i++ {
		if i == 0 {
			if L[i].a == L[i+1].a {
				memo[L[i].a] = 1
			}
		} else if i == len(L)-1 {
			if L[i-1].a == L[i].a {
				memo[L[i].a] = 1
			}
		} else {
			if L[i-1].a == L[i].a || L[i].a == L[i+1].a {
				memo[L[i].a] = 1
			}
		}
	}

	for bits := range memo {
		for i := 0; i < n; i++ {
			if bits|A[i] == bits {
				flags[i] = true
			}
		}
	}

	sum := int64(0)
	for i := 0; i < n; i++ {
		if flags[i] {
			sum += int64(B[i])
		}
	}

	fmt.Println(sum)
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

/*********** DP sub-functions ***********/

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

// 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 *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

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

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var A []int64
var B []int

type group struct {
	bits    int64
	members []int
}

type Student struct {
	key int64
	a   int64
	b   int
	idx int
}
type StudentList []*Student
type byKey struct {
	StudentList
}

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

func (l byKey) Less(i, j int) bool {
	return l.StudentList[i].key < l.StudentList[j].key
}

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

var flags []bool

func main() {
	n = ReadInt()
	A = ReadInt64Slice(n)
	B = ReadIntSlice(n)
	flags = make([]bool, n)

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

	L := make(StudentList, 0, 200000)
	for i := 0; i < n; i++ {
		L = append(L, &Student{key: A[i], a: A[i], b: B[i], idx: i})
	}
	sort.Stable(byKey{L})

	// 2以上のサイズのメモ
	memo := make(map[int64]int)
	for i := 0; i < len(L); i++ {
		if i == 0 {
			if L[i].a == L[i+1].a {
				memo[L[i].a] = 1
			}
		} else if i == len(L)-1 {
			if L[i-1].a == L[i].a {
				memo[L[i].a] = 1
			}
		} else {
			if L[i-1].a == L[i].a || L[i].a == L[i+1].a {
				memo[L[i].a] = 1
			}
		}
	}

	for bits := range memo {
		for i := 0; i < n; i++ {
			if bits|A[i] == bits {
				flags[i] = true
			}
		}
	}

	sum := int64(0)
	for i := 0; i < n; i++ {
		if flags[i] {
			sum += int64(B[i])
		}
	}

	fmt.Println(sum)
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol1230D(reader io.Reader, writer io.Writer) {
	type pair struct {
		a, b int64
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	if n == 1 {
		Fprintln(out, 0)
		return
	}
	arr := make([]pair, n)
	for i := range arr {
		Fscan(in, &arr[i].a)
	}
	for i := range arr {
		Fscan(in, &arr[i].b)
	}

	sort.Slice(arr, func(i, j int) bool { return arr[i].a < arr[j].a })
	multi := map[int64]int{}
	for i := 0; i < n-1; i++ {
		if arr[i].a == arr[i+1].a {
			multi[arr[i].a] = 1
		}
	}
	multiList := []int64{}
	for k := range multi {
		multiList = append(multiList, k)
	}
	ans := int64(0)
	for _, p := range arr {
		a, b := p.a, p.b
		if _, ok := multi[a]; ok {
			ans += b
		} else {
			for _, k := range multiList {
				if a&^k == 0 {
					ans += b
					break
				}
			}
		}
	}
	Fprintln(out, ans)
}

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

package main

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

func Sol1230D(reader io.Reader, writer io.Writer) {
	type pair struct {
		a, b int64
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	if n == 1 {
		Fprint(out, 0)
		return
	}
	arr := make([]pair, n)
	for i := range arr {
		Fscan(in, &arr[i].a)
	}
	for i := range arr {
		Fscan(in, &arr[i].b)
	}

	sort.Slice(arr, func(i, j int) bool { return arr[i].a < arr[j].a })
	multi := map[int64]bool{}
	for i := 0; i < n-1; i++ {
		if arr[i].a == arr[i+1].a {
			multi[arr[i].a] = true
		}
	}
	multiList := []int64{}
	for k := range multi {
		multiList = append(multiList, k)
	}
	ans := int64(0)
	for _, p := range arr {
		a, b := p.a, p.b
		if multi[a] {
			ans += b
		} else {
			for _, k := range multiList {
				if a&^k == 0 {
					ans += b
					break
				}
			}
		}
	}
	Fprint(out, ans)
}

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

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

/*********** DP sub-functions ***********/

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

// 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 *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

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

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var A []int64
var B []int

type group struct {
	bits    int64
	members []int
}

type Item struct {
	key int64
	a   int64
	b   int
	idx int
}
type ItemList []*Item
type byKey struct {
	ItemList
}

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

func (l byKey) Less(i, j int) bool {
	return l.ItemList[i].key < l.ItemList[j].key
}

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

var flags []bool

func main() {
	n = ReadInt()
	A = ReadInt64Slice(n)
	B = ReadIntSlice(n)
	flags = make([]bool, n)

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

	L := make(ItemList, 0, 200000)
	for i := 0; i < n; i++ {
		L = append(L, &Item{key: A[i], a: A[i], b: B[i], idx: i})
	}
	sort.Stable(byKey{L})

	// 2以上のサイズのメモ
	memo := make(map[int64]int)
	for i := 0; i < len(L); i++ {
		if i == 0 {
			if L[i].a == L[i+1].a {
				memo[L[i].a] = 1
			}
		} else if i == len(L)-1 {
			if L[i-1].a == L[i].a {
				memo[L[i].a] = 1
			}
		} else {
			if L[i-1].a == L[i].a || L[i].a == L[i+1].a {
				memo[L[i].a] = 1
			}
		}
	}

	for bits := range memo {
		for i := 0; i < n; i++ {
			if bits|A[i] == bits {
				flags[i] = true
			}
		}
	}

	sum := 0
	for i := 0; i < n; i++ {
		if flags[i] {
			sum += B[i]
		}
	}

	fmt.Println(sum)
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

/*********** DP sub-functions ***********/

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

// 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 *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

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

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var A []int64
var B []int

type group struct {
	bits    int64
	members []int
}

type Item struct {
	key int64
	a   int64
	b   int
	idx int
}
type ItemList []*Item
type byKey struct {
	ItemList
}

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

func (l byKey) Less(i, j int) bool {
	return l.ItemList[i].key < l.ItemList[j].key
}

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

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

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

	L := make(ItemList, 0, 200000)
	for i := 0; i < n; i++ {
		L = append(L, &Item{key: A[i], a: A[i], b: B[i], idx: i})
	}
	sort.Stable(byKey{L})

	// 2以上のサイズのメモ
	memo := make(map[int64]int)
	for i := 0; i < len(L); i++ {
		if i == 0 {
			if L[i].a == L[i+1].a {
				memo[L[i].a] = 1
			}
		} else if i == len(L)-1 {
			if L[i-1].a == L[i].a {
				memo[L[i].a] = 1
			}
		} else {
			if L[i-1].a == L[i].a || L[i].a == L[i+1].a {
				memo[L[i].a] = 1
			}
		}
	}

	// memoの併合
	bitMask := int64(0)
	for k := range memo {
		bitMask |= k
	}

	// membersをかき集める
	members := []int{}
	for i := 0; i < n; i++ {
		if bitMask|A[i] == bitMask {
			members = append(members, i)
		}
	}

	sum := 0
	for _, idx := range members {
		sum += B[idx]
	}

	fmt.Println(sum)
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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


Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of juices. Each of the next $$$n$$$ lines contains an integer $$$c_i$$$ $$$(1 \le c_i \le 100\,000)$$$ and a string $$$s_i$$$ — the price of the $$$i$$$-th juice and the vitamins it contains. String $$$s_i$$$ contains from $$$1$$$ to $$$3$$$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $$$s_i$$$. The order of letters in strings $$$s_i$$$ is arbitrary.

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

NoteIn the first example Petya buys the first, the second and the fourth juice. He spends $$$5 + 6 + 4 = 15$$$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $$$16$$$, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".

package main

import (
	"fmt"
	"io"
	"os"
)

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

func main() {
	in := io.Reader(os.Stdin)
	var n int
	const oo = 123456789
	const L = 3
	fmt.Fscanf(in, "%d\n", &n)
	// Initialize
	dp := make([]int, 1<<L)
	for mask := range dp {
		dp[mask] = oo
	}
	var cost int
	var juices string
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %s\n", &cost, &juices)
		var mask int
		for _, j := range juices {
			mask |= 1 << uint(j-'A')
		}
		dp[mask] = min(dp[mask], cost)
	}
	for maskA := 0; maskA < (1 << L); maskA++ {
		for maskB := 0; maskB < (1 << L); maskB++ {
			newCost := dp[maskA] + dp[maskB]
			newMask := maskA | maskB
			dp[newMask] = min(dp[newMask], newCost)
		}
	}
	ans := dp[len(dp)-1]
	if ans == oo {
		ans = -1
	}
	fmt.Println(ans)
}

package main

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

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

	var n, c int
	var s []byte
	dp := [8]int{}
	for i := 1; i < 8; i++ {
		dp[i] = -1
	}
	for Fscan(in, &n); n > 0; n-- {
		Fscan(in, &c, &s)
		v := 0
		for _, b := range s {
			v |= 1 << (b - 'A')
		}
		for i, dpi := range dp {
			if dpi != -1 && i|v != i && (dp[i|v] == -1 || dpi+c < dp[i|v]) {
				dp[i|v] = dpi + c
			}
		}
	}
	Fprint(out, dp[7])
}

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


Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).

package main

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

type brain struct {
	v    int
	link []int
}

func maxdist(v *map[int]brain, n int, src int, m int) (int, int) {
	mm := m
	nn := n
	for _, x := range (*v)[n].link {
		if x == src {
			continue
		}
		t, nt := maxdist(v, x, n, m+1)
		if t > mm {
			mm = t
			nn = nt
		}
	}

	return mm, nn
}

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

	m, _ := strconv.Atoi(s[1])
	v := make(map[int]brain)
	for i := 0; i < m; i++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")
		s := strings.Split(text, " ")
		a, _ := strconv.Atoi(s[0])
		b, _ := strconv.Atoi(s[1])
		tmpb := v[a]
		tmpb.v = a
		tmpb.link = append(tmpb.link, b)
		v[a] = tmpb
		tmpb = v[b]
		tmpb.v = b
		tmpb.link = append(tmpb.link, a)
		v[b] = tmpb
	}
	t, n := maxdist(&v, 1, 0, 0)
	t, n = maxdist(&v, n, 0, 0)

	fmt.Println(t)
}


You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5; 1 \le m \le 10^5$$$) — the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \le s_j, t_j \le n; s_j \ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.

Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.

package main

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

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

func CF1709B(in io.Reader, out io.Writer) {
	r := bufio.NewReader(in)
	w := bufio.NewWriter(out)
	defer w.Flush()

	var n, m int64
	fmt.Fscan(r, &n, &m)
	arr := make([]int64, n)
	prefix, sufFix := make([]int64, n), make([]int64, n)
	for i := int64(0); i < n; i++ {
		fmt.Fscan(r, &arr[i])
		if i == 0 {
			continue
		}
		if arr[i] < arr[i-1] {
			prefix[i] = prefix[i-1] - arr[i] + arr[i-1]
			sufFix[i] = sufFix[i-1]
		} else {
			prefix[i] = prefix[i-1]
			sufFix[i] = sufFix[i-1] - arr[i-1] + arr[i]
		}
	}

	var start, end int64
	for i := int64(0); i < m; i++ {
		fmt.Fscan(r, &start, &end)
		if start < end {
			fmt.Fprintln(w, prefix[end-1]-prefix[start-1])
		} else {
			fmt.Fprintln(w, sufFix[start-1]-sufFix[end-1])
		}
	}
}

package main
import (
	"fmt"
	"bufio"
	"os"
)

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

	fmt.Fscan(reader, &size)
	fmt.Fscan(reader, &test)

	height := make([]int64, size)
	forward := make([]int64, size)
	backward := make([]int64, size)
	quest := make([][2]int64, test)

	for i := range height {
		fmt.Fscan(reader, &height[i])
	}

	var sum int64
	for i := int64(1); i != size; i++ {
		if height[i-1] > height[i] {
			sum += height[i-1] - height[i]
		}
		forward[i] = sum
	}

	sum = 0
	for i := int64(size-1); i != 0; i-- {
		if height[i] > height[i-1] {
			sum += height[i] - height[i-1]
		}
		backward[i-1] = sum
	}

	for i := range quest {
		fmt.Fscan(reader, &quest[i][0], &quest[i][1])
	}

	for i := range quest {
		sum = 0
		if quest[i][0] < quest[i][1] {
			sum += forward[quest[i][1]-1] - forward[quest[i][0]-1]
		} else {
			sum += backward[quest[i][1]-1] - backward[quest[i][0]-1]
		}
		fmt.Fprintln(writer, sum)
	}
}

package main

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

func solve() {
	n, m := get(), get()
	a := geta(n)
	pl := make([]int64, n)
	for i := 1; i < n; i++ {
		pl[i] = pl[i-1] + int64(max(a[i-1]-a[i], 0))
	}
	pr := make([]int64, n)
	for i := n - 2; i >= 0; i-- {
		pr[i] = pr[i+1] + int64(max(a[i+1]-a[i], 0))
	}

	var s, t int
	for ; m > 0; m-- {
		s, t = get(), get()
		s--
		t--
		if s > t {
			put64ln(pr[t] - pr[s])
		} else {
			put64ln(pl[t] - pl[s])
		}
	}
}

const (
	once       = true
	maxBufSize = 0 // 10_000_000
)

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

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	in.Split(bufio.ScanWords)
	if maxBufSize > 0 {
		in.Buffer(make([]byte, maxBufSize), maxBufSize)
	}

	out = bufio.NewWriter(os.Stdout)
	defer out.Flush()

	if once {
		solve()
		return
	}

	for t := get(); t > 0; t-- {
		solve()
	}
}

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

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

func geti64() int64 {
	x, _ := strconv.ParseInt(gets(), 10, 64)
	return x
}

func gets() string {
	scan()
	return in.Text()
}

func scan() {
	in.Scan()
}

func putaln(a []int) {
	for _, v := range a {
		put(v)
		putc(' ')
	}
	putc('\n')
}

func put64(x int64) {
	out.WriteString(strconv.FormatInt(x, 10))
}

func put(x int) {
	out.WriteString(strconv.Itoa(x))
}

func put64ln(x int64) {
	put64(x)
	putc('\n')
}

func putln(x int) {
	put(x)
	putc('\n')
}

func putc(c rune) {
	out.WriteRune(c)
}

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

package main

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

func ReadLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}
	return strings.TrimRight(string(str), "\r\n")
}

func ReadLineArray(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(ReadLine(reader)), " ")
}

func ToNumberArray(array []string) []int {
	result := make([]int, len(array))
	for i := 0; i < len(array); i++ {
		number, _ := strconv.Atoi(array[i])
		result[i] = number
	}
	return result
}

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 16*1024*1024)
	firstLine := ToNumberArray(ReadLineArray(reader))
	size, times := firstLine[0], firstLine[1]

	array := ToNumberArray(ReadLineArray(reader))

	frontToEnd := make([]int64, size)
	endToFront := make([]int64, size)

	for i := 1; i < size; i++ {
		difference := array[i-1] - array[i]
		frontToEnd[i] = frontToEnd[i-1]
		if difference > 0 {
			frontToEnd[i] += int64(difference)
		}
	}

	for i := size - 1; i > 0; i-- {
		difference := array[i] - array[i-1]
		endToFront[i-1] = endToFront[i]
		if difference > 0 {
			endToFront[i-1] += int64(difference)
		}
	}

	for t := 0; t < times; t++ {
		line := ToNumberArray(ReadLineArray(reader))
		front, end := line[0], line[1]
		if front > end {
			fmt.Println(endToFront[end-1] - endToFront[front-1])
		} else {
			fmt.Println(frontToEnd[end-1] - frontToEnd[front-1])
		}
	}
}

// You can edit this code!
// Click here and start typing.
package main

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

var temp1 [100004]int64
var temp2 [100004]int64
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func main() {
	defer writer.Flush()
	var n, m, s, t int
	var a [100004]int64
	scanf("%d %d\n", &n, &m)
	for i := 1; i <= n; i++ {
		scanf("%d", &a[i])
	}
	temp1[1] = 0
	temp2[n] = 0
	for i := 2; i <= n; i++ {
		if a[i] <= a[i-1] {
			temp1[i] = temp1[i-1] + a[i-1] - a[i]
		} else {
			temp1[i] = temp1[i-1]
		}
		if a[n-i+1] <= a[n-i+2] {
			temp2[n-i+1] = temp2[n-i+2] + a[n-i+2] - a[n-i+1]
		} else {
			temp2[n-i+1] = temp2[n-i+2]
		}
	}
	for i := 1; i <= m; i++ {
		scanf("\n%d %d", &s, &t)
		if s > t {
			printf("%v\n", temp2[t]-temp2[s])
		} else {
			printf("%v\n", temp1[t]-temp1[s])
		}
	}

}

package main

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	printer := bufio.NewWriter(os.Stdout)
	defer printer.Flush()
	var n, m int
	fmt.Fscan(scanner, &n, &m)
	slice := make([]int64, n)
	for iter := 0; iter < n; iter++ {
		fmt.Fscan(scanner, &slice[iter])
	}
	ffirsttox := make([]int64, n)
	bxtolast := make([]int64, n)
	var ans int64 = 0
	for iter := 0; iter < n; iter++ {
		ffirsttox[iter] = ans
		if (iter != n-1) && (slice[iter+1] < slice[iter]) {
			ans += slice[iter] - slice[iter+1]
		}
	}
	ans = 0
	for iter := n - 1; iter >= 0; iter-- {
		bxtolast[iter] = ans
		if (iter != 0) && (slice[iter-1] < slice[iter]) {
			ans += slice[iter] - slice[iter-1]
		}
	}
	for i := 0; i < m; i++ {
		var a, b int
		fmt.Fscan(scanner, &a, &b)
		a--
		b--
		if a < b {
			fmt.Fprintln(printer, ffirsttox[b]-ffirsttox[a])
		} else {
			fmt.Fprintln(printer, bxtolast[b]-bxtolast[a])
		}
	}
}

package main

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

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

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

	prefix := make([]int64, n+1)
	suffix := make([]int64, n+1)
	prefix[0] = 0
	suffix[n] = 0
	prev := int64(0)
	for i := 0; i < n; i++ {
		if a[i] >= prev {
			prefix[i+1] = prefix[i]
		} else {
			prefix[i+1] = prefix[i] + (prev - a[i])
		}
		prev = a[i]
	}
	prev = 0
	for i := n - 1; i > -1; i-- {
		if a[i] >= prev {
			suffix[i] = suffix[i+1]
		} else {
			suffix[i] = suffix[i+1] + (prev - a[i])
		}
		prev = a[i]
	}
	// fmt.Println(suffix)
	var s, t int
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &s, &t)
		if s > t {
			fmt.Println(suffix[t-1] - suffix[s-1])
		} else {
			fmt.Println(prefix[t] - prefix[s])
		}
	}
}

package main

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

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

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

func main() {
	fmt.Fscan(reader, &n, &m)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}

	var left = make([]int64, n)
	var right = make([]int64, n)

	for i := 1; i < n; i++ {
		left[i] = int64(left[i-1]) + int64(max(a[i-1]-a[i], 0))
	}

	for i := n - 2; i >= 0; i-- {
		right[i] = int64(right[i+1]) + int64(max(a[i+1]-a[i], 0))
	}

	for i := 0; i < m; i++ {
		fmt.Fscan(reader, &s, &t)
		if s < t {
			fmt.Println(left[t-1] - left[s-1])
		} else {
			fmt.Println(right[t-1] - right[s-1])
		}
	}
}

package main

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

type Quest struct {
	s int
	t int
}

var (
	reader = bufio.NewReader(os.Stdin)
	n, m   int
	// a      []int
	// q      []Quest
)

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

func solve(n, m int, a []int, q []Quest) string {
	var left = make([]int64, n)
	var right = make([]int64, n)

	for i := 1; i < n; i++ {
		left[i] = int64(left[i-1]) + int64(max(a[i-1]-a[i], 0))
	}

	for i := n - 2; i >= 0; i-- {
		right[i] = int64(right[i+1]) + int64(max(a[i+1]-a[i], 0))
	}
	var result = make([]string, m)
	for i := 0; i < m; i++ {
		if q[i].s < q[i].t {
			result[i] = fmt.Sprint(left[q[i].t-1] - left[q[i].s-1])
		} else {
			result[i] = fmt.Sprint(right[q[i].t-1] - right[q[i].s-1])
		}
	}
	return strings.Join(result, "\n")
}

func main() {
	fmt.Fscan(reader, &n, &m)
	a := make([]int, n)
	q := make([]Quest, m)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	for i := 0; i < m; i++ {
		fmt.Fscan(reader, &q[i].s, &q[i].t)
	}
	fmt.Println(solve(n, m, a, q))
}

package main

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

func main() {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)

	var x = getIntln(reader)
	var n = x[0]
	var A = getIntln(reader)

	var previousBlock, currentBlock, fallDamage int64 = -1, -1, 0
	var ascendHealth, descendHealth = make([]int64, n), make([]int64, n)
	for i := int64(0); i < n; i++ {
		currentBlock = A[i]
		if currentBlock < previousBlock {
			fallDamage += previousBlock - currentBlock
		}
		ascendHealth[i] = fallDamage
		previousBlock = currentBlock
	}
	fallDamage = 0
	for i := n - 1; i >= 0; i-- {
		currentBlock = A[i]
		if currentBlock < previousBlock {
			fallDamage += previousBlock - currentBlock
		}
		descendHealth[i] = fallDamage
		previousBlock = currentBlock
	}

	for m := x[1]; m > 0; m-- {
		var st = getIntln(reader)
		var s, t = st[0], st[1]
		if s > t {
			writer.WriteString(strconv.FormatInt(descendHealth[t-1]-descendHealth[s-1], 10) + "\n")
		} else if s < t {
			writer.WriteString(strconv.FormatInt(ascendHealth[t-1]-ascendHealth[s-1], 10) + "\n")
		} else {
			writer.WriteString("0\n")
		}
	}
	writer.Flush()
}

func getString(in *bufio.Reader) string {
	res, _ := in.ReadString('\n')
	res = strings.ReplaceAll(res, "\n", "")
	res = strings.ReplaceAll(res, "\r", "")
	res = strings.TrimSpace(res)
	return res
}

func getIntln(in *bufio.Reader) []int64 {
	b := strings.Split(getString(in), " ")
	res := make([]int64, len(b))
	for k, v := range b {
		res[k], _ = strconv.ParseInt(v, 10, 64)
	}
	return res
}

package main

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

var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

func main() {
	defer ww.Flush()
	var n, m int
	fmt.Fscan(rr, &n, &m)
	nums := make([]int64, n)
	for i:=0;i<len(nums);i++ {
		fmt.Fscan(rr, &nums[i])
	}
	prefix := make([]int64, n+1)
	prefix[1] = 0
	for i:=1;i<len(nums);i++ {
		cur := max(0, nums[i-1] - nums[i])
		prefix[i+1] = prefix[i] + cur
	}
	lastfix := make([]int64, n+1)
	for i:=n-2;i>=0;i-- {
		cur := max(0, nums[i+1] - nums[i])
		lastfix[i] = lastfix[i+1] + cur
	}
	for i:=0;i<m;i++ {
		var a, b int64
		fmt.Fscan(rr, &a, &b)
		if a < b {
			fmt.Fprintln(ww, prefix[b] - prefix[a])
		} else {
			fmt.Fprintln(ww, lastfix[b-1] - lastfix[a-1])
		}
	}
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n, m int
	fmt.Fscan(in, &n, &m)
	nums := make([]int64, n+2)
	lsum := make([]int64, n+2)
	rsum := make([]int64, n+2)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &nums[i])
	}
	for i := 2; i <= n; i++ {
		if nums[i-1] > nums[i] {
			lsum[i] = lsum[i-1] + nums[i-1] - nums[i]
		} else {
			lsum[i] = lsum[i-1]
		}
	}
	for i := n - 1; i > 0; i-- {
		if nums[i+1] > nums[i] {
			rsum[i] = rsum[i+1] + nums[i+1] - nums[i]
		} else {
			rsum[i] = rsum[i+1]
		}
	}
	var t, s int
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &s, &t)
		if s < t {
			fmt.Fprintln(out, lsum[t]-lsum[s])
		} else {
			fmt.Fprintln(out, rsum[t]-rsum[s])
		}
	}
}

// 00
package main

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

func main() {
	var n, m, p, q int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &n, &m)
	h := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &h[i])
	}
	da := make([]int64, n)
	dd := make([]int64, n)
	for i := 0; i < n-1; i++ {
		if h[i] > h[i+1] {
			da[i+1] = h[i] - h[i+1]
		}
		da[i+1] += da[i]
	}
	for i := n - 1; i > 0; i-- {
		if h[i] > h[i-1] {
			dd[i-1] = h[i] - h[i-1]
		}
		dd[i-1] += dd[i]
	}
	for i := 0; i < m; i++ {
		damage := int64(0)
		fmt.Fscan(reader, &p, &q)
		if p > q {
			damage = dd[q-1] - dd[p-1]
		} else {
			damage = da[q-1] - da[p-1]
		}

		fmt.Println(damage)
	}
}

package main

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

const cf = true

func solve() {
	var n, m int
	fmt.Fscan(in, &n, &m)
	arr := make([]int64, n)
	for i := range arr {
		fmt.Fscan(in, &arr[i])
	}
	pref := make([]int64, n)
	prefR := make([]int64, n)
	for i := 1; i < n; i++ {
		pref[i] = pref[i-1]
		if arr[i] < arr[i-1] {
			pref[i] += arr[i-1] - arr[i]
		}
	}
	for i := n - 2; i >= 0; i-- {
		prefR[i] = prefR[i+1]
		if arr[i] < arr[i+1] {
			prefR[i] += arr[i+1] - arr[i]
		}
	}
	var s, t int
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &s, &t)
		s--
		t--
		if t > s {
			fmt.Fprintln(out, pref[t]-pref[s])
		} else {
			fmt.Fprintln(out, prefR[t]-prefR[s])
		}
	}
}

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

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

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

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

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

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

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

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

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

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

var exists = struct{}{}

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

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

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

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

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

type Ordered interface {
	Integer | Float | ~string
}

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

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

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

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

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

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

package main

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

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

	var buf bytes.Buffer

	n, q := readTwoNums(reader)

	A := readNNums(reader, n)
	quests := make([][]int, q)

	for i := 0; i < q; i++ {
		quests[i] = readNNums(reader, 2)
	}

	res := solve(A, quests)

	for i := 0; i < q; i++ {
		buf.WriteString(fmt.Sprintf("%d\n", res[i]))
	}

	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(A []int, quests [][]int) []int64 {
	n := len(A)
	dp := make([]int64, n+1)
	for i := 1; i < n; i++ {
		dp[i+1] = dp[i] + int64(max(0, A[i-1]-A[i]))
	}

	fp := make([]int64, n+1)
	for i := n - 2; i >= 0; i-- {
		fp[i] = fp[i+1] + int64(max(0, A[i+1]-A[i]))
	}

	res := make([]int64, len(quests))

	for i, quest := range quests {
		s, t := quest[0], quest[1]
		if s == t {
			res[i] = 0
			continue
		}
		if s < t {
			res[i] = dp[t] - dp[s]
		} else {
			res[i] = fp[t-1] - fp[s-1]
		}
	}

	return res
}

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

package main

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

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

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

	aa := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &aa[i])
	}
	bb := make([]int64, n)
	for i := 1; i < n; i++ {
		bb[i] = bb[i-1]
		if aa[i] < aa[i-1] {
			bb[i] += aa[i-1] - aa[i]
		}
	}
	cc := make([]int64, n)
	for i := n - 2; i >= 0; i-- {
		cc[i] = cc[i+1]
		if aa[i] < aa[i+1] {
			cc[i] += aa[i+1] - aa[i]
		}
	}

	for i := 0; i < m; i++ {
		var s, t int
		fmt.Fscan(in, &s, &t)
		if s < t {
			fmt.Fprintln(out, bb[t-1]-bb[s-1])
		} else {
			fmt.Fprintln(out, cc[t-1]-cc[s-1])
		}
	}
}

package main

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

func main() {
	inp := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)

	var n, m int
	fmt.Fscanln(inp, &n, &m)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		if i == n-1 {
			fmt.Fscanln(inp, &a[i])
		} else {
			fmt.Fscan(inp, &a[i])
		}
	}

	b := make([]int64, n)
	for i := 1; i < n; i++ {
		if a[i-1] > a[i] {
			b[i] = int64(a[i-1] - a[i])
		}
	}
	for i := 1; i < n; i++ {
		b[i] += b[i-1]
	}

	c := make([]int64, n)
	for i := 1; i < n; i++ {
		if a[n-i] > a[n-i-1] {
			c[i] = int64(a[n-i] - a[n-i-1])
		}
	}
	for i := 1; i < n; i++ {
		c[i] += c[i-1]
	}

	for i := 0; i < m; i++ {
		var s, t int
		fmt.Fscanln(inp, &s, &t)
		s--
		t--
		if s < t {
			fmt.Fprintln(out, b[t]-b[s])
		} else {
			s = n - s - 1
			t = n - t - 1
			fmt.Fprintln(out, c[t]-c[s])
		}
	}

	out.Flush()
}

package main

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

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

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

	var n int
	var m int
	var x int
	var s int
	var e int

	Fscan(in, &n)
	Fscan(in, &m)

	a := []int{}
	for i := 0; i < n; i++ {
		Fscan(in, &x)
		a = append(a, x)
	}
	dl := make([]int64, n)
	dr := make([]int64, n)
	sl, sr := int64(0), int64(0)
	for i, _ := range a {
		if i == 0 {
			continue
		}
		if a[i] < a[i-1] {
			sl += int64(a[i-1] - a[i])
		}
		dl[i] = sl
	}
	for i := n - 2; i >= 0; i-- {
		if a[i] < a[i+1] {
			sr += int64(a[i+1] - a[i])
		}
		dr[i] = sr
	}

	for l := 0; l < m; l++ {
		Fscan(in, &s, &e)
		s--
		e--
		ans := dl[e] -dl[s]
		if e < s {
			ans = dr[e] -dr[s]
		}
		Fprintln(out, ans)
	}
}

package main

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

var _, _, _ = main, rw, do

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	rw(r, w)
}

func rw(in io.Reader, out io.Writer) {
	var t int = 1
	// fmt.Fscan(in, &t)
	for ti := 0; ti < t; ti++ {
		var n, m int
		fmt.Fscan(in, &n, &m)
		b := make([]int, n)
		for i := range b {
			fmt.Fscan(in, &b[i])
		}
		c := make([][2]int, m)
		for i := range c {
			fmt.Fscan(in, &c[i][0], &c[i][1])
		}
		w1 := do(n, m, b, c)
		for _, v := range w1 {
			fmt.Fprintln(out, v)
		}
	}
}

func do(n, m int, b []int, c [][2]int) []int64 {
	s1 := make([]int64, n)
	s2 := make([]int64, n)
	for i := 1; i < n; i++ {
		v := b[i-1] - b[i]
		if v < 0 {
			v = 0
		}
		s1[i] += s1[i-1] + int64(v)
	}
	for i := n - 2; i >= 0; i-- {
		v := b[i+1] - b[i]
		if v < 0 {
			v = 0
		}
		s2[i] += s2[i+1] + int64(v)
	}
	ans := make([]int64, m)
	for i, v := range c {
		x := v[0] - 1
		y := v[1] - 1
		s := s1
		if x > y {
			s = s2
		}
		ans[i] = s[y] - s[x]
	}
	return ans
}

package main

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

func A1() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	//Fscan(in, &cas)
	var sol func()
	// Coding...beg!
	sol = func() {
		var n, m int64

		Fscan(in, &n, &m)
		a := make([]int64, n+1)
		up := make([]int64, n+1)
		down := make([]int64, n+1)
		for i := 1; i <= int(n); i++ {
			Fscan(in, &a[i])
		}
		for i := 2; i <= int(n); i++ {
			up[i] = up[i-1]
			down[i] = down[i-1]
			if a[i] > a[i-1] {
				up[i] += (a[i] - a[i-1])
			} else if a[i] < a[i-1] {
				down[i] += (a[i-1] - a[i])
			} else {

			}
		}
		for m > 0 {
			m--
			var x, y int
			Fscan(in, &x, &y)
			if x < y {
				Fprintln(out, down[y]-down[x])
			} else {
				Fprintln(out, up[x]-up[y])
			}
		}
	}
	// Coding...ove!
	for i := 0; i < cas; i++ {
		sol()
	}
}
func main() { A1() }

package main

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

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

func CF1709B(in io.Reader, out io.Writer) {
	r := bufio.NewReader(in)
	w := bufio.NewWriter(out)
	defer w.Flush()

	var n, m int
	fmt.Fscan(r, &n, &m)
	arr := make([]int, n)
	prefix, sufFix := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(r, &arr[i])
		if i == 0 {
			continue
		}
		if arr[i] < arr[i-1] {
			prefix[i] = prefix[i-1] - arr[i] + arr[i-1]
			sufFix[i] = sufFix[i-1]
		} else {
			prefix[i] = prefix[i-1]
			sufFix[i] = sufFix[i-1] - arr[i-1] + arr[i]
		}
	}

	var start, end int
	for i := 0; i < m; i++ {
		fmt.Fscan(r, &start, &end)
		if start < end {
			fmt.Fprintln(w, prefix[end-1]-prefix[start-1])
		} else {
			fmt.Fprintln(w, sufFix[start-1]-sufFix[end-1])
		}
	}
}

package main
import (
	"fmt"
	"bufio"
	"os"
)

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

	fmt.Fscan(reader, &size)
	fmt.Fscan(reader, &test)

	height := make([]int, size)
	forward := make([]int, size)
	backward := make([]int, size)
	quest := make([][2]int, test)

	for i := range height {
		fmt.Fscan(reader, &height[i])
	}

	sum := 0
	for i := 1; i != size; i++ {
		if height[i-1] > height[i] {
			sum += height[i-1] - height[i]
		}
		forward[i] = sum
	}

	sum = 0
	for i := size-1; i != 0; i-- {
		if height[i] > height[i-1] {
			sum += height[i] - height[i-1]
		}
		backward[i-1] = sum
	}

	for i := range quest {
		fmt.Fscan(reader, &quest[i][0], &quest[i][1])
	}

	for i := range quest {
		sum = 0
		if quest[i][0] < quest[i][1] {
			sum += forward[quest[i][1]-1] - forward[quest[i][0]-1]
		} else {
			sum += backward[quest[i][1]-1] - backward[quest[i][0]-1]
		}
		fmt.Fprintln(writer, sum)
	}
}

package main

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

func solve() {
	n, m := get(), get()
	a := geta(n)
	pl := make([]int, n)
	for i := 1; i < n; i++ {
		pl[i] = pl[i-1] + max(a[i-1]-a[i], 0)
	}
	pr := make([]int, n)
	for i := n - 2; i >= 0; i-- {
		pr[i] = pr[i+1] + max(a[i+1]-a[i], 0)
	}

	var s, t int
	for ; m > 0; m-- {
		s, t = get(), get()
		s--
		t--
		if s > t {
			putln(pr[t] - pr[s])
		} else {
			putln(pl[t] - pl[s])
		}
	}
}

const (
	once       = true
	maxBufSize = 0 // 10_000_000
)

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

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	in.Split(bufio.ScanWords)
	if maxBufSize > 0 {
		in.Buffer(make([]byte, maxBufSize), maxBufSize)
	}

	out = bufio.NewWriter(os.Stdout)
	defer out.Flush()

	if once {
		solve()
		return
	}

	for t := get(); t > 0; t-- {
		solve()
	}
}

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

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

func gets() string {
	scan()
	return in.Text()
}

func scan() {
	in.Scan()
}

func putaln(a []int) {
	for _, v := range a {
		put(v)
		putc(' ')
	}
	putc('\n')
}

func put(x int) {
	out.WriteString(strconv.Itoa(x))
}

func putln(x int) {
	put(x)
	putc('\n')
}

func putc(c rune) {
	out.WriteRune(c)
}

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

package main

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

func ReadLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}
	return strings.TrimRight(string(str), "\r\n")
}

func ReadLineArray(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(ReadLine(reader)), " ")
}

func ToNumberArray(array []string) []int {
	result := make([]int, len(array))
	for i := 0; i < len(array); i++ {
		number, _ := strconv.Atoi(array[i])
		result[i] = number
	}
	return result
}

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 16*1024*1024)
	firstLine := ToNumberArray(ReadLineArray(reader))
	size, times := firstLine[0], firstLine[1]

	array := ToNumberArray(ReadLineArray(reader))

	frontToEnd := make([]int, size)
	endToFront := make([]int, size)

	for i := 1; i < size; i++ {
		difference := array[i-1] - array[i]
		frontToEnd[i] = frontToEnd[i-1]
		if difference > 0 {
			frontToEnd[i] += difference
		}
	}

	for i := size - 1; i > 0; i-- {
		difference := array[i] - array[i-1]
		endToFront[i-1] = endToFront[i]
		if difference > 0 {
			endToFront[i-1] += difference
		}
	}

	for t := 0; t < times; t++ {
		line := ToNumberArray(ReadLineArray(reader))
		front, end := line[0], line[1]
		if front > end {
			fmt.Println(endToFront[end-1] - endToFront[front-1])
		} else {
			fmt.Println(frontToEnd[end-1] - frontToEnd[front-1])
		}
	}
}

// You can edit this code!
// Click here and start typing.
package main

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

var temp1 [100004]int64
var temp2 [100004]int64
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func main() {
	defer writer.Flush()
	var n, m, s, t int
	var a [100004]int64
	scanf("%d %d\n", &n, &m)
	for i := 1; i <= n; i++ {
		scanf("%ld", &a[i])
	}
	temp1[1] = 0
	temp2[n] = 0
	for i := 2; i <= n; i++ {
		if a[i] <= a[i-1] {
			temp1[i] = temp1[i-1] + a[i-1] - a[i]
		} else {
			temp1[i] = temp1[i-1]
		}
		if a[n-i+1] <= a[n-i+2] {
			temp2[n-i+1] = temp2[n-i+2] + a[n-i+2] - a[n-i+1]
		} else {
			temp2[n-i+1] = temp2[n-i+2]
		}
	}
	for i := 1; i <= m; i++ {
		scanf("\n%d %d", &s, &t)
		if s > t {
			printf("%ld\n", temp2[t]-temp2[s])
		} else {
			printf("%ld\n", temp1[t]-temp1[s])
		}
	}

}

// You can edit this code!
// Click here and start typing.
package main

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

var temp1 [100004]int
var temp2 [100004]int
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func main() {
	defer writer.Flush()
	var n, m, s, t int
	var a [100004]int
	scanf("%d %d\n", &n, &m)
	for i := 1; i <= n; i++ {
		scanf("%d", &a[i])
	}
	temp1[1] = 0
	temp2[n] = 0
	for i := 2; i <= n; i++ {
		if a[i] <= a[i-1] {
			temp1[i] = temp1[i-1] + a[i-1] - a[i]
		} else {
			temp1[i] = temp1[i-1]
		}
		if a[n-i+1] <= a[n-i+2] {
			temp2[n-i+1] = temp2[n-i+2] + a[n-i+2] - a[n-i+1]
		} else {
			temp2[n-i+1] = temp2[n-i+2]
		}
	}
	for i := 1; i <= m; i++ {
		scanf("\n%d %d", &s, &t)
		if s > t {
			printf("%d\n", temp2[t]-temp2[s])
		} else {
			printf("%d\n", temp1[t]-temp1[s])
		}
	}

}

package main

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	printer := bufio.NewWriter(os.Stdout)
	defer printer.Flush()
	var n, m int
	fmt.Fscan(scanner, &n, &m)
	slice := make([]int, n)
	for iter := 0; iter < n; iter++ {
		fmt.Fscan(scanner, &slice[iter])
	}
	ffirsttox := make([]int, n)
	bfirsttox := make([]int, n)
	fxtolast := make([]int, n)
	bxtolast := make([]int, n)
	ans := 0
	for iter := 0; iter < n; iter++ {
		ffirsttox[iter] = ans
		if (iter != n-1) && (slice[iter+1] < slice[iter]) {
			ans += slice[iter] - slice[iter+1]
		}
	}
	ans = 0
	for iter := n - 1; iter > 0; iter-- {
		fxtolast[iter] = ans
		if (iter != 0) && (slice[iter-1] > slice[iter]) {
			ans += slice[iter-1] - slice[iter]
		}
	}
	ans = 0
	for iter := n - 1; iter >= 0; iter-- {
		bxtolast[iter] = ans
		if (iter != 0) && (slice[iter-1] < slice[iter]) {
			ans += slice[iter] - slice[iter-1]
		}
	}
	ans = 0
	for iter := 0; iter < n; iter++ {
		bfirsttox[iter] = ans
		if (iter != n-1) && (slice[iter+1] > slice[iter]) {
			ans += slice[iter+1] - slice[iter]
		}
	}
	for i := 0; i < m; i++ {
		var a, b int
		fmt.Fscan(scanner, &a, &b)
		a--
		b--
		if a < b {
			fmt.Fprintln(printer, ffirsttox[b]-ffirsttox[a])
		} else {
			fmt.Fprintln(printer, bxtolast[b]-bxtolast[a])
		}
	}
}

package main

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	printer := bufio.NewWriter(os.Stdout)
	defer printer.Flush()
	var n, m int
	fmt.Fscan(scanner, &n, &m)
	slice := make([]int, n)
	for iter := 0; iter < n; iter++ {
		fmt.Fscan(scanner, &slice[iter])
	}
	ffirsttox := make([]int, n)
	bfirsttox := make([]int, n)
	fxtolast := make([]int, n)
	bxtolast := make([]int, n)
	ans := 0
	for iter := 0; iter < n; iter++ {
		ffirsttox[iter] = ans
		if (iter != n-1) && (slice[iter+1] < slice[iter]) {
			ans += slice[iter] - slice[iter+1]
		}
	}
	ans = 0
	for iter := n - 1; iter > 0; iter-- {
		fxtolast[iter] = ans
		if (iter != 0) && (slice[iter-1] > slice[iter]) {
			ans += slice[iter-1] - slice[iter]
		}
	}
	ans = 0
	for iter := n - 1; iter >= 0; iter-- {
		bxtolast[iter] = ans
		if (iter != 0) && (slice[iter-1] < slice[iter]) {
			ans += slice[iter] - slice[iter-1]
		}
	}
	ans = 0
	for iter := 0; iter < n; iter++ {
		bfirsttox[iter] = ans
		if (iter != n-1) && (slice[iter+1] > slice[iter]) {
			ans += slice[iter+1] - slice[iter]
		}
	}
	for i := 0; i < n; i++ {
		fmt.Fprintln(printer, "!!!", ffirsttox[i], bxtolast[i])
	}
	for i := 0; i < m; i++ {
		var a, b int
		fmt.Fscan(scanner, &a, &b)
		a--
		b--
		if a < b {
			fmt.Fprintln(printer, ffirsttox[b]-ffirsttox[a])
		} else {
			fmt.Fprintln(printer, bxtolast[b]-bxtolast[a])
		}
	}
}

package main

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

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

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

	prefix := make([]int, n+1)
	suffix := make([]int, n+1)
	prefix[0] = 0
	suffix[n] = 0
	prev := 0
	for i := 0; i < n; i++ {
		if a[i] >= prev {
			prefix[i+1] = prefix[i]
		} else {
			prefix[i+1] = prefix[i] + (prev - a[i])
		}
		prev = a[i]
	}
	prev = 0
	for i := n - 1; i > -1; i-- {
		if a[i] >= prev {
			suffix[i] = suffix[i+1]
		} else {
			suffix[i] = suffix[i+1] + (prev - a[i])
		}
		prev = a[i]
	}
	// fmt.Println(suffix)
	var s, t int
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &s, &t)
		if s > t {
			fmt.Println(suffix[t-1] - suffix[s-1])
		} else {
			fmt.Println(prefix[t] - prefix[s])
		}
	}
}

package main

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

type Quest struct {
	s int
	t int
}

var (
	reader = bufio.NewReader(os.Stdin)
	n, m   int
	// a      []int
	// q      []Quest
)

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

func solve(n, m int, a []int, q []Quest) string {
	var left = make([]int64, n)
	var right = make([]int64, n)

	for i := 1; i < n; i++ {
		left[i] = int64(left[i-1]) + int64(max(a[i-1]-a[i], 0))
	}

	for i := n - 2; i >= 0; i-- {
		right[i] = int64(right[i+1]) + int64(max(a[i+1]-a[i], 0))
	}
	fmt.Println(left, right)
	var result = make([]string, m)
	for i := 0; i < m; i++ {
		if q[i].s < q[i].t {
			result[i] = fmt.Sprint(left[q[i].t-1] - left[q[i].s-1])
		} else {
			result[i] = fmt.Sprint(right[q[i].t-1] - right[q[i].s-1])
		}
	}
	return strings.Join(result, "\n")
}

func main() {
	fmt.Fscan(reader, &n, &m)
	a := make([]int, n)
	q := make([]Quest, m)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	for i := 0; i < m; i++ {
		fmt.Fscan(reader, &q[i].s, &q[i].t)
	}
	fmt.Println(solve(n, m, a, q))
}

package main

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

func main() {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)

	var x = getIntln(reader)
	var n = x[0]
	var A = getIntln(reader)

	var previousBlock, currentBlock, fallDamage = -1, -1, 0
	var ascendHealth, descendHealth = make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		currentBlock = A[i]
		if currentBlock < previousBlock {
			fallDamage += previousBlock - currentBlock
		}
		ascendHealth[i] = fallDamage
		previousBlock = currentBlock
	}
	fallDamage = 0
	for i := n - 1; i >= 0; i-- {
		currentBlock = A[i]
		if currentBlock < previousBlock {
			fallDamage += previousBlock - currentBlock
		}
		descendHealth[i] = fallDamage
		previousBlock = currentBlock
	}

	for m := x[1]; m > 0; m-- {
		var st = getIntln(reader)
		var s, t = st[0], st[1]
		if s > t {
			writer.WriteString(strconv.Itoa(descendHealth[t-1]-descendHealth[s-1]) + "\n")
		} else if s < t {
			writer.WriteString(strconv.Itoa(ascendHealth[t-1]-ascendHealth[s-1]) + "\n")
		} else {
			writer.WriteString("0\n")
		}
	}
	writer.Flush()
}

func getString(in *bufio.Reader) string {
	res, _ := in.ReadString('\n')
	res = strings.ReplaceAll(res, "\n", "")
	res = strings.ReplaceAll(res, "\r", "")
	res = strings.TrimSpace(res)
	return res
}

func getIntln(in *bufio.Reader) []int {
	b := strings.Split(getString(in), " ")
	res := make([]int, len(b))
	for k, v := range b {
		res[k], _ = strconv.Atoi(v)
	}
	return res
}

package main

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

var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

func main() {
	defer ww.Flush()
	var n, m int
	fmt.Fscan(rr, &n, &m)
	nums := make([]int, n)
	for i:=0;i<len(nums);i++ {
		fmt.Fscan(rr, &nums[i])
	}
	prefix := make([]int, n+1)
	prefix[1] = 0
	for i:=1;i<len(nums);i++ {
		cur := max(0, nums[i-1] - nums[i])
		prefix[i+1] = prefix[i] + cur
	}
	lastfix := make([]int, n+1)
	for i:=n-2;i>=0;i-- {
		cur := max(0, nums[i+1] - nums[i])
		lastfix[i] = lastfix[i+1] + cur
	}
	for i:=0;i<m;i++ {
		var a, b int
		fmt.Fscan(rr, &a, &b)
		if a < b {
			fmt.Fprintln(ww, prefix[b] - prefix[a])
		} else {
			fmt.Fprintln(ww, lastfix[b-1] - lastfix[a-1])
		}
	}
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n, m int
	fmt.Fscan(in, &n, &m)
	nums := make([]int, n+2)
	lsum := make([]int, n+2)
	rsum := make([]int, n+2)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &nums[i])
	}
	for i := 2; i <= n; i++ {
		if nums[i-1] > nums[i] {
			lsum[i] = lsum[i-1] + nums[i-1] - nums[i]
		} else {
			lsum[i] = lsum[i-1]
		}
	}
	for i := n - 1; i > 0; i-- {
		if nums[i+1] > nums[i] {
			rsum[i] = rsum[i+1] + nums[i+1] - nums[i]
		} else {
			rsum[i] = rsum[i+1]
		}
	}
	var t, s int
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &s, &t)
		if s < t {
			fmt.Fprintln(out, lsum[t]-lsum[s])
		} else {
			fmt.Fprintln(out, rsum[t]-rsum[s])
		}
	}
}

package main

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

const cf = true

func solve() {
	var n, m int
	fmt.Fscan(in, &n, &m)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscan(in, &arr[i])
	}
	pref := make([]int, n)
	prefR := make([]int, n)
	for i := 1; i < n; i++ {
		pref[i] = pref[i-1]
		if arr[i] < arr[i-1] {
			pref[i] += arr[i-1] - arr[i]
		}
	}
	for i := n - 2; i >= 0; i-- {
		prefR[i] = prefR[i+1]
		if arr[i] < arr[i+1] {
			prefR[i] += arr[i+1] - arr[i]
		}
	}
	var s, t int
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &s, &t)
		s--
		t--
		if t > s {
			fmt.Fprintln(out, pref[t]-pref[s])
		} else {
			fmt.Fprintln(out, prefR[t]-prefR[s])
		}
	}
}

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

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

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

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

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

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

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

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

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

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

var exists = struct{}{}

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

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

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

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

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

type Ordered interface {
	Integer | Float | ~string
}

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

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

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

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

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

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