package main

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

const MAXN = 100
const MAXC = 10

func main() {
	var n, q, c int
	var pre [MAXN + 1][MAXN + 1][MAXC + 1]int

	stdin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(stdin, "%d %d %d\n", &n, &q, &c)

	for i := 0; i < n; i++ {
		var starx, stary, brightness int
		fmt.Fscanf(stdin, "%d %d %d\n", &starx, &stary, &brightness)
		pre[starx][stary][brightness] += 1
	}

	for i := 1; i <= MAXN; i++ {
		for j := 1; j <= MAXN; j++ {
			for b := 0; b <= c; b++ {
				pre[i][j][b] += pre[i-1][j][b] + pre[i][j-1][b] - pre[i-1][j-1][b]
			}
		}
	}

	stdout := bufio.NewWriter(os.Stdout)
	for i := 0; i < q; i++ {
		var t, x1, y1, x2, y2 int
		var ans = 0
		fmt.Fscanf(stdin,"%d %d %d %d %d\n", &t, &x1, &y1, &x2, &y2)

		for b := 0; b <= c; b++ {
			ans += (pre[x2][y2][b] - pre[x1-1][y2][b] -
				pre[x2][y1-1][b] + pre[x1-1][y1-1][b]) * ((b + t) % (c + 1))
		}
		fmt.Fprintf(stdout,"%d\n", ans)
	}

	stdout.Flush()

}

package main

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

const SKY_SIZE int = 101

func Init() {
}

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

	sky := make([][][]int, C + 1)
	for t := 0; t <= C; t++ {
		sky[t] = MakeIntMatrix(SKY_SIZE, SKY_SIZE)
	}

	for i := 0; i < N; i++ {
		X := io.NextInt()
		Y := io.NextInt()
		S := io.NextInt()

		for t := 0; t <= C; t++ {
			sky[t][X][Y] += S
			S = (S + 1) % (C + 1)
		}
	}

	sums := make([][][]int, C + 1)
	for t := 0; t <= C; t++ {
		sums[t] = MakeIntMatrix(SKY_SIZE + 1, SKY_SIZE + 1)
	}

	for t := 0; t <= C; t++ {
		for r := 1; r <= SKY_SIZE; r++ {
			for c := 1; c <= SKY_SIZE; c++ {
				sums[t][r][c] = sky[t][r - 1][c - 1] + sums[t][r][c - 1] + sums[t][r - 1][c] - sums[t][r - 1][c - 1]
			}
		}
	}

	for q := 0; q < Q; q++ {
		T := io.NextInt()
		X1 := io.NextInt()
		Y1 := io.NextInt()
		X2 := io.NextInt()
		Y2 := io.NextInt()

		t := T % (C + 1)
		io.Println(sums[t][X2 + 1][Y2 + 1] - sums[t][X1][Y2 + 1] - sums[t][X2 + 1][Y1] + sums[t][X1][Y1])
	}
}

func MakeIntMatrix(rows, cols int) [][]int {
	mat := make([][]int, rows)
	for i := range mat {
		mat[i] = make([]int, cols)
	}
	return mat
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

import (
	"fmt"
)

const MAXN = 100

func main() {
	var n, q, c int
	var input [101][101]int
	var pre [101][101][11]int

	fmt.Scanf("%d %d %d\n", &n, &q, &c)

	for i := 0; i < n; i++ {
		var starx, stary, brightness int
		fmt.Scanf("%d %d %d\n", &starx, &stary, &brightness)
		input[starx][stary] = brightness + 1
	}

	var included = 0
	for i := 1; i <= MAXN; i++ {
		for j := 1; j <= MAXN; j++ {
			for b := 0; b <= c; b++ {
				included = 0
				if b == input[i][j]-1 {
					included = 1
				}
				pre[i][j][b] = pre[i-1][j][b] + pre[i][j-1][b] + included - pre[i-1][j-1][b]
				//if included == 1 {
				//	fmt.Printf("included: %d %d %d %d\n", i, j, b, pre[i][j][b])
				//}
			}
		}
	}

	for i := 0; i < q; i++ {
		var t, x1, y1, x2, y2 int
		var ans = 0
		fmt.Scanf("%d %d %d %d %d\n", &t, &x1, &y1, &x2, &y2)

		for b := 0; b <= c; b++ {
			ans += (pre[x2][y2][b] - pre[x1-1][y2][b] -
				pre[x2][y1-1][b] + pre[x1-1][y1-1][b]) * ((b + t) % (c + 1))
		}
		fmt.Println(ans)
	}

}

package main

import (
	"fmt"
)

const MAXN  = 100

func main() {
	var n, q, c int
	var input [101][101]int
	var pre [101][101][11]int

	fmt.Scanf("%d %d %d\n", &n, &q, &c)

	for i := 0; i < n; i++ {
		var starx, stary, brightness int
		fmt.Scanf("%d %d %d\n", &starx, &stary, &brightness)
		input[starx][stary] = brightness + 1
	}

	for i := 1; i <= MAXN; i++ {
		for j := 1; j <= MAXN; j++ {
			for b := 0; b <= c; b++ {
				var included = 0
				if b == input[i][j] - 1 {
					included = 1
				}
				pre[i][j][b] = pre[i-1][j][b] + pre[i][j-1][b] + included - pre[i-1][j-1][b]
			}
		}
	}

	for i := 0; i < q; i++ {
		var t, x1, y1, x2, y2 int
		var ans = 0
		fmt.Scanf("%d %d %d %d %d\n", &t, &x1, &y1, &x2, &y2)

		for b := 0; b <= c; b++ {
			included := 0
			if input[x1][y1] - 1 == b {
				included = 1
			}
			ans += (pre[x2][y2][b] - pre[x1][y1][b] + included) * ((b + t) % (c + 1))
		}
		fmt.Println(ans)
	}

}

package main

import (
	"fmt"
)

const MAXN = 100

func main() {
	var n, q, c int
	var input [101][101]int
	var pre [101][101][11]int

	fmt.Scanf("%d %d %d\n", &n, &q, &c)

	for i := 0; i < n; i++ {
		var starx, stary, brightness int
		fmt.Scanf("%d %d %d\n", &starx, &stary, &brightness)
		input[starx][stary] = brightness + 1
	}

	for i := 1; i <= MAXN; i++ {
		for j := 1; j <= MAXN; j++ {
			for b := 0; b <= c; b++ {
				var included = 0
				if b == input[i][j]-1 {
					included = 1
				}
				pre[i][j][b] = pre[i-1][j][b] + pre[i][j-1][b] + included - pre[i-1][j-1][b]
			}
		}
	}

	for i := 0; i < q; i++ {
		var t, x1, y1, x2, y2 int
		var ans = 0
		fmt.Scanf("%d %d %d %d %d\n", &t, &x1, &y1, &x2, &y2)

		for b := 0; b <= c; b++ {
			ans += (pre[x2][y2][b] - pre[x1-1][y2][b] -
				pre[x2][y1-1][b] + pre[x1-1][y1-1][b]) * ((b + t) % (c + 1))
		}
		fmt.Println(ans)
	}

}

package main

import (
	"fmt"
)

const MAXN = 100

func main() {
	var n, q, c int64
	var input [101][101]int64
	var pre [101][101][11]int64

	fmt.Scanf("%d %d %d\n", &n, &q, &c)

	for i := int64(0); i < n; i++ {
		var starx, stary, brightness int64
		fmt.Scanf("%d %d %d\n", &starx, &stary, &brightness)
		input[starx][stary] = brightness + 1
	}

	for i := 1; i <= MAXN; i++ {
		for j := 1; j <= MAXN; j++ {
			for b := int64(0); b <= c; b++ {
				var included = int64(0)
				if b == input[i][j]-1 {
					included = 1
				}
				pre[i][j][b] = pre[i-1][j][b] + pre[i][j-1][b] + included - pre[i-1][j-1][b]
			}
		}
	}

	for i := int64(0); i < q; i++ {
		var t, x1, y1, x2, y2 int64
		var ans = int64(0)
		fmt.Scanf("%d %d %d %d %d\n", &t, &x1, &y1, &x2, &y2)

		for b := int64(0); b <= c; b++ {
			ans += (pre[x2][y2][b] - pre[x1-1][y2][b] -
				pre[x2][y1-1][b] + pre[x1-1][y1-1][b]) * ((b + t) % (c + 1))
		}
		fmt.Println(ans)
	}

}

package main

import (
	"fmt"
)

const MAXN  = 100

func main() {
	var n, q, c int
	var input [101][101]int
	var pre [101][101][11]int

	fmt.Scanf("%d %d %d\n", &n, &q, &c)

	for i := 0; i < n; i++ {
		var starx, stary, brightness int
		fmt.Scanf("%d %d %d\n", &starx, &stary, &brightness)
		input[starx][stary] = brightness + 1
	}

	for i := 1; i <= MAXN; i++ {
		for j := 1; j <= MAXN; j++ {
			for b := 0; b <= c; b++ {
				var counted = 0
				if b == input[i][j] - 1 {
					counted = 1
				}
				pre[i][j][b] = pre[i-1][j][b] + pre[i][j-1][b] + counted - pre[i-1][j-1][b]
			}
		}
	}

	for i := 0; i < q; i++ {
		var t, x1, y1, x2, y2 int
		var ans int
		fmt.Scanf("%d %d %d %d %d\n", &t, &x1, &y1, &x2, &y2)

		for c1 := 0; c1 <= c; c1++ {
			included := 0
			if input[x1][y1] - 1 == c1 {
				included = 1
			}
			ans += (pre[x2][y2][c1] - pre[x1][y1][c1] + included) * ((c1 + t) % (c + 1))
		}
		fmt.Println(ans)
	}

}

package main

import (
	"fmt"
)

const MAXN  = 100

func main() {
	var n, q, c int
	var input [101][101]int
	var pre [101][101][11]int

	fmt.Scanf("%d %d %d\n", &n, &q, &c)

	for i := 0; i < n; i++ {
		var starx, stary, brightness int
		fmt.Scanf("%d %d %d\n", &starx, &stary, &brightness)
		input[starx][stary] = brightness + 1
	}

	for i := 1; i <= MAXN; i++ {
		for j := 1; j <= MAXN; j++ {
			for b := 0; b <= c; b++ {
				var counted = 0
				if b == input[i][j] - 1 {
					counted = 1
				}
				pre[i][j][b] = pre[i-1][j][b] + pre[i][j-1][b] + counted - pre[i-1][j-1][b]
			}
		}
	}

	for i := 0; i < q; i++ {
		var t, x1, y1, x2, y2 int
		var ans int
		fmt.Scanf("%d %d %d %d %d\n", &t, &x1, &y1, &x2, &y2)

		for c1 := 0; c1 <= 10; c1++ {
			included := 0
			if input[x1][y1] - 1 == c1 {
				included = 1
			}
			ans += (pre[x2][y2][c1] - pre[x1][y1][c1] + included) * ((c1 + t) % (c + 1))
		}
		fmt.Println(ans)
	}

}


package main

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

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

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

func getLine() string {
	s, _ := reader.ReadString('\n')
	if strings.HasSuffix(s, "\r\n") {
		s = s[:len(s)-2]
	} else if strings.HasSuffix(s, "\n") {
		s = s[:len(s)-1]
	}
	return s
}
func getLine2Int() (n int) {
	scanf("%d\n", &n)
	return
}
func getLine2Int2() (a, b int) {
	scanf("%d %d\n", &a, &b)
	return
}
func getLine2Ints(n int) []int {
	ans := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &ans[i])
	}
	scanf("%d\n", &ans[n-1])
	return ans
}

func pcheck(i bool) {
	if i {
		printf("YES\n")
	} else {
		printf("NO\n")
	}
}

var debug = true

func see(a interface{}) {
	if debug {
		printf("DEBUG:%v\n", a)
	}
}

var now = make([]int, 1000)
var nowsum = 0

func fixDiff(diff int) int {
	if diff > 0 {
		return diff
	}
	status := 0
	for i := 0; ; i++ {
		switch status {
		case 0:
			now[i], diff = 0, diff+now[i]
			if diff > 0 {
				status = 1
			}
		case 1:
			if now[i] != 9 {
				diff, now[i] = diff-1, now[i]+1
				return diff
			}
			now[i], diff = 0, diff+now[i]
		}
	}
}

func addDiff(diff int) {
	for i := 0; diff > 0; i++ {
		now[i], diff = now[i]+diff, 0
		if now[i] > 9 {
			now[i], diff = 9, now[i]-9
		}
	}
}

func put() {
	status := 0
	for i := 999; i >= 0; i-- {
		switch status {
		case 0:
			if now[i] != 0 { // first item not equals zero
				printf("%d", now[i])
				status = 1
			}
		case 1:
			printf("%d", now[i])
		}
	}
	printf("\n")
}

func main() {
	defer writer.Flush()

	n := getLine2Int()
	for in := 0; in < n; in++ {
		tmp := getLine2Int()
		addDiff(fixDiff(tmp - nowsum))
		nowsum = tmp
		put()
	}
}

package main

import "os"
import "fmt"
import "bufio"

var (
    reader = bufio.NewReader(os.Stdin)
)

const MAXLEN = 90000

var number [2][MAXLEN]byte
var pre, now *[MAXLEN]byte

func output(data [MAXLEN]byte) {
    for i, flag := 0, false; i < MAXLEN; i++ {
        if(data[i] != 0) { flag = true }
        if(flag) {
            fmt.Print(data[i])
        }
    }
    fmt.Println()
}

func work(presum, data uint64) {
    for i := 0; i < MAXLEN; i++ {
        now[i] = 0
    }
    if(data > presum) {
        data -= presum
        for i := MAXLEN-1; i >= 0; i-- {
            if(data > uint64(9-pre[i])) {
                data -= uint64(9-pre[i])
                now[i] = 9
            } else {
                now[i] = pre[i] + byte(data)
                data = 0;
            }
        }
    } else {
        data = presum - data + 1
        add := 0
        for i, flag, sum := MAXLEN-1, false, uint64(0); i >= 0; i-- {
            if(data > sum) {
                sum += uint64(pre[i])
            } else if(flag == false) {
                if(pre[i] < 9) {
                    now[i] = pre[i] + byte(1)
                    flag = true
                    add = i
                } else {
                    sum += uint64(pre[i])
                    now[i] = pre[i]
                }
            } else {
                if(sum + data > 0) {
                    sum -= data
                    for j := MAXLEN-1; j > add; j-- {
                        if(sum > 9) {
                            now[j] = 9
                            sum -= 9
                        } else {
                            now[j] = byte(sum)
                            sum = 0
                        }
                    }
                    data = 0
                }
                now[i] = pre[i]
            }
        }
    }
    output(*now)
    now, pre = pre, now
}

func main() {
    var n uint64
    fmt.Fscan(reader, &n)
    pre, now = &number[0], &number[1]
    for i, presum := uint64(0), uint64(0); i < n; i++ {
        var data uint64
        fmt.Fscan(reader, &data)
        work(presum, data)
        presum = data
    }
}

package main

import "os"
import "fmt"
import "bufio"

var (
    reader = bufio.NewReader(os.Stdin)
)

const MAXLEN = 90000

var number [2][MAXLEN]byte
var pre, now *[MAXLEN]byte

func output(data [MAXLEN]byte) {
    for i, flag := 0, false; i < MAXLEN; i++ {
        if(data[i] != 0) { flag = true }
        if(flag) {
            fmt.Print(data[i])
        }
    }
    fmt.Println()
}

func work(presum, data uint64) {
    for i := 0; i < MAXLEN; i++ {
        now[i] = 0
    }
    if(data > presum) {
        data -= presum
        for i := MAXLEN-1; i >= 0; i-- {
            if(data > uint64(9-pre[i])) {
                data -= uint64(9-pre[i])
                now[i] = 9
            } else {
                now[i] = pre[i] + byte(data)
                data = 0;
            }
        }
    } else {
        data = presum - data + 1
        add := 0
        for i, flag, sum := MAXLEN-1, false, uint64(0); i >= 0; i-- {
            if(data > sum) {
                sum += uint64(pre[i])
            } else if(flag == false) {
                if(pre[i] < 9) {
                    now[i] = pre[i] + byte(1)
                    flag = true
                    add = i
                } else {
                    sum += uint64(pre[i])
                    now[i] = pre[i]
                }
            } else {
                if(sum + data > 0) {
                    sum -= data
                    for j := MAXLEN-1; j > add; j-- {
                        if(sum > 9) {
                            now[j] = 9
                            sum -= 9
                        } else {
                            now[j] = byte(sum)
                            sum = 0
                        }
                    }
                }
                now[i] = pre[i]
            }
        }
    }
    output(*now)
    now, pre = pre, now
}

func main() {
    var n uint64
    fmt.Fscan(reader, &n)
    pre, now = &number[0], &number[1]
    for i, presum := uint64(0), uint64(0); i < n; i++ {
        var data uint64
        fmt.Fscan(reader, &data)
        work(presum, data)
        presum = data
    }
}

package main

import "os"
import "fmt"
import "bufio"

var (
    reader = bufio.NewReader(os.Stdin)
)

const MAXLEN = 90000

var number [2][MAXLEN]byte
var pre, now *[MAXLEN]byte

func output(data [MAXLEN]byte) {
    for i, flag := 0, false; i < MAXLEN; i++ {
        if(data[i] != 0) { flag = true }
        if(flag) {
            fmt.Print(data[i])
        }
    }
    fmt.Println()
}

func work(presum, data uint64) {
    for i := 0; i < MAXLEN; i++ {
        now[i] = 0
    }
    if(data > presum) {
        data -= presum
        for i := MAXLEN-1; i >= 0; i-- {
            if(data > uint64(9-pre[i])) {
                data -= uint64(9-pre[i])
                now[i] = 9
            } else {
                now[i] = pre[i] + byte(data)
                data = 0;
            }
        }
    } else {
        data = presum - data + 1
        for i, flag := MAXLEN-1, false; i >= 0; i-- {
            if(data > 0) {
                if(data > uint64(pre[i])) {
                    data -= uint64(pre[i])
                    now[i] = 0
                } else {
                    now[i] = pre[i] - byte(data)
                    data = 0
                }
            } else if(flag == false) {
                if(pre[i] < 9) {
                    now[i] = pre[i] + byte(1)
                    flag = true
                } else {
                    now[i] = pre[i]
                }
            } else {
                now[i] = pre[i]
            }
        }
    }
    output(*now)
    now, pre = pre, now
}

func main() {
    var n uint64
    fmt.Fscan(reader, &n)
    pre, now = &number[0], &number[1]
    for i, presum := uint64(0), uint64(0); i < n; i++ {
        var data uint64
        fmt.Fscan(reader, &data)
        work(presum, data)
        presum = data
    }
}

package main

import "os"
import "fmt"
import "bufio"

var (
    reader = bufio.NewReader(os.Stdin)
)

func work(pre *uint64, presum, data uint64) {
    if(data > presum) {
        data -= presum
        var now uint64 = 0
        var tmp uint64 = *pre
        var s uint64 = 1
        for ; tmp > 0 || data > 0; {
            v := tmp%10
            tmp /= 10
            if(data > 9-v) {
                data -= 9-v
                v = 9
            } else {
                v += data
                data = 0
            }
            now += v*s
            s *= 10
        }
        *pre = now
        fmt.Println(now)
    } else {
        data = presum - data + 1
        var now uint64 = 0
        var tmp uint64 = *pre
        var s uint64 = 1
        for ; data > 0; {
            v := tmp%10
            tmp /= 10
            if(data > v) {
                data -= v
                v = 0
            } else {
                v -= data
                data = 0
            }
            now += v*s
            s *= 10
        }
        flag := false
        for ; flag == false || tmp > 0; {
            v := tmp%10
            tmp /= 10
            if(flag == false && v < 9) {
                v += 1
                flag = true
            }
            now += v*s
            s *= 10
        }
        *pre = now
        fmt.Println(now)
    }
}

func main() {
    var n uint64
    fmt.Fscan(reader, &n)
    for i, pre, presum := uint64(0), uint64(0), uint64(0); i < n; i++ {
        var data uint64
        fmt.Fscan(reader, &data)
        work(&pre, presum, data)
        presum = data
    }
}

package main

import "os"
import "fmt"
import "bufio"

var (
    reader = bufio.NewReader(os.Stdin)
)

func work(pre *uint64, presum, data uint64) {
    if(data > presum) {
        data -= presum
        var now uint64 = 0
        var tmp uint64 = *pre
        var s uint64 = 1
        for ; tmp > 0 || data > 0; {
            v := tmp%10
            tmp /= 10
            if(data > 9-v) {
                data -= 9-v
                v = 9
            } else {
                v += data
                data = 0
            }
            now += v*s
            s *= 10
        }
        *pre = now
        fmt.Println(now)
    } else {
        data = presum - data + 1
        var now uint64 = 0
        var tmp uint64 = *pre
        var s uint64 = 1
        for ; data > 0; {
            v := tmp%10
            tmp /= 10
            if(data > v) {
                data -= v
                v = 0
            } else {
                v -= data
                data = 0
            }
            now += v*s
            s *= 10
        }
        for ; true; {
            v := tmp%10
            tmp /= 10
            flag := false
            if(v < 9) {
                v += 1
                flag = true
            }
            now += v*s
            s *= 10
            if(flag == true) {
                break
            }
        }
        *pre = now
        fmt.Println(now)
    }
}

func main() {
    var n uint64
    fmt.Fscan(reader, &n)
    for i, pre, presum := uint64(0), uint64(0), uint64(0); i < n; i++ {
        var data uint64
        fmt.Fscan(reader, &data)
        work(&pre, presum, data)
        presum = data
    }
}


package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n := reader.NextInt64()
		pp := make([]int64, n)
		for i := int64(0); i < n; i++ {
			pp[i] = reader.NextInt64()
		}
		writer.Printf("%s\n", sol(pp))
	}
}

func sol(pp []int64) string {
	for i := 1; i < len(pp); i++ {
		if pp[i] > pp[i-1] && pp[i] != pp[i-1]+1 {
			return "No"
		}
	}
	return "Yes"
}

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

package main

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

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

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

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

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

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

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

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

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

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

var (
	t int

	n int
	P []int
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n = ReadInt()
		P = ReadIntSlice(n)

		solve()
	}
}

func solve() {
	for i := 0; i < n-1; i++ {
		if P[i+1]-P[i] > 1 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

// Author: sighduck
// URL: https://codeforces.com/contest/1340/problem/A

package main

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

func _Solve(n int, p []int, index []int, visited []bool, value int, valueIndex int) string {
	if value == n+1 {
		return "Yes"
	}
	vI := valueIndex
	if valueIndex == -1 {
		vI = index[value]
	}
	if p[vI] == value {
		visited[vI] = true
		if vI+1 < n && !visited[vI+1] {
			return _Solve(n, p, index, visited, value+1, vI+1)
		}
		return _Solve(n, p, index, visited, value+1, -1)
	}
	return "No"
}

func Solve(n int, p []int) string {
	index := make([]int, n+1)
	for i, elem := range p {
		index[elem] = i
	}
	visited := make([]bool, n)
	return _Solve(n, p, index, visited, 1, index[1])
}

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

	var t int
	fmt.Fscanf(reader, "%d\n", &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscanf(reader, "%d\n", &n)
		p := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(reader, "%d", &p[i])
		}
		fmt.Fscanf(reader, "\n")
		fmt.Fprintf(writer, "%s\n", Solve(n, p))
	}
}

package main

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

func main() {
	s := NewScanner()
	t := s.NextInt()

Next:
	for i := 0; i < t; i++ {
		n := s.NextInt()

		ar := make([]int, n)
		m := map[int]int{}
		for k := 0; k < n; k++ {
			ar[k] = s.NextInt()
			m[ar[k]] = k
		}

		for j := 1; j <= n-1; j++ {
			idx := m[j]
			if idx != n-1 && ar[idx] < ar[idx+1] && ar[idx+1]-ar[idx] != 1 {
				fmt.Println("No")
				continue Next
			}
		}

		fmt.Println("Yes")
	}
}

type scanner struct {
	*bufio.Scanner
}

func NewScanner() *scanner {
	s := bufio.NewScanner(os.Stdin)
	s.Split(bufio.ScanWords)
	return &scanner{s}
}

func (s *scanner) NextInt() int {
	s.Scan()
	i, _ := strconv.Atoi(s.Text())
	return i
}

func (s *scanner) NextInt64() int64 {
	s.Scan()
	i, _ := strconv.ParseInt(s.Text(), 10, 64)
	return i
}

func (s *scanner) NextString() string {
	s.Scan()
	return s.Text()
}

package main

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

func main() {
	rd := bufio.NewReader(os.Stdin)
	wr := bufio.NewWriter(os.Stdout)

	var t, n, i, j, k, l int
	var bo bool
	fmt.Fscanf(rd, "%d\n", &t)
	for i = 0; i < t; i++ {
		fmt.Fscanf(rd, "%d\n", &n)
		bo = true
		for j = 0; j < n; j++ {
			fmt.Fscanf(rd, "%d", &k)
			if j > 0 && bo {
				if k > l {
					if k != l+1 {
						fmt.Fprintf(wr, "No\n")
						bo = false
					}
				}
			}
			l = k
		}
		if bo {
			fmt.Fprintf(wr, "Yes\n")
		}
		fmt.Fscanf(rd, "\n")
	}

	wr.Flush()
}

package main

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

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

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

func scanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

var sc = newScanner()

func solve(a []int) bool {
	min, max := 1, 1
	var prev int
	for i := len(a) - 1; i >= 0; i-- {
		if prev != 0 {
			if a[i] == prev-1 {
				if a[i] == min {
					min = max + 1
					prev = 0
				} else {
					prev--
				}
			} else {
				return false
			}
		} else {
			if a[i] == min {
				min++
			} else {
				prev, max = a[i], a[i]
			}
		}
	}
	return true
}

func main() {
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	for t := scanInt(); t > 0; t-- {
		n := scanInt()
		a := scanInts(n)
		if solve(a) {
			fmt.Fprintln(w, "Yes")
		} else {
			fmt.Fprintln(w, "No")
		}
	}
}

package main

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

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

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

func scanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

var sc = newScanner()

func solve(a []int) bool {
	min, max := 1, 1
	var prev int
	for i := len(a) - 1; i >= 0; i-- {
		if prev != 0 {
			if a[i] == prev-1 {
				if a[i] == min {
					min = max + 1
					prev = 0
				} else {
					prev--
				}
			} else {
				return false
			}
		} else {
			if a[i] == min {
				min = max + 1
				prev = 0
			} else {
				prev, max = a[i], a[i]
			}
		}
	}
	return true
}

func main() {
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	for t := scanInt(); t > 0; t-- {
		n := scanInt()
		a := scanInts(n)
		if solve(a) {
			fmt.Fprintln(w, "Yes")
		} else {
			fmt.Fprintln(w, "No")
		}
	}
}

package main

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

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

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

func scanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

var sc = newScanner()

func solve(a []int) bool {
	min := 1
	var max, prev int
	for i := len(a) - 1; i >= 0; i-- {
		if a[i] == min {
			min++
			prev = 0
			continue
		}
		if prev == 0 {
			prev, max = a[i], a[i]
			continue
		}
		if a[i] == prev-1 {
			prev--
			if prev == min {
				min = max + 1
				prev = 0
			}
		} else {
			return false
		}
	}
	return true
}

func main() {
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	for t := scanInt(); t > 0; t-- {
		n := scanInt()
		a := scanInts(n)
		if solve(a) {
			fmt.Fprintln(w, "Yes")
		} else {
			fmt.Fprintln(w, "No")
		}
	}
}

package main

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

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

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

func scanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

var sc = newScanner()

func solve(a []int) bool {
	min := 1
	var prev int
	for i := len(a) - 1; i >= 0; i-- {
		if a[i] == min {
			min++
			prev = 0
			continue
		}
		if prev == 0 {
			prev = a[i]
		} else {
			if a[i] == prev-1 {
				prev--
				if prev == min {
					prev = 0
				}
			} else {
				return false
			}
		}
	}
	return true
}

func main() {
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	for t := scanInt(); t > 0; t-- {
		n := scanInt()
		a := scanInts(n)
		if solve(a) {
			fmt.Fprintln(w, "Yes")
		} else {
			fmt.Fprintln(w, "No")
		}
	}
}


package main

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

/* solution */

func solve() {

	q := readInt()

	for i := 0; i < q; i++ {
		solveSingle()
	}

}

func solveSingle() {

	n := readInt()

	a, b := -1, -1
	for i := 0; i < n; i++ {
		v := readInt()
		if v >= a {
			b = a
			a = v
		} else if v > b {
			b = v
		}
	}

	if b-1 <= n-2 {
		printInt(b - 1)
	} else if n-2 >= 0 {
		printInt(n - 2)
	} else {
		printInt(0)
	}

}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

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

	reader = bufio.NewScanner(f)
	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func print(s string) {
	writer.WriteString(s)
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

package main

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

func main() {
	var n, q int
	var st string

	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &q)

	for i := 0; i < q; i++ {
		fmt.Fscanln(scr, &n)

		a := make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscanf(scr, "%d", &a[j])
		}
		fmt.Fscanln(scr, &st)

		sort.Ints(a)

		if len(a)-2 <= a[len(a)-2]-1 {
			fmt.Println(len(a) - 2)
		} else {
			fmt.Println(a[len(a)-2] - 1)
		}
	}

}

package main

import (
	"fmt"
	"sort"
)

func ReadN(all []int, i, n int) {
	if n == 0 {
		return
	}
	if m, err := Scan(&all[i]); m != 1 {
		panic(err)
	}
	ReadN(all, i+1, n-1)
}

func Scan(a *int) (int, error) {
	return fmt.Scan(a)
}

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

func main()  {
	var requests int
	Scan(&requests)
	for j:=0;j < requests ;j++ {
		var ledCount int
		Scan(&ledCount)
		ledges := make([]int, ledCount)
		ReadN(ledges, 0, ledCount)
		sort.Ints(ledges[:])

		fmt.Printf("%d\n", min(ledges[ledCount - 2] - 1, ledCount - 2))
	}
}

//1
//4
//1 3 1 3

//HOWDY! IT'S ME! A HARD BLACKISH DICK MOVE!
package main

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

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

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

//str := PrintlnInts(X...)

/*******************************************************************/
func max2(a []int) (int, int) {
	max1, max2 := 0, 0
	for _, v := range a {
		if v >= max2 {
			max1, max2 = max2, v
		} else if v > max1 {
			max1 = v
		}
	}
	return max1, max2
}

func main() {
	for t := ReadInt(); t > 0; t-- {
		n := ReadInt()
		a := ReadIntSlice(n)
		m1, _ := max2(a)
		fmt.Println(min(m1-1, n-2))
	}
}

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

func min(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	min := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] < min {
			min = args[i]
		}
	}
	return min
}

func max(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

func _gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return _gcd(b, a%b)
}

func gcd(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	gcd := args[0]
	for i := 1; i < len(args); i++ {
		gcd = _gcd(gcd, args[i])
	}
	return gcd
}

/*********** 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+9))
	// 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 readInt()
}
func ReadInt2() (int, int) {
	return readInt(), readInt()
}
func ReadInt3() (int, int, int) {
	return readInt(), readInt(), readInt()
}
func ReadInt4() (int, int, int, int) {
	return readInt(), readInt(), readInt(), readInt()
}

func readInt_64() int64 {
	return readIntNbits(64)
}

func ReadInt2_64() (int64, int64) {
	return readInt_64(), readInt_64()
}

func ReadInt3_64() (int64, int64, int64) {
	return readInt_64(), readInt_64(), readInt_64()
}

func readInt() int {
	return int(readIntNbits(32))
}

func readIntNbits(n int) int64 {
	i, err := strconv.ParseInt(ReadString(), 0, n)
	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
}

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

// PrintIntsLine returns integers string delimited by a space.
func PrintlnInts(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)
}

package main

import (
 "fmt"
 "sort"
)

func main() {

 var testCase int

 if _, err := fmt.Scan(&testCase); err != nil {
 }

 for testCase > 0 {
  testCase -= 1
  var plankNum int
  if _, err := fmt.Scan(&plankNum); err != nil {
  }

  planks := make([]int, plankNum)
  for i := 0; i < plankNum; i += 1 {
   if _, err := fmt.Scan(&planks[i]); err != nil {
   }
  }

  if plankNum < 3 {
   fmt.Println(0)
   continue
  }

  sort.Ints(planks)
  m := planks[plankNum-2]

  if m-1 < plankNum-2 {

  if m - 1 < 0 {
    m = 1
  }
   fmt.Println(m - 1)
  } else {

   if plankNum - 2 < 0 {
    plankNum = 2
   }
   fmt.Println(plankNum - 2)
  }
 }
}

package main

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

func main() {

	//stdin, err := os.Open("test.txt")
	//if err != nil {
	///	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("test.txt")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)

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

	for i := 0; i < q; i++ {
		var n int
		fmt.Fscanf(reader, "%d\n", &n)
		a := make([]int, n, n)
		for j := 0; j < n; j++ {
			fmt.Fscanf(reader, "%d", &a[j])
		}
		fmt.Fscanf(reader, "\n")
		sort.Ints(a)
		fmt.Fprintf(writer, "%d\n", int(math.Min(float64(n-2), math.Min(float64(a[n-1]-1), float64(a[n-2]-1)))))
	}

	writer.Flush()
}

// Author: sighduck
// URL: https://codeforces.com/contest/1197/problem/A

package main

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

func Solve(n int, a []int) int {
	if n == 2 {
		return 0
	}
	sort.Ints(a)
	baseK := a[n-2] - 1
	stepK := n - 2
	if stepK < baseK {
		return stepK
	}
	return baseK
}

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

	var t int
	fmt.Fscanf(reader, "%d\n", &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscanf(reader, "%d\n", &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(reader, "%d", &a[i])
		}
		fmt.Fscanf(reader, "\n")
		fmt.Fprintf(writer, "%d\n", Solve(n, a))
	}
}

package main

import (
	"fmt"
	"sort"
)

func ReadN(all []int, i, n int) {
	if n == 0 {
		return
	}
	if m, err := Scan(&all[i]); m != 1 {
		panic(err)
	}
	ReadN(all, i+1, n-1)
}

func Scan(a *int) (int, error) {
	return fmt.Scan(a)
}

func main()  {
	var requests int
	Scan(&requests)
	for j:=0;j < requests ;j++ {
		var ledCount int
		Scan(&ledCount)
		if ledCount < 3 {
			fmt.Printf("0\n")
			return
		}

		ledges := make([]int, ledCount)
		ReadN(ledges, 0, ledCount)
		sort.Ints(ledges[:])
		//fmt.Println(ledges)

		var optimalLedge int
		if ledges[ledCount - 1] < ledges[ledCount - 2] {
			optimalLedge = ledges[ledCount - 1]
		} else {
			optimalLedge = ledges[ledCount - 2]
		}
		//fmt.Println(optimalLedge)

		if optimalLedge - (ledCount - 2) > 0 {
			fmt.Printf("%d\n",ledCount - 2)
		} else {
			fmt.Printf("%d\n",optimalLedge - 1)
		}
	}
}

//1
//4
//1 3 1 3

package main

import (
 "fmt"
 "sort"
)

func main() {

 var testCase int

 if _, err := fmt.Scanln(&testCase); err != nil {
 }

 for testCase > 0 {
  testCase -= 1
  var plankNum int
  if _, err := fmt.Scanln(&plankNum); err != nil {
  }

  planks := make([]int, plankNum)
  for i := 0; i < plankNum; i += 1 {
   if _, err := fmt.Scan(&planks[i]); err != nil {
   }
  }

  if plankNum < 3 {
   fmt.Println(0)
   continue
  }

  sort.Ints(planks)
  m := planks[plankNum-2]

  if m-1 < plankNum-2 {

  if m - 1 < 0 {
    m = 1
  }
   fmt.Println(m - 1)
  } else {

   if plankNum - 2 < 0 {
    plankNum = 2
   }
   fmt.Println(plankNum - 2)
  }
 }
}


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 (
	"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,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,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++
				}
			}
		}
	}
	fmt.Print(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, 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*/


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 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"
	"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 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はとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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


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

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