Petya is preparing for his birthday. He decided that there would be $$$n$$$ different dishes on the dinner table, numbered from $$$1$$$ to $$$n$$$. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from $$$n$$$ different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it:  the dish will be delivered by a courier from the restaurant $$$i$$$, in this case the courier will arrive in $$$a_i$$$ minutes,  Petya goes to the restaurant $$$i$$$ on his own and picks up the dish, he will spend $$$b_i$$$ minutes on this. Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.For example, if Petya wants to order $$$n = 4$$$ dishes and $$$a = [3, 7, 4, 5]$$$, and $$$b = [2, 1, 2, 4]$$$, then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in $$$3$$$ minutes, the courier of the fourth restaurant will bring the order in $$$5$$$ minutes, and Petya will pick up the remaining dishes in $$$1 + 2 = 3$$$ minutes. Thus, in $$$5$$$ minutes all the dishes will be at Petya's house.Find the minimum time after which all the dishes can be at Petya's home.

The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of dishes that Petya wants to order. The second line of each test case contains $$$n$$$ integers $$$a_1 \ldots a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the time of courier delivery of the dish with the number $$$i$$$. The third line of each test case contains $$$n$$$ integers $$$b_1 \ldots b_n$$$ ($$$1 \le b_i \le 10^9$$$) — the time during which Petya will pick up the dish with the number $$$i$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output one integer — the minimum time after which all dishes can be at Petya's home.

/*
URL:
https://codeforces.com/contest/1443/problem/C
*/

package main

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

var (
	t int

	n int
	A []int64
	B []int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for tc := 0; tc < t; tc++ {
		n = readi()
		A, B = readlls(n), readlls(n)

		solve()
	}
}

func solve() {
	S := []Store{}
	for i := 0; i < n; i++ {
		a, b := A[i], B[i]
		S = append(S, Store{a: a, b: b})
	}

	sort.Slice(S, func(i, j int) bool {
		if S[i].a < S[j].a {
			return true
		} else if S[i].a > S[j].a {
			return false
		} else {
			return S[i].b > S[j].b
		}
	})

	revB := []int64{}
	for i := n - 1; i >= 0; i-- {
		revB = append(revB, S[i].b)
	}

	bs := make([]int64, n+1)
	for i := 0; i < n; i++ {
		bs[i+1] = bs[i] + revB[i]
	}

	ans := Max(A...)
	ChMin(&ans, bs[n])
	for i := 0; i < n; i++ {
		deli := S[i].a
		walk := bs[n-(i+1)]
		val := Max(deli, walk)

		ChMin(&ans, val)
	}

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

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

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

type Store struct {
	a, b int64
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

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

// mod can calculate a right residual whether value is positive or negative.
func mod(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

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

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

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

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

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

	return s
}

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

// pow is integer version of math.Pow
// pow calculate a power by Binary Power (二分累乗法(O(log e))).
func pow(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 := pow(a, halfE)
		return half * half
	}

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

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  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()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

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

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

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

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

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

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

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

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

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

package main

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

func solve() {
	t := readInt()
	for i := 0; i < t; i++ {
		solveSingle()
	}
}

func solveSingle() {
	n := readInt()
	a := readIntArray(n)
	b := readIntArray(n)
	lo := 0
	hi := 1_000_000_001
	ans := hi
	for lo <= hi {
		mi := (lo + hi) / 2
		if ok(a, b, mi) {
			ans = min(ans, mi)
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}
	fmt.Println(ans)
}

func ok(a []int, b []int, t int) bool {
	cost := 0
	for i := 0; i < len(a); i++ {
		if a[i] > t {
			cost += b[i]
			if cost > t {
				return false
			}
		}
	}
	return cost <= t
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

func solve() {
	t := readInt()
	for i := 0; i < t; i++ {
		solveSingle()
	}
}

func solveSingle() {
	n := readInt()
	a := readInt64Array(n)
	b := readInt64Array(n)
	id := make([]int, n)
	for i := 0; i < n; i++ {
		id[i] = i
	}
	sort.Slice(id, func(i, j int) bool {
		return a[id[i]] < a[id[j]]
	})
	sum := make([]int64, n + 2)
	sum[n] = 0
	for i := n-1; i >= 0; i-- {
		sum[i] = sum[i+1]+b[id[i]]
	}
	ans := sum[0]
	for i := 0; i < n; i++ {
		ans = min(ans, max(sum[i+1], a[id[i]]))
	}
	fmt.Println(ans)
}

//func sol2(ans int, a []int, b []int) {
//	lo := 0
//	hi := 1_000_000_001
//	ans = hi
//	for lo <= hi {
//		mi := (lo + hi) / 2
//		if ok(a, b, mi) {
//			ans = min(ans, mi)
//			hi = mi - 1
//		} else {
//			lo = mi + 1
//		}
//	}
//	fmt.Println(ans)
//}
//
//func ok(a []int, b []int, t int) bool {
//	cost := 0
//	for i := 0; i < len(a); i++ {
//		if a[i] > t {
//			cost += b[i]
//			if cost > t {
//				return false
//			}
//		}
//	}
//	return cost <= t
//}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

type pair struct {
	a int
	b int
}

func main() {
	//rd, _ := os.Open("input")
	//in := bufio.NewReader(rd)
	in := bufio.NewReader(os.Stdin)

	var t, n int
	var p []pair
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		p = make([]pair, n)
		for i := range p {
			fmt.Fscan(in, &p[i].a)
		}
		for i := range p {
			fmt.Fscan(in, &p[i].b)
		}
		sort.Slice(p, func(i, j int) bool {
			return p[i].a > p[j].a || p[i].a == p[j].a && p[i].b > p[j].b
		})
		p = append(p, pair{0, 0})
		waitingTime := p[0].a
		walkingTime := 0
		for i := 0; i < len(p)-1; i++ {
			if walkingTime+p[i].b >= p[i].a {
				break
			}
			walkingTime += p[i].b
			waitingTime = p[i+1].a
		}
		fmt.Println(int(math.Max(float64(waitingTime), float64(walkingTime))))
	}
}

package main

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

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

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

type price struct {
	a, b 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 t int
	scanf("%d\n", &t)
	for {
		if t == 0 {
			break
		}
		t--

		var n int
		scanf("%d\n", &n)

		var c = make([]price, n)

		for i := 0; i < n; i++ {
			var a int64
			scanf("%d", &a)
			c[i].a = a
		}
		scanf("\n")

		for i := 0; i < n; i++ {
			var b int64
			scanf("%d", &b)
			c[i].b = b
		}
		scanf("\n")

		sort.SliceStable(c, func(i, j int) bool {
			return c[i].a <= c[j].a
		})

		var s = make([]int64, len(c))

		for i := 0; i < n; i++ {
			if i == 0 {
				s[0] = c[0].b
				continue
			}
			s[i] = s[i-1] + c[i].b
		}

		var res = min(s[len(s)-1], c[len(c)-1].a)

		for i := 1; i < n; i++ {
			res = min(max(c[i-1].a, s[len(s)-1]-s[i-1]), res)
		}

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

package main

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

func solve() {
	t := readInt()
	for i := 0; i < t; i++ {
		solveSingle()
	}
}

func solveSingle() {
	n := readInt()
	a := readIntArray(n)
	b := readIntArray(n)
	id := make([]int, n)
	for i := 0; i < n; i++ {
		id[i] = i
	}
	sort.Slice(id, func(i, j int) bool {
		return a[id[i]] < a[id[j]]
	})
	sum := make([]int, n + 2)
	sum[n] = 0
	for i := n-1; i >= 0; i-- {
		sum[i] = sum[i+1]+b[id[i]]
	}
	ans := sum[0]
	for i := 0; i < n; i++ {
		ans = min(ans, max(sum[i+1], a[id[i]]))
	}
	fmt.Println(ans)
}

func sol2(ans int, a []int, b []int) {
	lo := 0
	hi := 1_000_000_001
	ans = hi
	for lo <= hi {
		mi := (lo + hi) / 2
		if ok(a, b, mi) {
			ans = min(ans, mi)
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}
	fmt.Println(ans)
}

func ok(a []int, b []int, t int) bool {
	cost := 0
	for i := 0; i < len(a); i++ {
		if a[i] > t {
			cost += b[i]
			if cost > t {
				return false
			}
		}
	}
	return cost <= t
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

func solve() {
	t := readInt()
	for i := 0; i < t; i++ {
		solveSingle()
	}
}

func solveSingle() {
	n := readInt()
	a := readInt64Array(n)
	b := readInt64Array(n)
	costY0 := b[0]
	costY1 := int64(0)
	costD0 := int64(0)
	costD1 := a[0]
	for i := 1; i < n; i++ {
		var newCostY0 int64
		var newCostY1 int64
		if max(b[i]+costY0, costY1) < max(b[i]+costD0, costD1) {
			newCostY0 = b[i] + costY0
			newCostY1 = costY1
		} else {
			newCostY0 = b[i] + costD0
			newCostY1 = costD1
		}
		var newCostD0 int64
		var newCostD1 int64
		if max(costY0, max(a[i], costY0)) < max(costD0, max(a[i],costD1)) {
			newCostD0 = costY0
			newCostD1 = max(a[i], costY1)
		} else {
			newCostD0 = costD0
			newCostD1 = max(a[i], costD1)
		}
		costY0 = newCostY0
		costY1 = newCostY1
		costD0 = newCostD0
		costD1 = newCostD1
	}
	fmt.Println(min(max(costY0, costY1), max(costD0, costD1)))
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

func solve() {
	t := readInt()
	for i := 0; i < t; i++ {
		solveSingle()
	}
}

func solveSingle() {
	n := readInt()
	a := readInt64Array(n)
	b := readInt64Array(n)
	ab := make([][2]int64, n)
	for i := 0; i < n; i++ {
		ab[i][0] = a[i]
		ab[i][1] = b[i]
	}
	sort.Slice(ab, func(i, j int) bool {
		return ab[i][0] < ab[j][0]
	})
	bestAns := int64(math.MaxInt64)
	sort.Search(len(ab), func(i int) bool {
		ans := int64(math.MaxInt64)
		v := ab[i][0]
		cost := int64(0)
		cost1Max := int64(0)
		for j := 0; j < n; j++ {
			if ab[j][0] > v {
				cost += ab[j][1]
			} else {
				cost1Max = max(cost1Max, ab[j][0])
			}
		}
		ans = min(ans, max(cost, cost1Max))

		cost2 := int64(0)
		cost2Max := int64(0)
		for j := 0; j < n; j++ {
			if ab[j][0] >= v {
				cost2 += ab[j][1]
			} else {
				cost2Max = max(cost2Max, ab[j][0])
			}
		}
		ans = min(ans, max(cost2, cost2Max))

		//fmt.Println(v, ans)
		cont := ans >= bestAns
		bestAns = min(bestAns, ans)
		//fmt.Println("i", i, ans, bestAns, cont)
		return cont
	})
	fmt.Println(bestAns)
}

func solveSingleBak() {
	n := readInt()
	a := readInt64Array(n)
	b := readInt64Array(n)
	costY0 := b[0]
	costY1 := int64(0)
	costD0 := int64(0)
	costD1 := a[0]
	for i := 1; i < n; i++ {
		var newCostY0 int64
		var newCostY1 int64
		if max(b[i]+costY0, costY1) < max(b[i]+costD0, costD1) {
			newCostY0 = b[i] + costY0
			newCostY1 = costY1
		} else {
			newCostY0 = b[i] + costD0
			newCostY1 = costD1
		}
		var newCostD0 int64
		var newCostD1 int64
		if max(costY0, max(a[i], costY0)) < max(costD0, max(a[i], costD1)) {
			newCostD0 = costY0
			newCostD1 = max(a[i], costY1)
		} else {
			newCostD0 = costD0
			newCostD1 = max(a[i], costD1)
		}
		costY0 = newCostY0
		costY1 = newCostY1
		costD0 = newCostD0
		costD1 = newCostD1
	}
	fmt.Println(min(max(costY0, costY1), max(costD0, costD1)))
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

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

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

type price struct {
	a, b 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 t int
	scanf("%d\n", &t)
	for {
		if t == 0 {
			break
		}
		t--

		var n int
		scanf("%d\n", &n)

		var c = make([]price, n)

		for i := 0; i < n; i++ {
			var a int
			scanf("%d", &a)
			c[i].a = a
		}
		scanf("\n")

		for i := 0; i < n; i++ {
			var b int
			scanf("%d", &b)
			c[i].b = b
		}
		scanf("\n")

		sort.SliceStable(c, func(i, j int) bool {
			return c[i].a <= c[j].a
		})

		var s = make([]int, len(c))

		for i := 0; i < n; i++ {
			if i == 0 {
				s[0] = c[0].b
				continue
			}
			s[i] = s[i-1] + c[i].b
		}

		var res = min(s[len(s)-1], c[len(c)-1].a)

		for i := 1; i < n; i++ {
			res = min(max(c[i-1].a, s[len(s)-1]-s[i-1]), res)
		}

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


You are given a string s. Each pair of numbers l and r that fulfill the condition 1 ≤ l ≤ r ≤ |s|, correspond to a substring of the string s, starting in the position l and ending in the position r (inclusive).Let's define the function of two strings F(x, y) like this. We'll find a list of such pairs of numbers for which the corresponding substrings of string x are equal to string y. Let's sort this list of pairs according to the pair's first number's increasing. The value of function F(x, y) equals the number of non-empty continuous sequences in the list.For example: F(babbabbababbab, babb) = 6. The list of pairs is as follows:(1, 4), (4, 7), (9, 12)Its continuous sequences are:   (1, 4)  (4, 7)  (9, 12)  (1, 4), (4, 7)  (4, 7), (9, 12)  (1, 4), (4, 7), (9, 12) Your task is to calculate for the given string s the sum F(s, x) for all x, that x belongs to the set of all substrings of a string s.

The only line contains the given string s, consisting only of small Latin letters (1 ≤ |s| ≤ 105).

Print the single number — the sought sum. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

NoteIn the first sample the function values at x equal to "a", "aa", "aaa" and "aaaa" equal 10, 6, 3 and 1 correspondingly.In the second sample for any satisfying x the function value is 1.

package main

import (
	"bufio"
	. "fmt"
	"index/suffixarray"
	"io"
	"os"
	"reflect"
	"unsafe"
)

// github.com/EndlessCheng/codeforces-go
func CF123D(_r io.Reader, out io.Writer) {
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}
	var s []byte
	Fscan(bufio.NewReader(_r), &s)
	n := len(s)
	sa := *(*[]int32)(unsafe.Pointer(reflect.ValueOf(suffixarray.New(s)).Elem().FieldByName("sa").Field(0).UnsafeAddr()))
	rank := make([]int, n)
	for i := range rank {
		rank[sa[i]] = i
	}
	height := make([]int, n+1)
	h := 0
	for i, ri := range rank {
		if h > 0 {
			h--
		}
		if ri > 0 {
			for j := int(sa[ri-1]); i+h < n && j+h < n && s[i+h] == s[j+h]; h++ {
			}
		}
		height[ri] = h
	}

	type pair struct{ v, i int }
	pl := make([]int, n+1)
	st := []pair{{-1, 0}}
	for i, v := range height {
		for {
			if top := st[len(st)-1]; top.v < v {
				pl[i] = top.i
				break
			}
			st = st[:len(st)-1]
		}
		st = append(st, pair{v, i})
	}
	pr := make([]int, n+1)
	st = []pair{{-1, n}}
	for i := n - 1; i >= 0; i-- {
		v := height[i]
		for {
			if top := st[len(st)-1]; top.v < v {
				pr[i] = top.i
				break
			}
			st = st[:len(st)-1]
		}
		st = append(st, pair{v, i})
	}

	ans := int64(n) * int64(n+1) / 2
	usedSt := []int{0}
	for i, v := range height {
		for v < usedSt[len(usedSt)-1] {
			usedSt = usedSt[:len(usedSt)-1]
		}
		if v == usedSt[len(usedSt)-1] {
			continue
		}
		usedSt = append(usedSt, v)
		l, r := pl[i], pr[i]
		h, w := int64(v-max(height[l], height[r])), int64(r-l)
		ans += h * w * (w - 1) / 2
	}
	Fprint(out, ans)
}

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

package main

import (
	"bufio"
	. "fmt"
	"index/suffixarray"
	"os"
	"reflect"
	"unsafe"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}
	var s []byte
	Fscan(bufio.NewReader(os.Stdin), &s)
	n := len(s)
	sa := *(*[]int32)(unsafe.Pointer(reflect.ValueOf(suffixarray.New(s)).Elem().FieldByName("sa").Field(0).UnsafeAddr()))
	rank := make([]int, n)
	for i := range rank {
		rank[sa[i]] = i
	}
	height := make([]int, n+1)
	h := 0
	for i, ri := range rank {
		if h > 0 {
			h--
		}
		if ri > 0 {
			for j := int(sa[ri-1]); i+h < n && j+h < n && s[i+h] == s[j+h]; h++ {
			}
		}
		height[ri] = h
	}

	type pair struct{ v, i int }
	pl := make([]int, n+1)
	st := []pair{{-1, 0}}
	for i, v := range height {
		for {
			if top := st[len(st)-1]; top.v < v {
				pl[i] = top.i
				break
			}
			st = st[:len(st)-1]
		}
		st = append(st, pair{v, i})
	}
	pr := make([]int, n+1)
	st = []pair{{-1, n}}
	for i := n - 1; i >= 0; i-- {
		v := height[i]
		for {
			if top := st[len(st)-1]; top.v < v {
				pr[i] = top.i
				break
			}
			st = st[:len(st)-1]
		}
		st = append(st, pair{v, i})
	}

	ans := int64(n) * int64(n+1) / 2
	usedSt := []int{0}
	for i, v := range height {
		for v < usedSt[len(usedSt)-1] {
			usedSt = usedSt[:len(usedSt)-1]
		}
		if v == usedSt[len(usedSt)-1] {
			continue
		}
		usedSt = append(usedSt, v)
		l, r := pl[i], pr[i]
		h, w := int64(v-max(height[l], height[r])), int64(r-l)
		ans += h * w * (w - 1) / 2
	}
	Print(ans)
}


Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.

The first line of input contains three integers n, m and q (2 ≤ n ≤ 105, 1 ≤ m, q ≤ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations. The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary. Then m lines follow, each of them contains an integer t (1 ≤ t ≤ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi. Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered. All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.

First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes). After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3. See the samples for better understanding.

3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like

8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou

package main

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

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

	var n, m, q, d int
	var x, y string
	Fscan(in, &n, &m, &q)
	fa := make([]int, n)
	dis := make([]int, n)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			ffx := find(fa[x])
			dis[x] += dis[fa[x]]
			fa[x] = ffx
		}
		return fa[x]
	}
	delta := func(x, y int) int { return ((dis[x]-dis[y])%2 + 2) % 2 }
	merge := func(from, to int, d int) bool {
		if fFrom, fTo := find(from), find(to); fFrom != fTo {
			dis[fFrom] = d + dis[to] - dis[from]
			fa[fFrom] = fTo
			return true
		}
		return delta(from, to) == d
	}
	same := func(x, y int) bool { return find(x) == find(y) }

	id := make(map[string]int, n)
	for ; n > 0; n-- {
		Fscan(in, &x)
		id[x] = len(id)
	}
	for ; m > 0; m-- {
		Fscan(in, &d, &x, &y)
		if merge(id[x], id[y], d-1) {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}
	for ; q > 0; q-- {
		Fscan(in, &x, &y)
		if a, b := id[x], id[y]; same(a, b) {
			Fprintln(out, delta(a, b)+1)
		} else {
			Fprintln(out, 3)
		}
	}
}

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

package main

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

var stdReader = bufio.NewReader(os.Stdin)

func readToken() string {
	var char byte
	var err error
	for {
		char, err = stdReader.ReadByte()
		if err == io.EOF {
			return ""
		}
		if err != nil {
			panic(err)
		}
		if !unicode.IsSpace(rune(char)) {
			break
		}
	}
	bytes := []byte{char}
	for {
		char, err := stdReader.ReadByte()
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
		if unicode.IsSpace(rune(char)) {
			break
		}
		bytes = append(bytes, char)
	}
	return string(bytes)
}

func readInt() int {
	i, err := strconv.Atoi(readToken())
	if err != nil {
		panic(err)
	}
	return i
}

var dsu []int

func group(i int) int {
	if dsu[i] == i {
		return i
	}
	dsu[i] = group(dsu[i])
	return dsu[i]
}

var op []int

func opposite(i int) int {
	if op[i] < 0 {
		return -1
	}
	return group(op[i])
}

func relate(ga, gb int) int {
	switch {
	case ga == gb:
		return 1
	case opposite(ga) == gb:
		return 2
	default:
		return 3
	}
}

func unite(ga, gb int) {
	dsu[gb] = ga
}

func main() {
	n, r, q := readInt(), readInt(), readInt()
	en := make(map[string]int)
	for i := 0; i < n; i++ {
		en[readToken()] = i
	}

	dsu = make([]int, n)
	for i := range dsu {
		dsu[i] = i
	}
	op = make([]int, n)
	for i := range op {
		op[i] = -1
	}

	for i := 0; i < r; i++ {
		j := readInt()
		ga, gb := group(en[readToken()]), group(en[readToken()])
		rel := relate(ga, gb)
		if j == 1 {
			if rel == 2 {
				fmt.Println("NO")
			} else {
				if opposite(ga) >= 0 && opposite(gb) >= 0 {
					unite(opposite(ga), opposite(gb))
				} else if opposite(ga) >= 0 {
					op[gb] = opposite(ga)
				} else if opposite(gb) >= 0 {
					op[ga] = opposite(gb)
				}
				unite(ga, gb)
				pos := group(ga)
				if neg := opposite(pos); neg >= 0 {
					op[pos] = neg
					op[neg] = pos
				}
				fmt.Println("YES")
			}
		} else {
			if rel == 1 {
				fmt.Println("NO")
			} else {
				switch {
				case opposite(ga) >= 0 && opposite(gb) >= 0:
					unite(ga, opposite(gb))
					unite(opposite(ga), gb)
				case opposite(ga) >= 0:
					unite(opposite(ga), gb)
				case opposite(gb) >= 0:
					unite(ga, opposite(gb))
				}
				op[group(ga)] = group(gb)
				op[group(gb)] = group(ga)
				fmt.Println("YES")
			}
		}
	}

	for i := 0; i < q; i++ {
		fmt.Println(relate(group(en[readToken()]), group(en[readToken()])))
	}
}


Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing $$$N$$$ gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves:  Take one gold coin from the chest.  Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even. Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.

The first line contains a single integer $$$T$$$ $$$(1 \le T \le 10^5)$$$ denotes the number of test cases. The next $$$T$$$ lines each contain a single integer $$$N$$$ $$$(1 \le N \le 10^{18})$$$.

$$$T$$$ lines, each line is the answer requested by Mr. Chanek.

NoteFor the first case, the game is as follows:   Mr. Chanek takes one coin.  The opponent takes two coins.  Mr. Chanek takes one coin.  The opponent takes one coin. For the second case, the game is as follows:   Mr. Chanek takes three coins.  The opponent takes one coin.  Mr. Chanek takes one coin.  The opponent takes one coin.

package main

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

/*
2
5
6

2
4
*/

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

	var T, R int
	var target []int
	max := 0
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		if max < R {
			max = R
		}
		target = append(target, R)
	}

	var A = make(map[int]int)
	A[0] = 0
	for i := 1; i <= max; i++ {
		if i%2 != 0 {
			A[i] = i - A[i-1]
		} else {
			A[i] = i - A[i/2]
		}
	}

	for _, t := range target {
		Fprintln(out, A[t])
	}
}

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

	var T, R int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		var total int64
		get := true
		for R > 0 {
			if R == 4 {
				if get {
					total += 3
				} else {
					total += 1
				}
				R = 0
			} else if R%2 == 0 {
				if (R/2)%2 != 0 {
					if get {
						total += R / 2
					}
					R = R / 2
				} else {
					if get {
						total += 1
					}
					R = R - 1
				}
			} else {
				if get {
					total += 1
				}
				R = R - 1
			}
			get = !get
		}
		Fprintln(out, total)
	}

}

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

package main

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

/*
2
5
6

2
4
*/

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

	var T, R int
	var target []int
	max := 0
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		if max < R {
			max = R
		}
		target = append(target, R)
	}

	var A = make(map[int]int)
	A[0] = 0
	for i := 1; i <= max; i++ {
		if i%2 != 0 {
			A[i] = i - A[i-1]
		} else {
			A[i] = i - A[i/2]
		}
	}

	for _, t := range target {
		Fprintln(out, A[t])
	}
}

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

	var T, R int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		var f int

		for R > 0 {
			if R == 4 {
				f += 3
				R = 0
			} else if R%2 == 0 && (R/2)%2 == 0 {
				f += R / 2
				R = (R / 2) - 1
			} else {
				f += 1
				R -= 2
			}
		}
		Fprintln(out, f)
	}

}

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

package main

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

/*
2
5
6

2
4
*/

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

	var T, R int
	var target []int
	max := 0
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		if max < R {
			max = R
		}
		target = append(target, R)
	}

	var A = make(map[int]int)
	A[0] = 0
	for i := 1; i <= max; i++ {
		if i%2 != 0 {
			A[i] = i - A[i-1]
		} else {
			A[i] = i - A[i/2]
		}
	}

	for _, t := range target {
		Fprintln(out, A[t])
	}
}

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

	var T, R int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		var total int
		get := true
		for R > 0 {
			if R%2 == 0 {
				if get {
					total += R / 2
				}
				R = R / 2
			} else {
				if get {
					total += 1
				}
				R = R - 1
			}
			get = !get
		}
		Fprintln(out, total)
	}

}

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

package main

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

/*
2
5
6

2
4
*/

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

	var T, R int
	var target []int
	max := 0
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		if max < R {
			max = R
		}
		target = append(target, R)
	}

	var A = make(map[int]int)
	A[0] = 0
	for i := 1; i <= max; i++ {
		if i%2 != 0 {
			A[i] = i - A[i-1]
		} else {
			A[i] = i - A[i/2]
		}
	}

	for _, t := range target {
		Fprintln(out, A[t])
	}
}

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

	var T, R int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		var total int
		get := true
		for R > 0 {
			if R == 4 {
				if get {
					total += 3
				} else {
					total += 1
				}
				R = 0
			} else if R%2 == 0 {
				if (R/2)%2 != 0 {
					if get {
						total += R / 2
					}
					R = R / 2
				} else {
					if get {
						total += 1
					}
					R = R - 1
				}
			} else {
				if get {
					total += 1
				}
				R = R - 1
			}
			get = !get
		}
		Fprintln(out, total)
	}

}

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

package main

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

/*
2
5
6

2
4
*/

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

	var T, R int
	var target []int
	max := 0
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		if max < R {
			max = R
		}
		target = append(target, R)
	}

	var A = make(map[int]int)
	A[0] = 0
	for i := 1; i <= max; i++ {
		if i%2 != 0 {
			A[i] = i - A[i-1]
		} else {
			A[i] = i - A[i/2]
		}
	}

	for _, t := range target {
		Fprintln(out, A[t])
	}
}

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

	var T, R int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &R)
		var total int
		get := true
		for R > 0 {
			if R%2 == 0 {
				if (R/2)%2 != 0 || R == 4 {
					if get {
						total += R / 2
					}
					R = R / 2
				} else {
					if get {
						total += 1
					}
					R = R - 1
				}

			} else {
				if get {
					total += 1
				}
				R = R - 1
			}
			get = !get
		}
		Fprintln(out, total)
	}

}

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


You have an array of positive integers a[1], a[2], ..., a[n] and a set of bad prime numbers b1, b2, ..., bm. The prime numbers that do not occur in the set b are considered good. The beauty of array a is the sum , where function f(s) is determined as follows:  f(1) = 0;  Let's assume that p is the minimum prime divisor of s. If p is a good prime, then , otherwise . You are allowed to perform an arbitrary (probably zero) number of operations to improve array a. The operation of improvement is the following sequence of actions:  Choose some number r (1 ≤ r ≤ n) and calculate the value g = GCD(a[1], a[2], ..., a[r]).  Apply the assignments: , , ..., . What is the maximum beauty of the array you can get?

The first line contains two integers n and m (1 ≤ n, m ≤ 5000) showing how many numbers are in the array and how many bad prime numbers there are. The second line contains n space-separated integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109) — array a. The third line contains m space-separated integers b1, b2, ..., bm (2 ≤ b1 < b2 < ... < bm ≤ 109) — the set of bad prime numbers.

Print a single integer — the answer to the problem.

NoteNote that the answer to the problem can be negative.The GCD(x1, x2, ..., xk) is the maximum positive integer that divides each xi.

package main

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

var n, m int

func Gcd(x int, y int) int {
	if x == 0 {
		return y
	} else {
		return Gcd(y%x, x)
	}
}

const maxn = 32768

var p [maxn]int
var plen = 0
var bad map[int]bool

func GetPrime() {
	for i := 2; i < maxn; i++ {
		var mk = false
		for j := 0; j < plen && !mk && p[j]*p[j] <= i; j++ {
			if i%p[j] == 0 {
				mk = true
			}
		}
		if !mk {
			p[plen] = i
			plen++
		}
	}
}

func Count(x int) int {
	var ret = 0
	for now := 0; x != 1 && now < plen; now++ {
		if x%p[now] == 0 {
			var cur = 0
			for x%p[now] == 0 {
				cur++
				x /= p[now]
			}
			if bad[p[now]] {
				ret -= cur
			} else {
				ret += cur
			}
		}
	}
	if x != 1 {
		if bad[x] {
			ret--
		} else {
			ret++
		}
	}
	return ret
}

func main() {
	scanner.Split(bufio.ScanWords)
	GetPrime()
	n = scanner.NextInt()
	m = scanner.NextInt()
	a := make([]int, n)
	b := make([]int, n)
	bad = make(map[int]bool)
	for i := 0; i < n; i++ {
		a[i] = scanner.NextInt()
	}
	for i := 0; i < m; i++ {
		bad[scanner.NextInt()] = true
	}
	var ans = 0
	var now = 0
	for i := 0; i < n; i++ {
		now = Gcd(now, a[i])
		ans += Count(a[i])
		b[i] = Count(now)
	}
	var cur = 0
	for i := n - 1; i >= 0; i-- {
		if b[i] < cur {
			ans += (cur - b[i]) * (i + 1)
			cur = b[i]
		}
	}
	fmt.Printf("%d\n", ans)
}

type Scanner struct {
	*bufio.Scanner
}

var scanner = Scanner{bufio.NewScanner(os.Stdin)}

func (self *Scanner) Next() string {
	if !self.Scan() {
		panic(self.Err())
	}
	return self.Text()
}

func (self *Scanner) NextInt() int {
	x, err := strconv.Atoi(self.Next())
	if err != nil {
		panic(err)
	}
	return x
}

package main

import "fmt"

var n, m int

func Gcd(x int, y int) int {
    if x == 0 {
        return y
    } else {
        return Gcd(y%x, x)
    }
}

const maxn = 32768

var p [maxn]int
var plen = 0
var bad map[int]bool

func GetPrime() {
    for i := 2; i < maxn; i++ {
        var mk = false
        for j := 0; j < plen && !mk && p[j]*p[j] <= i; j++ {
            if i%p[j] == 0 {
                mk = true
            }
        }
        if !mk {
            p[plen] = i
            plen++
        }
    }
}

func Count(x int) int {
    var ret = 0
    for now := 0; x != 1 && now < plen; now++ {
        if x%p[now] == 0 {
            var cur = 0
            for x%p[now] == 0 {
                cur++
                x /= p[now]
            }
            if bad[p[now]] {
                ret -= cur
            } else {
                ret += cur
            }
        }
    }
    if x != 1 {
        if bad[x] {
            ret--
        } else {
            ret++
        }
    }
    return ret
}

func main() {
    GetPrime()
    fmt.Scanf("%d %d\n", &n, &m)
    a := make([]int, n)
    b := make([]int, n)
    bad = make(map[int]bool)
    for i := 0; i < n; i++ {
        fmt.Scanf("%d", &a[i])
    }
    var x int
    fmt.Scanf("%d", &x)
    for i := 0; i < m; i++ {
        fmt.Scanf("%d", &x)
        bad[x] = true
    }
    var ans = 0
    var now = 0
    for i := 0; i < n; i++ {
        now = Gcd(now, a[i])
        ans += Count(a[i])
        b[i] = Count(now)
    }
    var cur = 0
    for i := n - 1; i >= 0; i-- {
        if b[i] < cur {
            ans += (cur - b[i]) * (i + 1)
            cur = b[i]
        }
    }
    fmt.Printf("%d\n", ans)
}

package main

import "fmt"

var n, m int

func Gcd(x int, y int) int {
	if x == 0 {
		return y
	} else {
		return Gcd(y%x, x)
	}
}

const maxn = 32768

var p [maxn]int
var plen = 0
var bad map[int]bool

func GetPrime() {
	for i := 2; i < maxn; i++ {
		var mk = false
		for j := 0; j < plen && !mk && p[j]*p[j] <= i; j++ {
			if i%p[j] == 0 {
				mk = true
			}
		}
		if !mk {
			p[plen] = i
			plen++
		}
	}
}

func Count(x int) int {
	var ret = 0
	for now := 0; x != 1 && now < plen; now++ {
		if x%p[now] == 0 {
			var cur = 0
			for x%p[now] == 0 {
				cur++
				x /= p[now]
			}
			if bad[p[now]] {
				ret -= cur
			} else {
				ret += cur
			}
		}
	}
	if x != 1 {
		if bad[x] {
			ret--
		} else {
			ret++
		}
	}
	return ret
}

func main() {
	GetPrime()
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([]int, n)
	b := make([]int, n)
	bad = make(map[int]bool)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &a[i])
	}
	for i := 0; i < m; i++ {
		var x int
		fmt.Scanf("%d", &x)
		bad[x] = true
	}
	var ans = 0
	var now = 0
	for i := 0; i < n; i++ {
		now = Gcd(now, a[i])
		ans += Count(a[i])
		b[i] = Count(now)
	}
	var cur = 0
	for i := n - 1; i >= 0; i-- {
		if b[i] < cur {
			ans += (cur - b[i]) * (i + 1)
			cur = b[i]
		}
	}
	fmt.Printf("%d\n", ans)
}

package main

import "fmt"

var n, m int

func Gcd(x int, y int) int {
    if x == 0 {
        return y
    } else {
        return Gcd(y%x, x)
    }
}

const maxn = 32768

var p [maxn]int
var plen = 0
var bad map[int]bool

func GetPrime() {
    for i := 2; i < maxn; i++ {
        var mk = false
        for j := 0; j < plen && !mk && p[j]*p[j] <= i; j++ {
            if i%p[j] == 0 {
                mk = true
            }
        }
        if !mk {
            p[plen] = i
            plen++
        }
    }
}

func Count(x int) int {
    var ret = 0
    for now := 0; x != 1 && now < plen; now++ {
        if x%p[now] == 0 {
            var cur = 0
            for x%p[now] == 0 {
                cur++
                x /= p[now]
            }
            if bad[p[now]] {
                ret -= cur
            } else {
                ret += cur
            }
        }
    }
    if x != 1 {
        if bad[x] {
            ret--
        } else {
            ret++
        }
    }
    return ret
}

func main() {
    GetPrime()
    fmt.Scanf("%d %d\n", &n, &m)
    a := make([]int, n)
    b := make([]int, n)
    bad = make(map[int]bool)
    for i := 0; i < n; i++ {
        fmt.Scanf("%d", &a[i])
    }
    var x int
    for i := 0; i < 1; i++ {
        fmt.Scanf("%d", &x)
        bad[x] = true
    }
    var ans = 0
    var now = 0
    for i := 0; i < n; i++ {
        now = Gcd(now, a[i])
        ans += Count(a[i])
        b[i] = Count(now)
    }
    var cur = 0
    for i := n - 1; i >= 0; i-- {
        if b[i] < cur {
            ans += (cur - b[i]) * (i + 1)
            cur = b[i]
        }
    }
    fmt.Printf("%d\n", x)
}

package main

import "fmt"

var n, m int

func Gcd(x int, y int) int {
    if x == 0 {
        return y
    } else {
        return Gcd(y%x, x)
    }
}

const maxn = 32768

var p [maxn]int
var plen = 0
var bad map[int]bool

func GetPrime() {
    for i := 2; i < maxn; i++ {
        var mk = false
        for j := 0; j < plen && !mk && p[j]*p[j] <= i; j++ {
            if i%p[j] == 0 {
                mk = true
            }
        }
        if !mk {
            p[plen] = i
            plen++
        }
    }
}

func Count(x int) int {
    var ret = 0
    for now := 0; x != 1 && now < plen; now++ {
        if x%p[now] == 0 {
            var cur = 0
            for x%p[now] == 0 {
                cur++
                x /= p[now]
            }
            if bad[p[now]] {
                ret -= cur
            } else {
                ret += cur
            }
        }
    }
    if x != 1 {
        if bad[x] {
            ret--
        } else {
            ret++
        }
    }
    return ret
}

func main() {
    GetPrime()
    fmt.Scanf("%d %d\n", &n, &m)
    a := make([]int, n)
    b := make([]int, n)
    bad = make(map[int]bool)
    for i := 0; i < n; i++ {
        fmt.Scanf("%d%c", &a[i])
    }
    for i := 0; i < m; i++ {
        var x int
        fmt.Scanf("%d%c", &x)
        bad[x] = true
    }
    var ans = 0
    var now = 0
    for i := 0; i < n; i++ {
        now = Gcd(now, a[i])
        ans += Count(a[i])
        b[i] = Count(now)
    }
    var cur = 0
    for i := n - 1; i >= 0; i-- {
        if b[i] < cur {
            ans += (cur - b[i]) * (i + 1)
            cur = b[i]
        }
    }
    fmt.Printf("%d\n", ans)
}


A basketball competition is held where the number of players in a team does not have a maximum or minimum limit (not necessarily $$$5$$$ players in one team for each match). There are $$$N$$$ candidate players in the competition that will be trained by Pak Chanek, the best basketball coach on earth. The $$$i$$$-th candidate player has a power of $$$P_i$$$.Pak Chanek will form zero or more teams from the $$$N$$$ candidate players on the condition that each candidate player may only join in at most one team. Each of Pak Chanek's teams will be sent to compete once with an enemy team that has a power of $$$D$$$. In each match, the team sent is said to defeat the enemy team if the sum of powers from the formed players is strictly greater than $$$D$$$.One of Pak Chanek's skills is that when a team that has been formed plays in a match, he can change the power of each player in the team to be equal to the biggest player power from the team.Determine the maximum number of wins that can be achieved by Pak Chanek.

The first line contains two integers $$$N$$$ and $$$D$$$ ($$$1 \le N \le 10^5$$$, $$$1 \le D \le 10^9$$$) — the number of candidate players and the power of the enemy team. The second line contains $$$N$$$ integers $$$P_1, P_2, \ldots, P_N$$$ ($$$1 \le P_i \le 10^9$$$) — the powers of all candidate players.

A line containing an integer representing the maximum number of wins that can be achieved by Pak Chanek.

NoteThe $$$1$$$-st team formed is a team containing players $$$4$$$ and $$$6$$$. The power of each player in the team becomes $$$100$$$. So the total power of the team is $$$100 + 100 = 200 > 180$$$.The $$$2$$$-nd team formed is a team containing players $$$1$$$, $$$2$$$, and $$$5$$$. The power of each player in the team becomes $$$90$$$. So the total power of the team is $$$90 + 90 + 90 = 270 > 180$$$.

package main

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

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

	var n, d int
	fmt.Fscan(r, &n, &d)
	p := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscan(r, &p[i])
	}
	sort.Ints(p)

	left := 0
	right := n - 1
	wins := 0

	for right >= 0 {
		// fmt.Fprintf(w, "left: %d, right: %d, d: %d, p[right]: %d, d/p[r]: %d, wins:%d\n", left, right, d, p[right], d/p[right], wins)
		left += d / p[right]
		if right >= left {
			wins++
			right--
		} else {
			break
		}
	}
	fmt.Fprintln(w, wins)
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	n      int
	d      int64
)

func solve(n int, d int64, p []int64) int {
	var r, prevr, c int
	sort.Slice(p, func(i, j int) bool {
		return p[i] < p[j]
	})
	for i := n - 1; i > -1; i-- {
		r = int(d/p[i] + 1)
		if i < n-1 {
			r += prevr
		}
		prevr = r
		if r <= n {
			c++
		} else {
			break
		}
	}
	return c
}

func main() {
	fmt.Fscan(reader, &n, &d)
	var p = make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &p[i])
	}
	fmt.Println(solve(n, d, p))
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	n      int
	d      int64
)

func solve(n int, d int64, p []int64) int {
	var r, c = make([]int, n), 0
	sort.Slice(p, func(i, j int) bool {
		return p[i] < p[j]
	})
	for i := n - 1; i > -1; i-- {
		r[i] = int(d/p[i] + 1)
		if i < n-1 {
			r[i] += r[i+1]
		}
		if r[i] <= n {
			c++
		} else {
			break
		}
	}
	return c
}

func main() {
	fmt.Fscan(reader, &n, &d)
	var p = make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &p[i])
	}
	fmt.Println(solve(n, d, p))
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	n      int
	d      int64
)

func solve(n int, d int64, p []int64) int {
	var r = make([]int, n)
	var c int
	sort.Slice(p, func(i, j int) bool {
		return p[i] < p[j]
	})
	for i := n - 1; i > -1; i-- {
		if i == n-1 {
			r[i] = int((p[i] + d) / p[i])
		} else {
			r[i] = int((p[i]+d)/p[i]) + r[i+1]
		}
		if r[i] <= n {
			c++
		} else {
			break
		}
	}
	return c
}

func main() {
	fmt.Fscan(reader, &n, &d)
	var p = make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &p[i])
	}
	fmt.Println(solve(n, d, p))
}

package main

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

func main() {
	var N, D int
	fmt.Scanln(&N, &D)
	var reader = bufio.NewReader(os.Stdin)
	var p = getIntln(reader)
	sort.Slice(p, func(i, j int) bool {
		return p[i] < p[j]
	})
	var x = sort.Search(N, func(i int) bool {
		return p[i] > D
	})
	var result = N - x
	var first, last = 0, x - 1
	for first < last {
		var x = p[last]
		for x <= D && first < last {
			x += p[last]
			first++
		}
		if x > D {
			result++
		}
		last--
	}
	fmt.Println(result)
}

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

func getString(in *bufio.Reader) string {
	var s, _ = in.ReadString('\n')
	s = strings.TrimSpace(s)
	return s
}

package main

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

// https://codeforces.com/problemset/problem/1725/B
func P1725b(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	var players = make([]int, n)

	for i := 0; i < n; i++ {
		var v int
		fmt.Fscan(in, &v)
		players[i] = v
	}

	var res int = 0

	sort.Ints(players)
	for len(players) > 0 {
		var best int = players[len(players)-1]
		var needTotal int = d/best + 1
		if needTotal > len(players) {
			break
		}
		var newPlayers = players[(needTotal - 1):(len(players) - 1)]
		players = newPlayers
		res++
	}
	fmt.Fprintf(out, "%d\n", res)
}

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

package main

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

const cf = true

func solve() {
	var n, d int
	fmt.Fscan(in, &n, &d)
	d++
	powers := make([]int, n)
	for i := range powers {
		fmt.Fscan(in, &powers[i])
	}
	sort.Slice(powers, func(i, j int) bool {
		return powers[j] < powers[i]
	})
	playersLeft := n
	ans := 0
	for i := range powers {
		needed := d/powers[i] + min(1, d%powers[i])
		playersLeft -= needed
		if playersLeft < 0 {
			break
		}
		ans++
	}
	fmt.Fprintln(out, ans)
}

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"
	"fmt"
	"os"
	"sort"
)

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

	var n, d int
	fmt.Fscan(r, &n, &d)
	p := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscan(r, &p[i])
	}
	// fmt.Fprintln(w, "******** p ", p)
	sort.Ints(p)
	// fmt.Fprintln(w, "####******** p ", p)

	left := 0
	right := n - 1
	wins := 0

	for {
		// fmt.Fprintf(w, "left: %d, right: %d, d: %d, p[right]: %d, d/p[r]: %d, wins:%d\n", left, right, d, p[right], d/p[right], wins)
		left += d / p[right] + 1
		if right + 1 >= left {
			wins++
			right--
		} else {
			break
		}
	}
	fmt.Fprintln(w, wins)
}

package main

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

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

	var n, d int
	fmt.Fscan(r, &n, &d)
	p := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscan(r, &p[i])
	}
	// fmt.Fprintln(w, "******** p ", p)
	sort.Ints(p)
	// fmt.Fprintln(w, "####******** p ", p)

	left := 0
	right := n - 1
	wins := 0

	for {
		// fmt.Fprintf(w, "left: %d, right: %d, d: %d, p[right]: %d, d/p[r]: %d, wins:%d\n", left, right, d, p[right], d/p[right], wins)
		t := d / p[right]
		if d % p[right] > 0 {
			t++
		}
		left += t
		if right + 1 >= left {
			wins++
			right--
		} else {
			break
		}
	}
	fmt.Fprintln(w, wins)
}

package main

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

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

	var n, d int
	fmt.Fscan(r, &n, &d)
	p := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscan(r, &p[i])
	}
	// fmt.Fprintln(w, "******** p ", p)
	sort.Ints(p)
	// fmt.Fprintln(w, "####******** p ", p)

	left := 0
	right := n - 1
	wins := 0

	for {
		// fmt.Fprintf(w, "left: %d, right: %d, d: %d, p[right]: %d, d/p[r]: %d, wins:%d\n", left, right, d, p[right], d/p[right], wins)
		t := d / p[right]
		if d % p[right] > 0 {
			t++
		}
		left += t
		if right >= left {
			wins++
			right--
		} else {
			break
		}
	}
	fmt.Fprintln(w, wins)
}

package main

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

func main() {
	var N, D int
	fmt.Scanln(&N, &D)
	var reader = bufio.NewReader(os.Stdin)
	var p = getIntln(reader)
	sort.Slice(p, func(i, j int) bool {
		return p[i] < p[j]
	})
	var x = sort.Search(N, func(i int) bool {
		return p[i] > D
	})
	var result = N - x
	var first, last = 0, x - 1
	for first < last {
		var x = p[last]
		for x <= D && first < last {
			x += p[last]
			first++
		}
		result++
		last--
	}
	fmt.Println(result)
}

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

func getString(in *bufio.Reader) string {
	var s, _ = in.ReadString('\n')
	s = strings.TrimSpace(s)
	return s
}

package main

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

// https://codeforces.com/problemset/problem/1725/B
func P1725b(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	var players = make([]int, n)

	for i := 0; i < n; i++ {
		var v int
		fmt.Fscan(in, &v)
		players[i] = v
	}

	var res int = 0

	sort.Ints(players)
	for len(players) > 0 {
		var best int = players[len(players)-1]
		var needTotal = int(math.Ceil(float64(d) / float64(best)))
		if needTotal > len(players) {
			break
		}
		var newPlayers = players[(needTotal - 1):(len(players) - 1)]
		players = newPlayers
		res++
	}
	fmt.Fprintf(out, "%d\n", res)
}

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

package main

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

const cf = true

func solve() {
	var n, d int
	fmt.Fscan(in, &n, &d)
	powers := make([]int, n)
	for i := range powers {
		fmt.Fscan(in, &powers[i])
	}
	sort.Slice(powers, func(i, j int) bool {
		return powers[j] < powers[i]
	})
	playersLeft := n
	ans := 0
	for i := range powers {
		needed := d/powers[i] + min(1, d%powers[i])
		playersLeft -= needed
		if playersLeft < 0 {
			break
		}
		ans++
	}
	fmt.Fprintln(out, ans)
}

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


An agent called Cypher is decrypting a message, that contains a composite number $$$n$$$. All divisors of $$$n$$$, which are greater than $$$1$$$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.

The first line contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. Next $$$t$$$ lines describe each test case. In a single line of each test case description, there is a single composite number $$$n$$$ $$$(4 \le n \le 10^9)$$$ — the number from the message. It's guaranteed that the total number of divisors of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case in the first line output the initial order of divisors, which are greater than $$$1$$$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them.

NoteIn the first test case $$$6$$$ has three divisors, which are greater than $$$1$$$: $$$2, 3, 6$$$. Regardless of the initial order, numbers $$$2$$$ and $$$3$$$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $$$2, 6, 3, 6$$$, and every two adjacent numbers are not coprime.In the second test case $$$4$$$ has two divisors greater than $$$1$$$: $$$2, 4$$$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of $$$30$$$ greater than $$$1$$$ can be placed in some order so that there are no two adjacent numbers that are coprime.

package main

import (
	"bufio"
	. "fmt"
	"io"
	"math/bits"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1419E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type pair struct{ p, e int }

	var T, n, l, r int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		op := 1
		fs := []pair{}
		for i := 2; i*i <= n; i++ {
			e := 0
			for ; n%i == 0; n /= i {
				e++
			}
			if e > 0 {
				fs = append(fs, pair{i, e})
				if e > 1 {
					op = 0
				}
			}
		}
		if n > 1 {
			fs = append(fs, pair{n, 1})
		}

		ans := []interface{}{}
		var f func(m, v int)
		f = func(m, v int) {
			if m == 0 {
				ans = append(ans, v)
				return
			}
			p := fs[bits.TrailingZeros(uint(m))]
			m &= m - 1
			for i := 0; i < p.e; i++ {
				v *= p.p
				f(m, v)
			}
		}
		n = len(fs)
		for i := 1; i < 1<<n; i++ {
			m := i ^ i>>1
			if m+1 == 1<<n {
				l = len(ans)
				f(m, 1)
				r = len(ans)
			} else {
				f(m, 1)
			}
		}
		if n == 2 {
			l++
		} else {
			op = 0
		}
		Fprint(out, ans[:l]...)
		Fprint(out, " ")
		Fprint(out, ans[r:]...)
		Fprint(out, " ")
		Fprintln(out, ans[l:r]...)
		Fprintln(out, op)
	}
}

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

package main

import (
	"bufio"
	. "fmt"
	"io"
	"math/bits"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1419E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type pair struct{ p, e int }

	var T, n, l, r int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		if n == 6 {
			Fprintln(out, "2 3 6\n1")
			continue
		}
		fs := []pair{}
		for i := 2; i*i <= n; i++ {
			e := 0
			for ; n%i == 0; n /= i {
				e++
			}
			if e > 0 {
				fs = append(fs, pair{i, e})
			}
		}
		if n > 1 {
			fs = append(fs, pair{n, 1})
		}

		ans := []interface{}{}
		var f func(m, v int)
		f = func(m, v int) {
			if m == 0 {
				ans = append(ans, v)
				return
			}
			p := fs[bits.TrailingZeros(uint(m))]
			m &= m - 1
			for i := 0; i < p.e; i++ {
				v *= p.p
				f(m, v)
			}
		}
		n = len(fs)
		for i := 1; i < 1<<n; i++ {
			m := i ^ i>>1
			if m+1 == 1<<n {
				l = len(ans)
				if n == 2 {
					l++
				}
				f(m, 1)
				r = len(ans)
			} else {
				f(m, 1)
			}
		}
		Fprint(out, ans[:l]...)
		Fprint(out, " ")
		Fprint(out, ans[r:]...)
		Fprint(out, " ")
		Fprintln(out, ans[l:r]...)
		Fprintln(out, 0)
	}
}

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


The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits.Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri — the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1, y1) and (x2, y2) is Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place.The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.

The first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa ≠ xb, ya ≠ yb). The second line contains integer n — the number of radiators (1 ≤ n ≤ 103). Then n lines contain the heaters' coordinates as "xi yi ri", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1 ≤ ri ≤ 1000. Several radiators can be located at the same point.

Print the only number — the number of blankets you should bring.

NoteIn the first sample the generals are sitting at points: (2, 2), (2, 3), (2, 4), (2, 5), (3, 2), (3, 5), (4, 2), (4, 3), (4, 4), (4, 5). Among them, 4 generals are located outside the heating range. They are the generals at points: (2, 5), (3, 5), (4, 4), (4, 5).In the second sample the generals are sitting at points: (5, 2), (5, 3), (6, 2), (6, 3). All of them are located inside the heating range.

package main

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

func main(){
	var a [2]int
	var b [2]int
	re := bufio.NewScanner(os.Stdin)
	re.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	re.Scan()
	a[0], _ = strconv.Atoi(re.Text())
	re.Scan()
	b[0], _ = strconv.Atoi(re.Text())
	re.Scan()
	a[1], _ = strconv.Atoi(re.Text())
	re.Scan()
	b[1], _ = strconv.Atoi(re.Text())
	var n int
	re.Scan()
	n, _ = strconv.Atoi(re.Text())
	x := make([]int, n)
	y := make([]int, n)
	r := make([]int, n)
	ans := 0
	for i:=0; i<n; i++ {
		re.Scan()
		x[i], _ = strconv.Atoi(re.Text())
		re.Scan()
		y[i], _ = strconv.Atoi(re.Text())
		re.Scan()
		r[i], _ = strconv.Atoi(re.Text())
	}
	if a[0] > a[1] {
		t := a[0]
		a[0] = a[1]
		a[1] = t
	}
	if b[0] > b[1] {
		t := b[0]
		b[0] = b[1]
		b[1] = t
	}
	for i:=a[0]; i<=a[1]; i++ {
		for j:=b[0]; j<=b[1]; j++ {
			if (i == a[0] || i == a[1]) && (j >= b[0] && j <= b[1]) {
				h := 0
				for k:=0; k<n; k++ {
					p, q := 0, 0
					p = i-x[k]
					q = j-y[k]
					if p*p+q*q <= r[k]*r[k] {
						h = 1
					}
				}
				if h == 0 {
					ans += 1
				}
			}
			if (j == b[0] || j == b[1]) && (i > a[0] && i < a[1]) {
				h := 0
				for k:=0; k<n; k++ {
					p, q := 0, 0
					p = i-x[k]
					q = j-y[k]
					if p*p+q*q <= r[k]*r[k] {
						h = 1
					}
				}
				if h == 0 {
					ans += 1
				}
			}
		}
	}
	w.WriteString(strconv.Itoa(ans)+"\n")
	w.Flush()
}

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  x0, y0, x1, y1 := getI(), getI(), getI(), getI()
  if x0 > x1 {
    x0, x1 = x1, x0
  }
  if y0 > y1 {
    y0, y1 = y1, y0
  }
  chairs := map[[2]int]bool{}
  for x := x0; x <= x1; x++ {
    chairs[[2]int{ x, y0 }] = true
    chairs[[2]int{ x, y1 }] = true
  }
  for y := y0; y <= y1; y++ {
    chairs[[2]int{ x0, y }] = true
    chairs[[2]int{ x1, y }] = true
  }

  numRadiators := getI()
  for i := 0; i < numRadiators; i++ {
    x, y, r := getI(), getI(), getI()
    toRemove := [][2]int{}
    for chair := range(chairs) {
      X, Y := chair[0], chair[1]
      if (X - x) * (X - x) + (Y - y) * (Y - y) <= r * r {
        toRemove = append(toRemove, chair)
      }
    }
    for _, chair := range(toRemove) {
      delete(chairs, chair)
    }
  }

  result := len(chairs)
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

import (
    "fmt"
    "math"
)

func main() {
    d := func(x1,y1,x2,y2 int) float64 {
        dx, dy := float64(x1-x2), float64(y1-y2)
        return math.Sqrt((dx*dx)+(dy*dy))
    }

    var xa,ya,xb,yb,n int
    fmt.Scan(&xa,&ya,&xb,&yb)
    if xa > xb { xa, xb = xb, xa }
    if ya > yb { ya, yb = yb, ya }
    fmt.Scan(&n)
    x, y, r := make([]int,n), make([]int,n), make([]float64,n)
    for i := 0; i < n; i++ { fmt.Scan(&x[i],&y[i],&r[i]) }
    ans := 0
    for i := xa; i <= xb; i++ {
        a, b := true, true
        for j := 0; j < n; j++ {
            if d(i,ya,x[j],y[j]) <= r[j] { a = false }
            if d(i,yb,x[j],y[j]) <= r[j] { b = false }
        }
        if (a && b) {
            ans += 2
        } else if (a || b) {
            ans += 1
        }
    }
    for i := ya+1; i < yb; i++ {
        a, b := true, true
        for j := 0; j < n; j++ {
            if d(xa,i,x[j],y[j]) <= r[j] { a = false }
            if d(xb,i,x[j],y[j]) <= r[j] { b = false }
        }
        if (a && b) {
            ans += 2
        } else if (a || b) {
            ans += 1
        }
    }
    fmt.Println(ans)
}

// 144B-mic
package main

import (
	"fmt"
	"math"
)

func main() {
	var xa, ya, xb, yb, lx, ly, rx, ry, n, i, j, res int
	var a, b, c []int
	fmt.Scan(&xa, &ya, &xb, &yb)
	lx = int(math.Min(float64(xa), float64(xb)))
	ly = int(math.Min(float64(ya), float64(yb)))
	rx = int(math.Max(float64(xa), float64(xb)))
	ry = int(math.Max(float64(ya), float64(yb)))
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		var f, s, t int
		fmt.Scan(&f, &s, &t)
		a = append(a, f)
		b = append(b, s)
		c = append(c, t)
	}
	for i = lx; i <= rx; i++ {
		add := 1
		for j = 0; j < n && add == 1; j++ {
			if (a[j]-i)*(a[j]-i)+(b[j]-ly)*(b[j]-ly) <= c[j]*c[j] {
				add = 0
			}
		}
		res += add
	}

	for i = lx; i <= rx; i++ {
		add := 1
		for j = 0; j < n && add == 1; j++ {
			if (a[j]-i)*(a[j]-i)+(b[j]-ry)*(b[j]-ry) <= c[j]*c[j] {
				add = 0
			}
		}
		res += add
	}

	for i = ly + 1; i < ry; i++ {
		add := 1
		for j = 0; j < n && add == 1; j++ {
			if (a[j]-lx)*(a[j]-lx)+(b[j]-i)*(b[j]-i) <= c[j]*c[j] {
				add = 0
			}
		}
		res += add
	}

	for i = ly + 1; i < ry; i++ {
		add := 1
		for j = 0; j < n && add == 1; j++ {
			if (a[j]-rx)*(a[j]-rx)+(b[j]-i)*(b[j]-i) <= c[j]*c[j] {
				add = 0
			}
		}
		res += add
	}
	fmt.Println(res)
}