You have to restore the wall. The wall consists of $$$N$$$ pillars of bricks, the height of the $$$i$$$-th pillar is initially equal to $$$h_{i}$$$, the height is measured in number of bricks. After the restoration all the $$$N$$$ pillars should have equal heights.You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is $$$A$$$; remove a brick from the top of one non-empty pillar, the cost of this operation is $$$R$$$; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $$$M$$$.You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $$$0$$$.What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?

The first line of input contains four integers $$$N$$$, $$$A$$$, $$$R$$$, $$$M$$$ ($$$1 \le N \le 10^{5}$$$, $$$0 \le A, R, M \le 10^{4}$$$) — the number of pillars and the costs of operations. The second line contains $$$N$$$ integers $$$h_{i}$$$ ($$$0 \le h_{i} \le 10^{9}$$$) — initial heights of pillars.

Print one integer — the minimal cost of restoration.

package main

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

var sc = WordScanner()
var memory [1000000]int
var memory2 [1000000]int64

func main() {
	n := sc.Int()
	a := int64(sc.Int())
	r := int64(sc.Int())
	m := int64(sc.Int())
	if m > a + r {
		m = a + r
	}
	hsp := memory[:n]
	for i := range hsp {
		hsp[i] = sc.Int()
	}
	sort.Ints(hsp)
	hs := memory2[:n]
	for i := range hs {
		hs[i] = int64(hsp[i])
	}
	for i := range hs[1:] {
		hs[i + 1] += hs[i]
	}
	var ans int64 = r * (hs[n - 1] - hs[0] * int64(n))
	var f bool
	for i := range hs {
		if i > 0 && hsp[i] == hsp[i - 1] {
			continue
		}
		h := int64(hsp[i])
		x := int64(i + 1) * h - hs[i]
		y := hs[n - 1] - hs[i] - int64(n - i - 1) * h
		w := x * m + (y - x) * r
		if y < x {
			if !f {
				d := (x - y) / int64(n)
				w = (y + d * int64(n - i)) * m + (x - y - d * int64(n)) * a
				if ans > w {
					ans = w
				}
				if d * int64(n) < x - y {
					w = (x - (d + 1) * int64(i)) * m + (y - x + (d + 1) * int64(n)) * r
					if ans > w {
						ans = w
					}
				}
				f = true
			}
			w = y * m + (x - y) * a
		}
		if ans > w {
			ans = w
		}
	}
	fmt.Println(ans)
}

type Scanner struct {
	*bufio.Scanner
}

func WordScanner() Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return Scanner{sc}
}

func (sc Scanner) Text() string {
	sc.Scan()
	return sc.Scanner.Text()
}

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

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}
	lastIndex := len(dp) - 1

	var minCost int64 = 1e18

	for i := 0; i < len(h) - 1; i++ {
		if h[i] == h[i + 1] {
			continue
		}
		leftCount := int64(i + 1)
		rightCount := int64(len(h) - i - 1)

		if A + R < M {

			var height int64

			if leftCount * A > rightCount * R {
				height = h[i]

			} else {
				height = h[i+1] - 1
			}

			top := height * leftCount
			sm := top - dp[i]
			sp := dp[lastIndex] - dp[i] - rightCount * height

			cost := sm * A + sp * R

			if cost < minCost {
				minCost = cost
			}

		} else {
			bottomSM := leftCount * h[i] - dp[i]
			bottomSP := dp[lastIndex] - dp[i] - rightCount * h[i]
			smTop :=  leftCount * (h[i + 1] - 1) - dp[i]
			spTop := dp[lastIndex] - dp[i] - rightCount * (h[i + 1] - 1)

			var bottomCost int64
			var tCost int64 = 1e18
			var t2Cost int64 = 1e18
			var topCost int64
			var localMin int64

			if bottomSP > bottomSM {
				bottomCost = R * (bottomSP - bottomSM) + M * bottomSM

				diff := bottomSP - bottomSM
				t := diff/(leftCount + rightCount)
				threshold := t
				if diff % (leftCount + rightCount) != 0 {
					threshold++
				}

				if threshold < h[i + 1] - h[i] {
					sm1 := leftCount * (h[i] + t) - dp[i]
					sp1 := dp[lastIndex] - dp[i] - rightCount * (h[i] + t)
					tCost = sm1 * M + (sp1 - sm1) * R

					sm2 := leftCount * (h[i] + t + 1) - dp[i]
					sp2 := dp[lastIndex] - dp[i] - rightCount * (h[i] + t + 1)
					t2Cost = (sm2 - sp2) * A + sp2 * M
					topCost = (smTop - spTop) * A + spTop * M
				} else {
					topCost = (spTop - smTop) * R + smTop * M
				}

				localMin = min(bottomCost, min(tCost, min(t2Cost, topCost)))

				minCost = min(minCost, localMin)

			} else {
				bottomCost = A * (bottomSM - bottomSP) + M * bottomSP
				topCost = (smTop - spTop) * A + spTop * M

				localMin = min(bottomCost, topCost)
				minCost = min(minCost, localMin)
			}
		}
	}

	var lastCost int64 = ((int64(h[lastIndex]) * int64(len(h))) - dp[lastIndex]) * A

	minCost = min(minCost, lastCost)

	return minCost
}

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

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

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

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

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

const MAXN = 100010

var (
	n, a, r, m int
	arr        [MAXN]int
	ar         []int
	sum        [MAXN]int64
)

func find_lm(ar []int, h int) (lt, mt int64) {
	lt_i := sort.Search(len(ar), func(i int) bool { return ar[i] >= h }) - 1
	mt_i := sort.Search(len(ar), func(i int) bool { return ar[i] > h })

	lt, mt = 0, 0
	if lt_i >= 0 {
		lt = sum[lt_i]
	}
	lt = int64(lt_i + 1) * int64(h) - lt;

	mt = sum[n - 1]
	if mt_i > 0 {
		mt -= sum[mt_i - 1]
	}
	mt = mt - int64(n - mt_i) * int64(h);

	return
}

func Tern(mx int, f func(i int) int64) (i int, val int64) {
	lo, hi := 0, mx
	for lo < hi {
		mid := lo + (hi - lo) / 2
		if f(mid) > f(mid + 1) {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	return lo, f(lo)
}

func main() {
	scanf("%d %d %d %d\n", &n, &a, &r, &m)

	for i := 0; i < n; i++ {
		if i < n - 1 {
			scanf("%d", &arr[i])
		} else {
			scanf("%d\n", &arr[i])
		}
	}

	ar = arr[:n]
	sort.Ints(ar)
	for i := 0; i < n; i++ {
		sum[i] = int64(ar[i])
		if i > 0 {
			sum[i] += sum[i - 1]
		}
	}

	max_height := arr[n - 1]

	_, cost1 := Tern(max_height, func(h int) int64 {
		lt, mt := find_lm(ar, h)
		return lt*int64(a) + mt*int64(r)
	})

	_, cost2 := Tern(max_height, func(h int) int64 {
		lt, mt := find_lm(ar, h)
		to_move := Min(lt, mt)
		return to_move*int64(m) + (lt-to_move)*int64(a) + (mt-to_move)*int64(r)
	})

	fmt.Println(Min(cost1, cost2))
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}
	lastIndex := len(dp) - 1

	var minCost int64 = 1e18

	for i := 0; i < len(h) - 1; i++ {
		if h[i] == h[i + 1] {
			continue
		}
		leftCount := int64(i + 1)
		rightCount := int64(len(h) - i - 1)

		if A + R < M {

			var height int64

			if leftCount * A > rightCount * R {
				height = h[i]

			} else {
				height = h[i+1] - 1
			}

			top := height * leftCount
			sm := top - dp[i]
			sp := dp[lastIndex] - dp[i] - rightCount * height

			cost := sm * A + sp * R

			if cost < minCost {
				minCost = cost
			}

		} else {
			bottomSM := leftCount * h[i] - dp[i]
			bottomSP := dp[lastIndex] - dp[i] - rightCount * h[i]
			smTop :=  leftCount * (h[i + 1] - 1) - dp[i]
			spTop := dp[lastIndex] - dp[i] - rightCount * (h[i + 1] - 1)

			var bottomCost int64
			var tCost int64 = 1e18
			var t2Cost int64 = 1e18
			var topCost int64
			var localMin int64

			if bottomSP > bottomSM {
				bottomCost = R * (bottomSP - bottomSM) + M * bottomSM

				diff := bottomSP - bottomSM
				t := diff/(leftCount + rightCount)
				if diff % (leftCount + rightCount) != 0 {
					t++
				}

				if t < h[i + 1] - h[i] {
					tCost = (leftCount * (h[i] + t) - dp[i]) * M
					sm2 := leftCount * (h[i] + t + 1) - dp[i]
					sp2 := dp[lastIndex] - dp[i] - rightCount * (h[i] + t + 1)
					t2Cost = (sm2 - sp2) * A + sp2 * M
					topCost = (smTop - spTop) * A + spTop * M
				} else {
					topCost = (spTop - smTop) * R + smTop * M
				}

				localMin = min(bottomCost, min(tCost, min(t2Cost, topCost)))

				minCost = min(minCost, localMin)

			} else {
				bottomCost = A * (bottomSM - bottomSP) + M * bottomSP
				topCost = (smTop - spTop) * A + spTop * M

				localMin = min(bottomCost, topCost)
				minCost = min(minCost, localMin)
			}
		}
	}

	lastCost := int64(h[lastIndex]) * int64(len(h)) - dp[lastIndex] * A

	minCost = min(minCost, lastCost)

	return minCost
}

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

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}

	var minCost int64 = 1e18
	var startCost = (dp[len(dp) - 1] - int64(len(dp)) * h[0]) * R

	for i := 1; i < len(h); i++ {
		if h[i] == h[i - 1] {
			continue
		}
		if A + R < M {
			leftCount := i
			rightCount := len(h) - i

			if int64(leftCount) * A > int64(rightCount) * R {
				if minCost > startCost {
					minCost = startCost
				}

			} else {
				k := h[i] - 1

				sumNeg := k * int64(i) - dp[i - 1]
				sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

				c := sumNeg * A + sumPos * R

				if minCost > c {
					minCost = c
				}
			}

			left := h[i] * (int64(i) + 1) - dp[i]
			right := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

			startCost = left * A + right * R

		} else {
			var left = int64(i)
			var right = int64(len(h) - i)
			sMinus := left * h[i - 1] - dp[i - 1]
			sPlus := dp[len(dp) - 1] - dp[i - 1] - right * h[i - 1]

			if sMinus >= sPlus {
				if int64(len(h)) * A > right * M {
					if minCost > startCost {
						minCost = startCost
					}

				} else {
					k := h[i] - 1

					sumNeg := k * int64(i) - dp[i - 1]
					sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

					c := (sumNeg - sumPos) * A + sumPos * M

					if minCost > c {
						minCost = c
					}
				}

				leftSum := h[i] * (int64(i) + 1) - dp[i]
				rightSum := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

				startCost = (leftSum - rightSum) * A + rightSum * M

			} else {
				if left * M > (left + right) * R {
					diff := sPlus - sMinus
					heightDiff := h[i] - h[i - 1]

					if heightDiff > diff/int64(len(h)) {
						if right * M > (left + right) * A {
							k := h[i] - 1

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c := (sumNeg - sumPos) * A + sumPos * M

							var min int64
							if c > startCost {
								min = startCost
							} else {
								min =  c
							}

							if minCost > min {
								minCost = min
							}

						} else {
							if minCost > startCost {
								minCost = startCost
							}
						}

					} else {
						if minCost > startCost {
							minCost = startCost
						}
					}
				} else {
					diff := sPlus - sMinus
					heightDiff := h[i] - h[i - 1]

					if heightDiff > diff/int64(len(h)) {

						//todo

						if right * M > (left + right) * A {
							k := h[i] - 1

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c1 := (sumNeg - sumPos) * A + sumPos * M

							k = diff/int64(len(h))

							k += h[i - 1]

							sumNeg = k * int64(i) - dp[i - 1]
							sumPos = dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c2 := (sumPos - sumNeg) * R + sumNeg * M

							var min int64

							if c1 > c2 {
								min = c2
							} else {
								min = c1
							}

							if minCost > min {
								minCost = min
							}
						} else {

							k := diff/int64(len(h))

							k += h[i - 1]

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c2 := (sumPos - sumNeg) * R + sumNeg * M

							if minCost > c2 {
								minCost = c2
							}
						}

					} else {
						k := h[i] - 1

						sumNeg := k * int64(i) - dp[i - 1]
						sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

						c := (sumPos - sumNeg) * R + sumNeg * M

						if minCost > c {
							minCost = c
						}
					}
				}

				leftSum := h[i] * (int64(i) + 1) - dp[i]
				rightSum := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

				if leftSum > rightSum {
					startCost = (leftSum - rightSum) * A + rightSum * M
				} else {
					startCost = (rightSum - leftSum) * R + leftSum * M
				}

				if minCost > startCost {
					minCost = startCost
				}

			}
		}

	}

	return minCost
}

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}
	lastIndex := len(dp) - 1

	var minCost int64 = 1e18

	for i := 0; i < len(h) - 1; i++ {
		if h[i] == h[i + 1] {
			continue
		}
		leftCount := int64(i + 1)
		rightCount := int64(len(h) - i - 1)

		if A + R < M {

			var height int64

			if leftCount * A > rightCount * R {
				height = h[i]

			} else {
				height = h[i+1] - 1
			}

			top := height * leftCount
			sm := top - dp[i]
			sp := dp[lastIndex] - dp[i] - rightCount * height

			cost := sm * A + sp * R

			if cost < minCost {
				minCost = cost
			}

		} else {
			bottomSM := leftCount * h[i] - dp[i]
			bottomSP := dp[lastIndex] - dp[i] - rightCount * h[i]
			smTop :=  leftCount * (h[i + 1] - 1) - dp[i]
			spTop := dp[lastIndex] - dp[i] - rightCount * (h[i + 1] - 1)

			var bottomCost int64
			var tCost int64 = 1e18
			var t2Cost int64 = 1e18
			var topCost int64
			var localMin int64

			if bottomSP > bottomSM {
				bottomCost = R * (bottomSP - bottomSM) + M * bottomSM

				diff := bottomSP - bottomSM
				t := diff/(leftCount + rightCount)
				if diff % (leftCount + rightCount) != 0 {
					t++
				}

				if t < h[i + 1] - h[i] {
					tCost = (leftCount * (h[i] + t) - dp[i]) * M
					sm2 := leftCount * (h[i] + t + 1) - dp[i]
					sp2 := dp[lastIndex] - dp[i] - rightCount * (h[i] + t + 1)
					t2Cost = (sm2 - sp2) * A + sp2 * M
					topCost = (smTop - spTop) * A + spTop * M
				} else {
					topCost = (spTop - smTop) * R + smTop * M
				}

				localMin = min(bottomCost, min(tCost, min(t2Cost, topCost)))

				minCost = min(minCost, localMin)

			} else {
				bottomCost = A * (bottomSM - bottomSP) + M * bottomSP
				topCost = (smTop - spTop) * A + spTop * M

				localMin = min(bottomCost, topCost)
				minCost = min(minCost, localMin)
			}
		}
	}

	var lastCost int64 = ((int64(h[lastIndex]) * int64(len(h))) - dp[lastIndex]) * A

	minCost = min(minCost, lastCost)

	return minCost
}

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

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}

	var minCost int64 = 1e18
	var startCost = (dp[len(dp) - 1] - int64(len(dp)) * h[0]) * R

	for i := 1; i < len(h); i++ {
		if h[i] == h[i - 1] {
			continue
		}
		if A + R < M {
			leftCount := i
			rightCount := len(h) - i

			if int64(leftCount) * A > int64(rightCount) * R {
				if minCost > startCost {
					minCost = startCost
				}

			} else {
				k := h[i] - 1

				sumNeg := k * int64(i) - dp[i - 1]
				sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

				c := sumNeg * A + sumPos * R

				if minCost > c {
					minCost = c
				}
			}

			left := h[i] * (int64(i) + 1) - dp[i]
			right := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

			startCost = left * A + right * R

		} else {
			var left = int64(i)
			var right = int64(len(h) - i)
			sMinus := left * h[i - 1] - dp[i - 1]
			sPlus := dp[len(dp) - 1] - dp[i - 1] - right * h[i - 1]

			if sMinus >= sPlus {
				if int64(len(h)) * A > right * M {
					if minCost > startCost {
						minCost = startCost
					}

				} else {
					k := h[i] - 1

					sumNeg := k * int64(i) - dp[i - 1]
					sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

					c := (sumNeg - sumPos) * A + sumPos * M

					if minCost > c {
						minCost = c
					}
				}

				leftSum := h[i] * (int64(i) + 1) - dp[i]
				rightSum := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

				startCost = (leftSum - rightSum) * A + rightSum * M

			} else {
				if left * M > (left + right) * R {
					diff := sPlus - sMinus
					heightDiff := h[i] - h[i - 1]

					if heightDiff > diff/int64(len(h)) {
						if right * M > (left + right) * A {
							k := h[i] - 1

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c := (sumNeg - sumPos) * A + sumPos * M

							var min int64
							if c > startCost {
								min = startCost
							} else {
								min =  c
							}

							if minCost > min {
								minCost = min
							}

						} else {
							if minCost > startCost {
								minCost = startCost
							}
						}

					} else {
						if minCost > startCost {
							minCost = startCost
						}
					}
				} else {
					diff := sPlus - sMinus
					heightDiff := h[i] - h[i - 1]

					if heightDiff > diff/int64(len(h)) {

						//todo

						if right * M > (left + right) * A {
							k := h[i] - 1

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c1 := (sumNeg - sumPos) * A + sumPos * M

							k = diff/int64(len(h))

							sumNeg = k * int64(i) - dp[i - 1]
							sumPos = dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c2 := (sumPos - sumNeg) * R + sumNeg * M

							var min int64

							if c1 > c2 {
								min = c2
							} else {
								min = c1
							}

							if minCost > min {
								minCost = min
							}
						} else {

							k := diff/int64(len(h))

							k += h[i - 1]

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c2 := (sumPos - sumNeg) * R + sumNeg * M

							if minCost > c2 {
								minCost = c2
							}
						}

					} else {
						k := h[i] - 1

						sumNeg := k * int64(i) - dp[i - 1]
						sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

						c := (sumPos - sumNeg) * R + sumNeg * M

						if minCost > c {
							minCost = c
						}
					}
				}

				leftSum := h[i] * (int64(i) + 1) - dp[i]
				rightSum := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

				if leftSum > rightSum {
					startCost = (leftSum - rightSum) * A + rightSum * M
				} else {
					startCost = (rightSum - leftSum) * R + leftSum * M
				}

				if minCost > startCost {
					minCost = startCost
				}

			}
		}

	}

	return minCost
}

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

import (
	"fmt"
	"sort"
)

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
}

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

const MAXN = 100010

var (
	n, a, r, m int
	arr        [MAXN]int
	ar         []int
	sum        [MAXN]int64
)

func find_lm(ar []int, h int) (lt, mt int64) {
	lt_i := sort.Search(len(ar), func(i int) bool { return ar[i] >= h }) - 1
	mt_i := sort.Search(len(ar), func(i int) bool { return ar[i] > h })

	lt, mt = 0, 0
	if lt_i >= 0 {
		lt = sum[lt_i]
	}
	lt = int64(lt_i + 1) * int64(h) - lt;

	mt = sum[n - 1]
	if mt_i > 0 {
		mt -= sum[mt_i - 1]
	}
	mt = mt - int64(n - mt_i) * int64(h);

	return
}

func Tern(mx int, f func(i int) int64) (i int, val int64) {
	lo, hi := 0, mx
	for lo < hi {
		mid := lo + (hi - lo) / 2
		if f(mid) > f(mid + 1) {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	return lo, f(lo)
}

func main() {
	fmt.Scanf("%d %d %d %d", &n, &a, &r, &m)

	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &arr[i])
	}

	ar = arr[:n]
	sort.Ints(ar)
	for i := 0; i < n; i++ {
		sum[i] = int64(ar[i])
		if i > 0 {
			sum[i] += sum[i - 1]
		}
	}

	max_height := arr[n - 1]

	_, cost1 := Tern(max_height, func(h int) int64 {
		lt, mt := find_lm(ar, h)
		return lt*int64(a) + mt*int64(r)
	})

	_, cost2 := Tern(max_height, func(h int) int64 {
		lt, mt := find_lm(ar, h)
		to_move := Min(lt, mt)
		ret := to_move*int64(m) + (lt-to_move)*int64(a) + (mt-to_move)*int64(r)
		//fmt.Println(h, lt, mt, ret)
		return ret
	})

	fmt.Println(Min(cost1, cost2))
}


Sonya was unable to think of a story for this problem, so here comes the formal description.You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.

The first line of the input contains a single integer n (1 ≤ n ≤ 3000) — the length of the array. Next line contains n integer ai (1 ≤ ai ≤ 109).

Print the minimum number of operation required to make the array strictly increasing.

NoteIn the first sample, the array is going to look as follows:2 3 5 6 7 9 11|2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9And for the second sample:1 2 3 4 5|5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12

package main

import (
	"bufio"
	"container/heap"
	. "fmt"
	"io"
	"os"
	"sort"
)

type hp struct{ sort.IntSlice }

func (h hp) Less(i, j int) bool  { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() interface{}   { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }

// github.com/EndlessCheng/codeforces-go
func CF713C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, v int
	Fscan(in, &n)
	ans := int64(0)
	h := hp{}
	for i := 1; i <= n; i++ {
		Fscan(in, &v)
		v -= i
		heap.Push(&h, v)
		if d := h.IntSlice[0] - v; d > 0 {
			ans += int64(d)
			h.IntSlice[0] = v
			heap.Fix(&h, 0)
		}
	}
	Fprint(out, ans)
}

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


Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.A position is good if two conditions hold:   there is no actor in the cell the spotlight is placed to;  there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan. The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.

Print one integer — the number of good positions for placing the spotlight.

NoteIn the first example the following positions are good:  the (1, 1) cell and right direction;  the (1, 1) cell and down direction;  the (1, 3) cell and left direction;  the (1, 3) cell and down direction;  the (1, 4) cell and left direction;  the (2, 2) cell and left direction;  the (2, 2) cell and up direction;  the (2, 2) and right direction;  the (2, 4) cell and left direction. Therefore, there are 9 good positions in this example.

package main

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

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1<<13)
	n, m := ReadInt(reader), ReadInt(reader)
	grid := make([][]int, n)
	rowSum := make([][]int, n)
	for i := 0; i < n; i++ {
		grid[i] = make([]int, m)
		rowSum[i] = make([]int, m)
		for j := 0; j < m; j++ {
			grid[i][j] = ReadInt(reader)
			rowSum[i][j] = grid[i][j]
			if j > 0 {
				rowSum[i][j] += rowSum[i][j-1]
			}
		}
	}
	colSum := make([][]int, m)
	for i := 0; i < m; i++ {
		colSum[i] = make([]int, n)
		for j := 0; j < n; j++ {
			colSum[i][j] = grid[j][i]
			if j > 0 {
				colSum[i][j] += colSum[i][j-1]
			}
		}
	}
	fmt.Println(countPositions(grid, rowSum, colSum))
}

func countPositions(grid, rowSum, colSum [][]int) int {
	count := 0
	for i, row := range grid {
		for j, col := range row {
			if col == 0 {
				count += contains(rowSum[i], 0, j)
				count += contains(rowSum[i], j, len(rowSum[i])-1)
				count += contains(colSum[j], 0, i)
				count += contains(colSum[j], i, len(colSum[j])-1)
			}
		}
	}
	return count
}

func contains(prefixSum []int, start, end int) int {
	total := prefixSum[end]
	if start > 0 {
		total -= prefixSum[start-1]
	}
	if total > 0 {
		return 1
	}
	return 0
}

func ReadInt(reader *bufio.Reader) int {
	b, err := reader.ReadByte()
	for !isValid(b, err) {
		b, err = reader.ReadByte()
	}
	res := 0
	for isValid(b, err) {
		res = res*10 + int(b-'0')
		b, err = reader.ReadByte()
	}
	return res
}

func isValid(b byte, err error) bool {
	return err == nil && '0' <= b && b <= '9'
}

package main

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

func solve() {
    dirs := [][]int{
        []int{0, -1},
        []int{0, 1},
        []int{-1, 0},
        []int{1, 0},
    }
    n, m := readInt(), readInt()
    a := make([][]int, n)
    for i := 0; i < n; i++ {
        a[i] = readIntArray(m)
    }

    mem := make([][][]int, len(dirs))
    for dir := range dirs {
        mem[dir] = make([][]int, n)
        for i := 0; i < n; i++ {
            mem[dir][i] = make([]int, m)
        }
    }

    var dp func(i, j, dir int) bool
    dp = func(i, j, dir int) bool {
        if i < 0 || i >= n || j < 0 || j >= m {
            return false
        }
        m := mem[dir][i][j]
        if m == 0 {
            d, v := dirs[dir], -1
            if a[i][j] == 1 || dp(i+d[0], j+d[1], dir) {
                v = 1
            }
            mem[dir][i][j] = v
        }
        return mem[dir][i][j] == 1
    }

    res := 0
    for dir := range dirs {
        for i := 0; i < n; i++ {
            for j := 0; j < m; j++ {
                if a[i][j] == 0 && dp(i, j, dir) {

                    res++
                }
            }
        }
    }

    fmt.Println(res)
}

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

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

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

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

func min(x, y int) int {
	return x + y - max(x, y)
}

// 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 readArray(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = readInt()
	}
	return res
}

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

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

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

	var n, m int
	fmt.Fscanf(bufin, "%d %d\n", &n, &m)
	a := make([][]int, n+2)
	left := make([][]int, n+2)
	right := make([][]int, n+2)
	up := make([][]int, n+2)
	down := make([][]int, n+2)
	for i := 0; i <= n+1; i++ {
		a[i] = make([]int, m+2)
		left[i] = make([]int, m+2)
		right[i] = make([]int, m+2)
		up[i] = make([]int, m+2)
		down[i] = make([]int, m+2)
	}
	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			fmt.Fscanf(bufin, "%d\n", &a[i][j])
		}
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if (left[i][j-1] == 1) || (a[i][j-1] == 1) {
				left[i][j] = 1
			}
		}
		for j := m; j >= 1; j-- {
			if (right[i][j+1] == 1) || (a[i][j+1] == 1) {
				right[i][j] = 1
			}
		}
	}

	for j := 1; j <= m; j++ {
		for i := 1; i <= n; i++ {
			if (up[i-1][j] == 1) || (a[i-1][j] == 1) {
				up[i][j] = 1
			}
		}
		for i := n; i >= 1; i-- {
			if (down[i+1][j] == 1) || (a[i+1][j] == 1) {
				down[i][j] = 1
			}
		}
	}

	res := 0
	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if a[i][j] == 0 {
				res += left[i][j]
				res += right[i][j]
				res += up[i][j]
				res += down[i][j]
			}
		}
	}

	fmt.Fprintf(bufout, "%d\n", res)
}

package main

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

func btoi(b bool) int {
	if b {
		return 1
	} else {
		return 0
	}
}
func main() {
	var n, m int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &n, &m)
	pos := make([]bool, n*m)
	for i := 0; i < n; i++ {
		for k := 0; k < m; k++ {
			index := i*m + k
			fmt.Fscan(in, &pos[index])
		}
	}

	flagrow := make([]bool, n)
	flagcolumn := make([]bool, m)
	ans := 0
	for index := 0; index < n*m; index++ {
		i := index / m
		k := index % m
		if pos[index] {
			flagrow[i] = true
			flagcolumn[k] = true
		} else {
			ans += btoi(flagrow[i])
			ans += btoi(flagcolumn[k])
		}
	}

	flagrow = make([]bool, n)
	flagcolumn = make([]bool, m)
	for index := n*m - 1; index >= 0; index-- {
		i := index / m
		k := index % m
		if pos[index] {
			flagrow[i] = true
			flagcolumn[k] = true
		} else {
			ans += btoi(flagrow[i])
			ans += btoi(flagcolumn[k])
		}
	}

	fmt.Println(ans)
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var word string
	fmt.Scan(&word)
	fmt.Println(replace(word))
}

func replace(word string) string {
	ans := ""
	for i := 0; i < len(word); i++ {
		if word[i] == 'o' {
			last := findLast(word, i)
			if last > i {
				ans += "***"
				i = last
			} else {
				ans += string(word[i])
			}
		} else {
			ans += string(word[i])
		}
	}
	return string(ans)
}

func findLast(word string, pos int) int {
	for i := pos; i < len(word); i++ {
		expected := byte('o')
		if (i-pos)&1 == 1 {
			expected = 'g'
		}
		if word[i] != expected {
			if word[i-1] == 'o' {
				return i - 1
			} else {
				return i - 2
			}
		}
	}
	return len(word) - 1
}


You are given an unweighted tree with $$$n$$$ vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices $$$a, b, c$$$ on this tree such that the number of edges which belong to at least one of the simple paths between $$$a$$$ and $$$b$$$, $$$b$$$ and $$$c$$$, or $$$a$$$ and $$$c$$$ is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.

The first line contains one integer number $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree.  Next $$$n - 1$$$ lines describe the edges of the tree in form $$$a_i, b_i$$$ ($$$1 \le a_i$$$, $$$b_i \le n$$$, $$$a_i \ne b_i$$$). It is guaranteed that given graph is a tree.

In the first line print one integer $$$res$$$ — the maximum number of edges which belong to at least one of the simple paths between $$$a$$$ and $$$b$$$, $$$b$$$ and $$$c$$$, or $$$a$$$ and $$$c$$$. In the second line print three integers $$$a, b, c$$$ such that $$$1 \le a, b, c \le n$$$ and $$$a \ne, b \ne c, a \ne c$$$. If there are several answers, you can print any.

NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices $$$1, 5, 6$$$ then the path between $$$1$$$ and $$$5$$$ consists of edges $$$(1, 2), (2, 3), (3, 4), (4, 5)$$$, the path between $$$1$$$ and $$$6$$$ consists of edges $$$(1, 2), (2, 3), (3, 4), (4, 6)$$$ and the path between $$$5$$$ and $$$6$$$ consists of edges $$$(4, 5), (4, 6)$$$. The union of these paths is $$$(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)$$$ so the answer is $$$5$$$. It can be shown that there is no better answer.

package main

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

type BfsNode struct {
	Node, Count int
}

func dfs(node int, adj [][]int) int {
	seen := make([]bool, len(adj))
	maxCount := 0
	var bestNode int

	var dfsInner func(int, int)
	dfsInner = func(node int, count int) {
		seen[node] = true
		count += 1

		for _, neighbour := range adj[node] {
			if seen[neighbour] {
				continue
			}

			// update furthest node
			if count > maxCount {
				maxCount = count
				bestNode = neighbour
			}

			dfsInner(neighbour, count)
		}
	}

	// call recursive inner
	dfsInner(node, 0)
	return bestNode
}

func path(a int, b int, adj [][]int) []int {
	// run dfs from a
	seen := make([]bool, len(adj))
	path := make([]int, 0, 2) // source and destination

	var dfsInner func(int) bool
	dfsInner = func(node int) bool {
		seen[node] = true

		if node == b {
			path = append(path, node)
			return true
		}

		for _, neighbour := range adj[node] {
			if seen[neighbour] {
				continue
			}

			if dfsInner(neighbour) {
				path = append(path, node)
				return true
			}
		}

		return false
	}

	dfsInner(a)
	return path
}

func bfs(node int, adj [][]int) (int, int) {
	seen := make([]bool, len(adj))
	q := []BfsNode{BfsNode{node, 0}}
	count := 0

	for len(q) > 0 {
		cur := q[0]
		q = q[1:]
		if seen[cur.Node] {
			continue
		}
		node = cur.Node
		count = cur.Count
		seen[node] = true

		for _, neighbour := range adj[node] {
			if seen[neighbour] {
				continue
			}

			q = append(q, BfsNode{neighbour, count + 1})
		}
	}

	return node, count
}

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

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

	adj := make([][]int, n+1)
	for i := 0; i < n; i++ {
		adj[i+1] = make([]int, 0)
	}

	for i := 0; i < n-1; i++ {
		scanner.Scan()
		a, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		b, _ := strconv.Atoi(scanner.Text())

		adj[a] = append(adj[a], b)
		adj[b] = append(adj[b], a)
	}

	// find first leaf by dfs
	leaf := dfs(1, adj)
	// find opposite node to leaf
	opp := dfs(leaf, adj)

	// get the diameter path
	diam := path(leaf, opp, adj)

	// run bfs from diameter nodes to find the furthest node from all
	// use a new virtual node for multiple source
	adj = append(adj, diam)
	third, dist := bfs(n+1, adj)

	// if the diameter spans the whole tree, bfs will give us one of the ends
	// so just pick any node that isn't one of those two
	for third == leaf || third == opp {
		third += 1
		if third > n {
			third = 1
		}
	}

	// edges on diameter = nodes - 1
	// distance from diameter - virtual node
	ans := len(diam) + dist - 2
	if ans >= n {
		ans = n - 1 // can't be any larger than the number of edges!
	}

	fmt.Println(ans)
	fmt.Println(leaf, opp, third)
}

package main

import (
	"fmt"
    "os"
    "io/ioutil"
    //~ "time"
)

var stdin_bytes []byte

func read_int() int {
    if len(stdin_bytes) == 0 {
        stdin_bytes, _ = ioutil.ReadAll(os.Stdin)
    }
    for !('0' <= stdin_bytes[0] && stdin_bytes[0] <= '9') {
        stdin_bytes = stdin_bytes[1:]
    }
    x := 0
    for '0' <= stdin_bytes[0] && stdin_bytes[0] <= '9' {
        x = 10 * x + int(stdin_bytes[0] - '0')
        stdin_bytes = stdin_bytes[1:]
    }
    return x
}

func read_tree() [][]int {
    num_nodes := read_int()
    graph := make([][]int, num_nodes)
    for i := 0; i < (num_nodes - 1); i++ {
        n1 := read_int() - 1
        n2 := read_int() - 1
        graph[n1] = append(graph[n1], n2)
        graph[n2] = append(graph[n2], n1)
    }
    return graph
}

func bfs(graph [][]int, start_node int) []int {
    distances := make([]int, len(graph))
    for i := 0; i < len(graph); i++ {
        distances[i] = -1;
    }
    distances[start_node] = 0;
    queue := make([]int, 0, len(graph))
    queue = append(queue, start_node)
    for len(queue) > 0 {
        current_node := queue[0]
        queue = queue[1:]
        for _, neighbor := range graph[current_node] {
            if distances[neighbor] == -1 {
                distances[neighbor] = distances[current_node] + 1;
                queue = append(queue, neighbor)
            }
        }
    }
    return distances
}

func max_distance_node(distances []int, exclude_nodes []int) (
            node int, distance int) {
    best_node, max_distance := -1, -1
    for node, distance := range distances {
        if max_distance == -1 || distance > max_distance {
            excluded := false
            for _, excluded_node := range(exclude_nodes) {
                if node == excluded_node {
                    excluded = true
                    break
                }
            }
            if !excluded {
                best_node, max_distance = node, distance
            }
        }
    }
    return best_node, max_distance
}

func sum_distances(distances_a []int, distances_b []int) []int {
    distances_sum := make([]int, len(distances_a))
    for i, da := range(distances_a) {
        distances_sum[i] = da + distances_b[i]
    }
    return distances_sum
}

func main() {
    //~ start := time.Now()
    tree := read_tree()
    //~ fmt.Printf("read: %s\n", time.Since(start))
    //~ start = time.Now()
    //~ fmt.Println(tree)
    distances_0 := bfs(tree, 0)
    node_a, _ := max_distance_node(distances_0, []int{})
    distances_a := bfs(tree, node_a)
    node_b, dist_a_b := max_distance_node(distances_a, []int{})
    distances_b := bfs(tree, node_b)
    distances_sum := sum_distances(distances_a, distances_b)
    node_c, dist_c_ab := max_distance_node(distances_sum,
                                           []int{node_a, node_b})
    num_edges := (dist_a_b + dist_c_ab) / 2
    //~ fmt.Printf("compute: %s\n", time.Since(start))
    fmt.Println(num_edges)
    fmt.Println(node_a + 1, node_b + 1, node_c + 1)
}

package main

import (
	"fmt"
    "os"
    "io/ioutil"
    //~ "time"
)

type edge struct {
    u int
    v int
}

var stdin_bytes []byte

func read_int() int {
    if len(stdin_bytes) == 0 {
        stdin_bytes, _ = ioutil.ReadAll(os.Stdin)
    }
    for !('0' <= stdin_bytes[0] && stdin_bytes[0] <= '9') {
        stdin_bytes = stdin_bytes[1:]
    }
    x := 0
    for '0' <= stdin_bytes[0] && stdin_bytes[0] <= '9' {
        x = 10 * x + int(stdin_bytes[0] - '0')
        stdin_bytes = stdin_bytes[1:]
    }
    return x
}

func read_edges() (num_nodes int, edges []edge) {
    num_nodes = read_int()
    edges = make([]edge, num_nodes - 1)
    for i := 0; i < (num_nodes - 1); i++ {
        u, v := read_int() - 1, read_int() - 1
        edges[i] = edge {u, v}
    }
    return num_nodes, edges
}

func compute_degrees(num_nodes int, edges []edge) []int {
    degrees := make([]int, num_nodes)
    for _, e := range edges {
        degrees[e.u] += 1
        degrees[e.v] += 1
    }
    return degrees
}

func build_graph(degrees []int, edges []edge) [][]int {
    start := 0
    starts := make([]int, len(degrees))
    for node, degree := range degrees {
        starts[node] = start
        start += degree
    }
    ends := make([]int, len(degrees))
    copy(ends, starts)
    //~ fmt.Println(degrees, starts, ends)
    graph := make([]int, 2 * len(degrees))
    for _, e := range edges {
        graph[ends[e.u]] = e.v
        ends[e.u] += 1
        graph[ends[e.v]] = e.u
        ends[e.v] += 1
    }
    graph_sliced := make([][]int, len(degrees))
    for node, start := range starts {
        end := ends[node]
        graph_sliced[node] = graph[start:end]
    }
    return graph_sliced
}

func bfs(graph [][]int, start_node int) []int {
    distances := make([]int, len(graph))
    for i := 0; i < len(graph); i++ {
        distances[i] = -1;
    }
    distances[start_node] = 0;
    queue := make([]int, 0, len(graph))
    queue = append(queue, start_node)
    for len(queue) > 0 {
        current_node := queue[0]
        queue = queue[1:]
        for _, neighbor := range graph[current_node] {
            if distances[neighbor] == -1 {
                distances[neighbor] = distances[current_node] + 1;
                queue = append(queue, neighbor)
            }
        }
    }
    return distances
}

func max_distance_node(distances []int, exclude_nodes []int) (
            node int, distance int) {
    best_node, max_distance := -1, -1
    for node, distance := range distances {
        if max_distance == -1 || distance > max_distance {
            excluded := false
            for _, excluded_node := range(exclude_nodes) {
                if node == excluded_node {
                    excluded = true
                    break
                }
            }
            if !excluded {
                best_node, max_distance = node, distance
            }
        }
    }
    return best_node, max_distance
}

func sum_distances(distances_a []int, distances_b []int) []int {
    distances_sum := make([]int, len(distances_a))
    for i, da := range(distances_a) {
        distances_sum[i] = da + distances_b[i]
    }
    return distances_sum
}

func main() {
    //~ start := time.Now()
    num_nodes, edges := read_edges()
    //~ fmt.Println(num_nodes, edges)
    degrees := compute_degrees(num_nodes, edges)
    tree := build_graph(degrees, edges)
    //~ fmt.Printf("read: %s\n", time.Since(start))
    //~ start = time.Now()
    //~ fmt.Println(tree)
    distances_0 := bfs(tree, 0)
    node_a, _ := max_distance_node(distances_0, []int{})
    distances_a := bfs(tree, node_a)
    node_b, dist_a_b := max_distance_node(distances_a, []int{})
    distances_b := bfs(tree, node_b)
    distances_sum := sum_distances(distances_a, distances_b)
    node_c, dist_c_ab := max_distance_node(distances_sum,
                                           []int{node_a, node_b})
    num_edges := (dist_a_b + dist_c_ab) / 2
    //~ fmt.Printf("compute: %s\n", time.Since(start))
    fmt.Println(num_edges)
    fmt.Println(node_a + 1, node_b + 1, node_c + 1)
}

package main

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

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

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

	t := make(map[int][]int)
	for i := 0; i < n-1; i++ {
		var u, v int
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		t[u] = append(t[u], v)
		t[v] = append(t[v], u)
	}

	a, b, c, d := findBest3Points(t)
	fmt.Printf("%d\n%d %d %d\n", d, a, b, c)
}

type T struct {
	t    map[int][]int
	dist map[int]int
	par  map[int]int
}

func newTree(tree map[int][]int) *T {
	t := new(T)
	t.t = tree
	t.dist = make(map[int]int)
	t.par = make(map[int]int)
	return t
}

func (t *T) init() {
	t.dist = make(map[int]int)
	t.par = make(map[int]int)
}

func findBest3Points(tree map[int][]int) (int, int, int, int) {
	t := newTree(tree)

	r, _ := t.dfs(1, 0)
	leaf, diam := t.dfs(r, 0)

	inChain := make(map[int]bool)

	cur := leaf
	for cur != r {
		inChain[cur] = true
		cur = t.par[cur]
	}
	inChain[r] = true

	furthest, x := 0, t.par[leaf]

	cur = leaf
	for cur != r {
		for _, ch := range t.t[cur] {
			if inChain[ch] {
				continue
			}
			y, d := t.dfs(ch, cur)
			if furthest < d+1 {
				furthest = d + 1
				x = y
			}
		}
		cur = t.par[cur]
	}

	return r, leaf, x, diam + furthest
}

func (t *T) dfs(r, p int) (int, int) {
	t.par[r] = p

	longest, x := 0, r
	for _, ch := range t.t[r] {
		if ch != p {
			leaf, d := t.dfs(ch, r)
			if longest < d+1 {
				longest = d + 1
				x = leaf
			}
		}
	}

	return x, longest
}

package main

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

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

	var n, v, w, u, maxD, ans int
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 0; i < n-1; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	var f func(v, fa, d int)
	f = func(v, fa, d int) {
		if d > maxD {
			maxD = d
			u = v
		}
		for _, w := range g[v] {
			if w != fa {
				f(w, v, d+1)
			}
		}
	}
	maxD = -1
	f(0, -1, 0)
	dv := u
	maxD = -1
	f(dv, -1, 0)
	dw := u

	onPath := make([]bool, n)
	var f2 func(v, fa int) bool
	f2 = func(v, fa int) bool {
		if v == dw {
			onPath[v] = true
			return true
		}
		for _, w := range g[v] {
			if w != fa {
				if f2(w, v) {
					onPath[v] = true
					ans++
					return true
				}
			}
		}
		return false
	}
	f2(dv, -1)

	maxD = 0
	u = -1
	f = func(v, fa, d int) {
		if d > maxD {
			maxD = d
			u = v
		}
		for _, w := range g[v] {
			if w != fa {
				if onPath[w] {
					f(w, v, 0)
				} else {
					f(w, v, d+1)
				}
			}
		}
	}
	f(dv, -1, 0)
	if u == -1 {
		if dv > dw {
			dv, dw = dw, dv
		}
		u = 0
		if dv == 0 {
			u = 1
		}
		if dw == 1 {
			u = 2
		}
	}
	Fprintln(out, ans+maxD)
	Fprintln(out, dv+1, dw+1, u+1)
}

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

package main

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

type BfsNode struct {
	Node, Count int
}

func dfs(node int, adj [][]int) int {
	seen := make([]bool, len(adj))
	maxCount := 0
	var bestNode int

	var dfsInner func(int, int)
	dfsInner = func(node int, count int) {
		seen[node] = true
		count += 1

		for _, neighbour := range adj[node] {
			if seen[neighbour] {
				continue
			}

			// update furthest node
			if count > maxCount {
				maxCount = count
				bestNode = neighbour
			}

			dfsInner(neighbour, count)
		}
	}

	// call recursive inner
	dfsInner(node, 0)
	return bestNode
}

func path(a int, b int, adj [][]int) []int {
	// run dfs from a
	seen := make([]bool, len(adj))
	path := make([]int, 0, 2) // source and destination

	var dfsInner func(int) bool
	dfsInner = func(node int) bool {
		seen[node] = true

		if node == b {
			path = append(path, node)
			return true
		}

		for _, neighbour := range adj[node] {
			if seen[neighbour] {
				continue
			}

			if dfsInner(neighbour) {
				path = append(path, node)
				return true
			}
		}

		return false
	}

	dfsInner(a)
	return path
}

func bfs(node int, adj [][]int) (int, int) {
	seen := make([]bool, len(adj))
	q := []BfsNode{BfsNode{node, 0}}
	count := 0

	for len(q) > 0 {
		cur := q[0]
		q = q[1:]
		if seen[cur.Node] {
			continue
		}
		node = cur.Node
		count = cur.Count
		seen[node] = true

		for _, neighbour := range adj[node] {
			if seen[neighbour] {
				continue
			}

			q = append(q, BfsNode{neighbour, count + 1})
		}
	}

	return node, count
}

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

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

	adj := make([][]int, n+1)
	for i := 0; i < n; i++ {
		adj[i+1] = make([]int, 0)
	}

	for i := 0; i < n-1; i++ {
		scanner.Scan()
		a, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		b, _ := strconv.Atoi(scanner.Text())

		adj[a] = append(adj[a], b)
		adj[b] = append(adj[b], a)
	}

	// find first leaf by dfs
	leaf := dfs(1, adj)
	// find opposite node to leaf
	opp := dfs(leaf, adj)

	// get the diameter path
	diam := path(leaf, opp, adj)

	// run bfs from diameter nodes to find the furthest node from all
	// use a new virtual node for multiple source
	adj = append(adj, diam)
	third, dist := bfs(n+1, adj)

	// edges on diameter = nodes - 1
	// distance from diameter - virtual node
	ans := len(diam) + dist - 2
	if ans >= n {
		ans = n - 1 // can't be any larger than the number of edges!
	}

	fmt.Println(ans)
	fmt.Println(leaf, opp, third)
}

package main

import (
	"fmt"
    "os"
    "io/ioutil"
    //~ "time"
)

var stdin_bytes []byte

func read_int() int {
    if len(stdin_bytes) == 0 {
        stdin_bytes, _ = ioutil.ReadAll(os.Stdin)
    }
    for !('0' <= stdin_bytes[0] && stdin_bytes[0] <= '9') {
        stdin_bytes = stdin_bytes[1:]
    }
    x := 0
    for '0' <= stdin_bytes[0] && stdin_bytes[0] <= '9' {
        x = 10 * x + int(stdin_bytes[0] - '0')
        stdin_bytes = stdin_bytes[1:]
    }
    return x
}

func read_tree() [][]int {
    num_nodes := read_int()
    graph := make([][]int, num_nodes)
    for i := 0; i < (num_nodes - 1); i++ {
        n1 := read_int() - 1
        n2 := read_int() - 1
        graph[n1] = append(graph[n1], n2)
        graph[n2] = append(graph[n2], n1)
    }
    return graph
}

func bfs(graph [][]int, start_node int) []int {
    distances := make([]int, len(graph))
    for i := 0; i < len(graph); i++ {
        distances[i] = -1;
    }
    distances[start_node] = 0;
    queue := make([]int, 0, len(graph))
    queue = append(queue, start_node)
    for len(queue) > 0 {
        current_node := queue[0]
        queue = queue[1:]
        for _, neighbor := range graph[current_node] {
            if distances[neighbor] == -1 {
                distances[neighbor] = distances[current_node] + 1;
                queue = append(queue, neighbor)
            }
        }
    }
    return distances
}

func max_distance_node(distances []int, exclude_nodes []int) (
            node int, distance int) {
    best_node, max_distance := -1, -1
    for node, distance := range distances {
        if max_distance == -1 || distance > max_distance {
            excluded := false
            for _, excluded_node := range(exclude_nodes) {
                if node == excluded_node {
                    excluded = true
                    break
                }
            }
            if !excluded {
                best_node, max_distance = node, distance
            }
        }
    }
    return best_node, max_distance
}

func sum_distances(distances_a []int, distances_b []int) []int {
    distances_sum := make([]int, len(distances_a))
    for i, da := range(distances_a) {
        distances_sum[i] = da + distances_b[i]
    }
    return distances_sum
}

func main() {
    //~ start := time.Now()
    tree := read_tree()
    //~ fmt.Printf("read: %s\n", time.Since(start))
    //~ start = time.Now()
    //~ fmt.Println(tree)
    distances_0 := bfs(tree, 0)
    node_a, _ := max_distance_node(distances_0, []int{})
    distances_a := bfs(tree, node_a)
    node_b, dist_a_b := max_distance_node(distances_a, []int{})
    distances_b := bfs(tree, node_b)
    distances_sum := sum_distances(distances_a, distances_b)
    node_c, dist_c_ab := max_distance_node(distances_sum,
                                           []int{node_a, node_b})
    num_edges := (dist_a_b + dist_c_ab) / 2
    //~ fmt.Printf("compute: %s\n", time.Since(start))
    fmt.Println(num_edges)
    fmt.Println(node_a, node_b, node_c)
}


Dreamoon is a big fan of the Codeforces contests.One day, he claimed that he will collect all the places from $$$1$$$ to $$$54$$$ after two more rated contests. It's amazing!Based on this, you come up with the following problem:There is a person who participated in $$$n$$$ Codeforces rounds. His place in the first round is $$$a_1$$$, his place in the second round is $$$a_2$$$, ..., his place in the $$$n$$$-th round is $$$a_n$$$.You are given a positive non-zero integer $$$x$$$.Please, find the largest $$$v$$$ such that this person can collect all the places from $$$1$$$ to $$$v$$$ after $$$x$$$ more rated contests.In other words, you need to find the largest $$$v$$$, such that it is possible, that after $$$x$$$ more rated contests, for each $$$1 \leq i \leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.For example, if $$$n=6$$$, $$$x=2$$$ and $$$a=[3,1,1,5,7,10]$$$ then answer is $$$v=5$$$, because if on the next two contest he will take places $$$2$$$ and $$$4$$$, then he will collect all places from $$$1$$$ to $$$5$$$, so it is possible to get $$$v=5$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains two integers $$$n, x$$$ ($$$1 \leq n, x \leq 100$$$). The second line contains $$$n$$$ positive non-zero integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$).

For each test case print one line containing the largest $$$v$$$, such that it is possible that after $$$x$$$ other contests, for each $$$1 \leq i \leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.

NoteThe first test case is described in the statement.In the second test case, the person has one hundred future contests, so he can take place $$$1,2,\ldots,99$$$ and place $$$101$$$ on them in some order, to collect places $$$1,2,\ldots,101$$$.

package main

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

var r__ *bufio.Reader = bufio.NewReader(os.Stdin)
var w__ *bufio.Writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{})  { fmt.Fscanf(r__, f, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(w__, f, a...) }
func fflush()                           { w__.Flush() }

func solve() {
	var n, x int
	var data [102]bool
	scanf("%d %d\n", &n, &x)

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

	i := 0
	for {
		i++

		if i > 100 {

			x--

			if x > 0 {
				continue

			} else {
				break
			}
		}

		curr := data[i]

		if !curr {
			data[i] = true
			x--

			if x == 0 {
				for data[i+1] {
					i = i + 1

				}
				break
			}

		} else {

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

}

func main() {
	defer fflush()

	var T, i uint64
	scanf("%d\n", &T)
	for i = 0; i < T; i++ {
		solve()
	}

}

package main

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

func main() {

	t := ScanInt()
	for ; t > 0; t-- {
		n := ScanInt()
		k := ScanInt()
		isUsed := make([]bool, 1000)
		for i := 0; i < n; i++ {
			isUsed[ScanInt()] = true
		}
		i := 1
		for ; k > 0; i++ {
			if isUsed[i] {
				continue
			}
			k--
		}
		for ; ; i++ {
			if !isUsed[i] {
				break
			}
		}
		fmt.Println(i-1)

	}
}

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

var O chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var P func(a ...interface{}) (n int, err error)

func init() {
	P = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	O = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func ScanWord() string { in.Scan(); return in.Text() }
func ScanInt() int     { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInt64() int64 { i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i }
func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt()
	}
	return arr
}
func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

/*********************** Utils ***********************/

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args []int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args []int64) int64 { mn, _ := MnMx(args); return mn }
func Mx(args []int64) int64 { _, mx := MnMx(args); return mx }
func LCM(a, b int64) int64  { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}
func MinimumMaximum(a, b int64) (int64, int64) {
	if a < b {
		return a, b
	}
	return b, a

}
func Minimum(a, b int64) int64 {
	min, _ := MinimumMaximum(a, b)
	return min

}
func Maximum(a, b int64) int64 {
	_, max := MinimumMaximum(a, b)
	return max

}

package main

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

func main() {

	t := ScanInt()
	for ; t > 0; t-- {
		n := ScanInt()
		k := ScanInt()
		isUsed := make([]bool, 1000)
		for i := 0; i < n; i++ {
			isUsed[ScanInt()] = true
		}
		i := 1
		for ; ; i++ {
			if isUsed[i] {
				continue
			} else if k == 0 {
				break
			}
			k--
		}
		fmt.Println(i - 1)

	}
}

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

var O chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var P func(a ...interface{}) (n int, err error)

func init() {
	P = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	O = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func ScanWord() string { in.Scan(); return in.Text() }
func ScanInt() int     { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInt64() int64 { i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i }
func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt()
	}
	return arr
}
func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

/*********************** Utils ***********************/

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args []int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args []int64) int64 { mn, _ := MnMx(args); return mn }
func Mx(args []int64) int64 { _, mx := MnMx(args); return mx }
func LCM(a, b int64) int64  { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}
func MinimumMaximum(a, b int64) (int64, int64) {
	if a < b {
		return a, b
	}
	return b, a

}
func Minimum(a, b int64) int64 {
	min, _ := MinimumMaximum(a, b)
	return min

}
func Maximum(a, b int64) int64 {
	_, max := MinimumMaximum(a, b)
	return max

}

package main

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

var reader = bufio.NewReader(os.Stdin)
var 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 scanAllStr() (string, error) {
	str, err := reader.ReadString('\n')
	if err != nil {
		return "", err
	}
	return strings.TrimRight(str, "\n\r"), nil
}

func main() {
	var casesNumb byte
	scanf("%d\n", &casesNumb)

	for i := byte(0); i < casesNumb; i++ {
		var n, x int
		scanf("%d %d\n", &n, &x)

		strA, err := scanAllStr()
		if err != nil {
			panic(err)
		}

		aStrArr := strings.Split(strA, " ")
		a := make([]int, len(aStrArr))
		for i, strA := range aStrArr {
			var err error
			a[i], err = strconv.Atoi(strA)
			if err != nil {
				fmt.Println(err)
				panic(err)
			}
		}
		sort.Ints(a)

		previous := 0
		v := 0
		for _, place := range a {
			if place == previous {
				continue
			}
			if place-1 > previous+x {
				v = previous + x
				break
			}
			x -= place - previous - 1
			previous = place
		}
		if v == 0 {
			v = previous + x
		}

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

	writer.Flush()
}

package main

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

const MaxV = 201

var(
	achieve [MaxV]bool
)

func solve() {
	n, x := scanInt(), scanInt()
	for i := 1; i <= n + x; i++ {
		achieve[i] = false
	}
	for i := 1; i <= n; i++ {
		ranking := scanInt()
		achieve[ranking] = true
	}
	for k := n + x; k > 0; k-- {
		v := 0
		for i := 1; i <= k; i++ {
			if achieve[i] == false {
				v++
			}
		}
		if v <= x {
			_, _ = printFmt(k)
			return
		}
	}
}

func main() {
	T := scanInt()
	for ; T > 0; T-- {
		solve()
	}
}
/*********************** I/O ***********************/

var channelType chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var printFmt func(a ...interface{}) (n int, err error)

func init() {
	printFmt = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	channelType = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

		for line := range channelType {
			_, _ = writer.WriteString(line + "\n")
		}
	}()
}

func scanString() string {in.Scan(); return in.Text() }
func scanInt() int {i, _ := strconv.Atoi(scanString()); return i}
func scanInt64() int64 {i, _ := strconv.ParseInt(scanString(), 10, 64); return i}
func scanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = scanString()}; return s}
func scanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = scanInt()}; return arr}
func scanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = scanInt64()}; return arr}

/*********************** Utils ***********************/

func stringEquivalent(v interface{}) string {return fmt.Sprintf("%v", v)}
func spaceSeperatedStringFromArray(a []int) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.Itoa(a[i]) + " ")}; return sb.String()}
func spaceSeperatedStringFromArray64(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func minMaxFromArray(args ...int64) (int64, int64) {minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64); for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64 {return a / gcdCalculation(a, b) * b}
func gcdCalculation(a, b int64) int64 {if a == 0 {return b}; return gcdCalculation(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func absoluteValue(x int64) int64 {if x < 0 {return -x}; return x}
func min(args ...int) int { mn, _ := MnMx(args...); return mn }
func max(args ...int) int { _, mx := MnMx(args...); return mx }
func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

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
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)
	T := NextInt()

	a := make([]int, 100010)
	for t := 0; t < T; t++ {
		n, x := NextInt(), NextInt()

		for i := 0; i < n; i++ {
			a[i] = NextInt()
		}
		sort.Ints(a[:n])
		last := 0
		for i := 0; i < n; i++ {
			// stderr("i", i, a[i], last, x)
			if a[i] == last+1 {
				last = a[i]
			} else if a[i] > last {
				t := min(max(a[i]-last-1, 0), x)
				x -= t
				last += t
				if a[i] == last+1 {
					last++
				}
				if last != a[i] {
					break
				}
			}
		}
		if x > 0 {
			last += x
		}
		fmt.Fprintln(out, last)
	}

}

package main

import "fmt"

func main() {
	var t, n, x int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n, &x)
		arr := make([]int, n)
		flag := make(map[int]bool)
		for j := 0; j < n; j++ {
			fmt.Scan(&arr[j])
			flag[arr[j]] = true
		}
		for j := n + x; j >= 0; j-- {
			var v int
			for k := 1; k <= j; k++ {
				if flag[k] == false {
					v++
				}
			}
			if v <= x {
				fmt.Printf("%d\n", j)
				break
			}
		}
	}
}

package main

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

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

	var t, n, x int
	fmt.Fscanf(in, "%d\n", &t)
	for ;t>0;t-- {
		fmt.Fscanf(in, "%d %d\n",&n, &x)
		a := make([]int,n)
		for i := 0 ; i < n ; i ++ {
			fmt.Fscanf(in, "%d",&a[i])
		}
		fmt.Fscanf(in,"\n")
		b := make([]int,202)
		for i := 0 ; i < n ; i ++{
			b[a[i]] = 1
		}
		output := 0
		for i := 1 ; i < 202 ; i ++ {
			if b[i] == 0 {
				b[i] = 1
				x --
			}
			if x == -1 {
				output = i - 1
				break
			}
		}
		fmt.Println(output)
	}

}

package main

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

func main() {
	// scanner := bufio.NewScanner(os.Stdin)
	var T int
	fmt.Scan(&T)
	for ; T>0; T-- {
		solve()
	}
}
func solve() {
	var n,x int;
		fmt.Scan(&n,&x);
		hm:=make(map[int]bool);
		arr:=make([]int,n)
		for i:=0;i<n;i++ {
			fmt.Scan(&arr[i])
			hm[arr[i]]=true
		}
		for i:=n+x;i>0;i--{
			var v int;
			for j:=1;j<=i;j++ {
				if(hm[j]==false){
					v++
				}
			}
			if(v<=x){
				fmt.Printf("%d \n",i)
				return;
			}
		}
}

package main
import "fmt"

func main() {
	var T, n, x, aux int
	fmt.Scan(&T)

	for ;T > 0; T-- {
		cont := 0
		bucket := make([]int, 205)
		fmt.Scan(&n, &x)

		for i := 0; i < n; i++ {
			fmt.Scan(&aux)
			bucket[aux]++
		}

		for i, v := range bucket {
			if cont == x && bucket[i] == 0 {
				fmt.Println(i-1)
				break
			}
			if i != 0 && v == 0 {
				cont++
				bucket[i] = 1
			}
		}
	}
}

package main

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

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

	solve := func() (ans int) {
		var n, x int
		Fscan(in, &n, &x)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		sort.Ints(a)
		ans = x
		vis := make([]bool, 400)
	o:

		for {
			for _, v := range a {
				if vis[v] {
					  continue
				}

				if v <= ans {
					vis[v]=true
					ans++
					continue o
				}
			}
			break
		}
		for _, v := range a {
			vis[v]=true
		}
		for i:=ans+1;vis[i];i++{
			ans=i
		}

		return ans
	}

	var t int
	Fscan(in, &t)
	for _case := 1; _case <= t; _case++ {
		Fprintln(out, solve())
	}
}

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

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 main() {
	for t := scanInt(); t > 0; t-- {
		n, x := scanInt(), scanInt()
		a := scanInts(n)
		b := make([]bool, 1000)
		for i := 0; i < n; i++ {
			b[a[i]] = true
		}

		res := 0
		for i := 1; i < len(b); i++ {
			if b[i] {
				res = i
			} else if x > 0 {
				res = i
				x--
			} else {
				break
			}
		}
		fmt.Println(res)
	}
}

package main

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

var r__ *bufio.Reader = bufio.NewReader(os.Stdin)
var w__ *bufio.Writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{})  { fmt.Fscanf(r__, f, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(w__, f, a...) }
func fflush()                           { w__.Flush() }

func solve() {
	var n, x int
	var data [102]bool
	scanf("%d %d\n", &n, &x)

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

	i := 0
	for {
		i++

		if i > 100 {

			x--

			if x > 0 {
				continue

			} else {
				break
			}
		}

		curr := data[i]

		if !curr {
			data[i] = true
			x--

			if x == 0 {
				if data[i+1] {
					i = i + 1
					break
				}
				break
			}

		} else {

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

}

func main() {
	defer fflush()

	var T, i uint64
	scanf("%d\n", &T)
	for i = 0; i < T; i++ {
		solve()
	}

}


Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed k hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.Vasya has a train lighting schedule for all n hours of the trip — n numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose k hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.

The first input line contains two integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n) — the number of hours on the train and the number of hours to read, correspondingly. The second line contains n space-separated integers ai (0 ≤ ai ≤ 100), ai is the light level at the i-th hour.

In the first output line print the minimum light level Vasya will read at. In the second line print k distinct space-separated integers b1, b2, ..., bk, — the indexes of hours Vasya will read at (1 ≤ bi ≤ n). The hours are indexed starting from 1. If there are multiple optimal solutions, print any of them. Print the numbers bi in an arbitrary order.

NoteIn the first sample Vasya should read at the first hour (light 20), third hour (light 30) and at the fourth hour (light 40). The minimum light Vasya will have to read at is 20.

package main

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

type Element struct {
	Val int
	Idx int
}

type Elements []Element

func (e Elements) Len() int {
	return len(e)
}

func (e Elements) Less(i, j int) bool {
	return e[i].Val <= e[j].Val
}

func (e Elements) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	iFile, _ := os.OpenFile("input.txt", os.O_RDWR|os.O_CREATE, 0777)
	oFile, _ := os.OpenFile("output.txt", os.O_RDWR|os.O_CREATE, 0777)
	reader := bufio.NewReader(iFile)
	writer := bufio.NewWriter(oFile)
	defer writer.Flush()

	var n, k, temp int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	a := make([]Element, 0)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &temp)
		a = append(a, Element{Val: temp, Idx: i})
	}
       fmt.Fscanf(reader, "\n")
	sort.Sort(Elements(a))
	fmt.Fprintf(writer, "%d\n", a[n-k].Val)
	for i := n - k; i < n; i++ {
		if i == (n - 1) {
			fmt.Fprintf(writer, "%d\n", a[i].Idx+1)
		} else {
			fmt.Fprintf(writer, "%d ", a[i].Idx+1)
		}
	}
}

package main

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

type Element struct {
	Val int
	Idx int
}

type Elements []Element

func (e Elements) Len() int {
	return len(e)
}

func (e Elements) Less(i, j int) bool {
	return e[i].Val <= e[j].Val
}

func (e Elements) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	iFile, _ := os.OpenFile("input.txt", os.O_RDWR|os.O_CREATE, 0777)
	oFile, _ := os.OpenFile("output.txt", os.O_RDWR|os.O_CREATE, 0777)
	reader := bufio.NewReader(iFile)
	writer := bufio.NewWriter(oFile)
	defer writer.Flush()

	var n, k, temp int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	a := make([]Element, 0)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &temp)
		a = append(a, Element{Val: temp, Idx: i + 1})
	}
	fmt.Fscanf(reader, "\n")
	sort.Sort(Elements(a))
	fmt.Fprintf(writer, "%d\n", a[n-k].Val)
	for i := n - k; i < n; i++ {
		if i == (n - 1) {
			fmt.Fprintf(writer, "%d\n", a[i].Idx)
		} else {
			fmt.Fprintf(writer, "%d ", a[i].Idx)
		}
	}
}

package main

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

func main(){
	var n, k int
	inp, _ := os.Open("input.txt")
	defer inp.Close()
	r := bufio.NewScanner(inp)
	r.Split(bufio.ScanWords)
	out, _ := os.Create("output.txt")
	defer out.Close()
	w := bufio.NewWriter(out)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	r.Scan()
	k, _ = strconv.Atoi(r.Text())
	a := make([]int, n)
	b := make([]int, n)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
		b[i] = a[i]
	}
	sort.Ints(a)
	w.WriteString(strconv.Itoa(a[n-k])+"\n")
	c := 0
	for j:=0; j<n; j++ {
		if b[j] >= a[n-k] {
			if c < k {
				w.WriteString(strconv.Itoa(j+1)+" ")
				c += 1
			} else {
				break
			}
		}
	}
	w.WriteString("\n")
	w.Flush()
}

package main

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

func main() {
    var n,k,i,j int
    input, _ := os.Open("input.txt")
    defer input.Close()
    scanner := bufio.NewScanner(input)
    scanner.Split(bufio.ScanWords)
    output, _ := os.Create("output.txt")
    defer output.Close()
    writer := bufio.NewWriter(output)
    scanner.Scan()
    aa, _ := strconv.Atoi(scanner.Text())
    n=aa
    scanner.Scan()
    bb, _ := strconv.Atoi(scanner.Text())
    k=bb
    a:=make([]int,n)
    b:=make([]int,n)
    for i=0;i<n;i++ {
    	scanner.Scan()
    	bb, _ := strconv.Atoi(scanner.Text())
    	a[i]=bb
    	b[i]=a[i]
    }
    sort.Ints(b)
    var min int
    min = b[n-k]
    writer.WriteString(strconv.Itoa(min)+"\n")
    for i=n-k;i<n;i++ {
    	for j=0;j<n;j++ {
    		if a[j]==b[i] {
    		    writer.WriteString(strconv.Itoa(j+1)+" ")
    		    a[j]=-1
    		    break
    		}
    	}
    }
    writer.WriteString("\n")
    writer.Flush()
}

package main

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

type Light struct {
    lvl, in int
}

type LightSlice []Light

func (l LightSlice) Len() int { return len(l) }
func (l LightSlice) Swap(i,j int) { l[i], l[j] = l[j], l[i] }
func (l LightSlice) Less(i,j int) bool { return l[i].lvl > l[j].lvl }

func main() {
    input, _ := os.Open("input.txt")
    defer input.Close()
    output, _ := os.Create("output.txt")
    defer output.Close()

    scanner := bufio.NewScanner(input)
    scanner.Split(bufio.ScanWords)
    writer := bufio.NewWriter(output)

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    var n,k int
    ScanInts(&n,&k)
    l := make(LightSlice,n)
    for i := 0; i < n; i++ {
        ScanInts(&l[i].lvl)
        l[i].in = i+1
    }
    sort.Sort(l)
    writer.WriteString(strconv.Itoa(l[k-1].lvl)+"\n")
    for i := 0; i < k; i++ {
        writer.WriteString(strconv.Itoa(l[i].in))
        if i == k-1 { writer.WriteRune('\n') } else { writer.WriteRune(' ') }
    }
    writer.Flush()
}

// 234B-mic
package main

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

func main() {
	var n, k, i int
	in, _ := os.Open("input.txt")
	defer in.Close()
	sc := bufio.NewScanner(in)
	sc.Split(bufio.ScanWords)
	ou, _ := os.Create("output.txt")
	defer ou.Close()
	wr := bufio.NewWriter(ou)
	sc.Scan()
	nn, _ := strconv.Atoi(sc.Text())
	n = nn
	sc.Scan()
	kk, _ := strconv.Atoi(sc.Text())
	k = kk
	var a, b []int
	for i = 1; i <= n; i++ {
		sc.Scan()
		aaa, _ := strconv.Atoi(sc.Text())
		a = append(a, aaa)
		b = append(b, aaa)
	}
	sort.Sort(sort.IntSlice(b))
	x := k
	wr.WriteString(strconv.Itoa(b[n-k]) + "\n")
	for i = n - x; i < n; i++ {
		for j := 0; j < n; j++ {
			if a[j] == b[i] {
				wr.WriteString(strconv.Itoa(j+1) + " ")
				a[j] = -1234567
				break
			}
		}
	}
	wr.Flush()
}

package main

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

type Element struct {
	Val int
	Idx int
}

type Elements []Element

func (e Elements) Len() int {
	return len(e)
}

func (e Elements) Less(i, j int) bool {
	return e[i].Val <= e[j].Val
}

func (e Elements) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

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

	var n, k, temp int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	a := make([]Element, 0)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &temp)
		a = append(a, Element{Val: temp, Idx: i})
	}
	//sort.Sort(Elements(a))
	fmt.Println(a, n, k)
}

package main

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

type Element struct {
	Val int
	Idx int
}

type Elements []Element

func (e Elements) Len() int {
	return len(e)
}

func (e Elements) Less(i, j int) bool {
	return e[i].Val <= e[j].Val
}

func (e Elements) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

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

	var n, k, temp int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	a := make([]Element, 0)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &temp)
		a = append(a, Element{Val: temp, Idx: i + 1})
	}
}

package main

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

func main(){
	var n, k int
	inp, _ := os.Open("input.txt")
	defer inp.Close()
	r := bufio.NewScanner(inp)
	r.Split(bufio.ScanWords)
	out, _ := os.Create("output.txt")
	defer out.Close()
	w := bufio.NewWriter(out)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	r.Scan()
	k, _ = strconv.Atoi(r.Text())
	a := make([]int, n)
	b := make([]int, 101)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
		b[a[i]] = i+1
	}
	sort.Ints(a)
	w.WriteString(strconv.Itoa(a[n-k])+"\n")
	for j:=n-k; j<n; j++ {
		w.WriteString(strconv.Itoa(b[a[j]])+" ")
	}
	w.WriteString("\n")
	w.Flush()
}

package main

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

func main() {
    var n,k,i,j int
    input, _ := os.Open("input.txt")
    defer input.Close()
    scanner := bufio.NewScanner(input)
    scanner.Split(bufio.ScanWords)
    output, _ := os.Create("output.txt")
    defer output.Close()
    writer := bufio.NewWriter(output)
    scanner.Scan()
    aa, _ := strconv.Atoi(scanner.Text())
    n=aa
    scanner.Scan()
    bb, _ := strconv.Atoi(scanner.Text())
    k=bb
    a:=make([]int,n)
    b:=make([]int,n)
    for i=0;i<n;i++ {
    	scanner.Scan()
    	bb, _ := strconv.Atoi(scanner.Text())
    	a[i]=bb
    	b[i]=a[i]
    }
    sort.Ints(b)
    var min int
    min = b[n-k]
    writer.WriteString(strconv.Itoa(min)+"\n")
    for i=n-k;i<n;i++ {
    	for j=0;j<n;j++ {
    		if a[j]==b[i] {
    		    writer.WriteString(strconv.Itoa(j)+" ")
    		    a[j]=-1
    		    break
    		}
    	}
    }
    writer.WriteString("\n")
    writer.Flush()
}

// 234B-mic
package main

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

func main() {
	var n, k, i int
	in, _ := os.Open("input.txt")
	defer in.Close()
	sc := bufio.NewScanner(in)
	sc.Split(bufio.ScanWords)
	ou, _ := os.Create("output.txt")
	defer ou.Close()
	wr := bufio.NewWriter(ou)
	sc.Scan()
	nn, _ := strconv.Atoi(sc.Text())
	n = nn
	sc.Scan()
	kk, _ := strconv.Atoi(sc.Text())
	k = kk
	var a, b []int
	for i = 1; i <= n; i++ {
		sc.Scan()
		aaa, _ := strconv.Atoi(sc.Text())
		a = append(a, aaa)
		b = append(b, aaa)
	}
	sort.Sort(sort.IntSlice(b))
	x := k
	wr.WriteString(strconv.Itoa(b[n-k+1]) + "\n")
	for i = n - x; i < n; i++ {
		for j := 0; j < n; j++ {
			if a[j] == b[i] {
				wr.WriteString(strconv.Itoa(j+1) + " ")
				a[j] = -1234567
				break
			}
		}
	}
	wr.Flush()
}

// 234B-mic
package main

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

func main() {
	var n, k, i int
	input, _ := os.Open("input.txt")
	defer input.Close()
	scanner := bufio.NewScanner(input)
	scanner.Split(bufio.ScanWords)
	output, _ := os.Create("output.txt")
	defer output.Close()
	writer := bufio.NewWriter(output)
	scanner.Scan()
	aa, _ := strconv.Atoi(scanner.Text())
	n = aa
	scanner.Scan()
	bb, _ := strconv.Atoi(scanner.Text())
	k = bb
	a := make([]int, 1001)
	b := make([]int, 1001)
	for i = 1; i <= n; i++ {
		scanner.Scan()
		aaa, _ := strconv.Atoi(scanner.Text())
		a[i] = aaa
		b[i] = a[i]
	}
	sort.Sort(sort.IntSlice(b))
	x := k
	writer.WriteString(strconv.Itoa(b[n-k+1]) + "\n")
	for i = 1; i <= n && x > 0; i++ {
		if a[i] >= b[n-k+1] {
			writer.WriteString(strconv.Itoa(i) + " ")
			x--
		}
	}
}

// 234B-mic
package main

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

func main() {
	var n, k, i int
	input, _ := os.Open("input.txt")
	defer input.Close()
	scanner := bufio.NewScanner(input)
	scanner.Split(bufio.ScanWords)
	output, _ := os.Create("output.txt")
	defer output.Close()
	writer := bufio.NewWriter(output)
	scanner.Scan()
	aa, _ := strconv.Atoi(scanner.Text())
	n = aa
	scanner.Scan()
	bb, _ := strconv.Atoi(scanner.Text())
	k = bb
	//var a, b []int
	a := make([]int, n+1)
	b := make([]int, n+1)
	for i = 1; i <= n; i++ {
		scanner.Scan()
		aaa, _ := strconv.Atoi(scanner.Text())
		//a = append(a, aaa)
		//b = append(b, aaa)
		a[i] = aaa
		b[i] = a[i]
	}
	sort.Sort(sort.IntSlice(b))
	x := k
	writer.WriteString(strconv.Itoa(b[n-k+1]) + "\n")
	for i = 1; i <= n && x > 0; i++ {
		if a[i] > b[n-k] {
			writer.WriteString(strconv.Itoa(i) + " ")
			x--
		}
	}
	writer.Flush()
}

// 234B-mic
package main

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

func main() {
	var n, k, i int
	input, _ := os.Open("input.txt")
	defer input.Close()
	scanner := bufio.NewScanner(input)
	scanner.Split(bufio.ScanWords)
	output, _ := os.Create("output.txt")
	defer output.Close()
	writer := bufio.NewWriter(output)
	scanner.Scan()
	aa, _ := strconv.Atoi(scanner.Text())
	n = aa
	scanner.Scan()
	bb, _ := strconv.Atoi(scanner.Text())
	k = bb
	var a, b []int
	//a := make([]int, n)
	//b := make([]int, n)
	for i = 1; i <= n; i++ {
		scanner.Scan()
		aaa, _ := strconv.Atoi(scanner.Text())
		a = append(a, aaa)
		b = append(b, aaa)
		//a[i] = aaa
		//b[i] = a[i]
	}
	sort.Sort(sort.IntSlice(b))
	x := k
	writer.WriteString(strconv.Itoa(b[n-k]) + "\n")
	for i = 1; i < n && x > 0; i++ {
		if a[i] >= b[n-k] {
			writer.WriteString(strconv.Itoa(i) + " ")
			x--
		}
	}
	writer.Flush()
}

package main

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

type Element struct {
	Val int
	Idx int
}

type Elements []Element

func (e Elements) Len() int {
	return len(e)
}

func (e Elements) Less(i, j int) bool {
	return e[i].Val <= e[j].Val
}

func (e Elements) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	iFile, _ := os.Open("input.txt")
	oFile, _ := os.Open("output.txt")
	reader := bufio.NewReader(iFile)
	writer := bufio.NewWriter(oFile)
	defer writer.Flush()

	var n, k, temp int
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	a := make([]Element, 0)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &temp)
		a = append(a, Element{Val: temp, Idx: i})
	}
	sort.Sort(Elements(a))
	fmt.Fprintf(writer, "%d\n", a[n-k].Val)
	for i := n - k; i < n; i++ {
		if i == (n - 1) {
			fmt.Fprintf(writer, "%d\n", a[i].Idx+1)
		} else {
			fmt.Fprintf(writer, "%d ", a[i].Idx+1)
		}
	}
}


Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.Petya can ask questions like: "Is the unknown number divisible by number y?".The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers yi, he should ask the questions about.

A single line contains number n (1 ≤ n ≤ 103).

Print the length of the sequence of questions k (0 ≤ k ≤ n), followed by k numbers — the questions yi (1 ≤ yi ≤ n). If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.

NoteThe sequence from the answer to the first sample test is actually correct.If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.If the unknown number is divisible by 4, it is 4.If the unknown number is divisible by 3, then the unknown number is 3.Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter.

package main

import (
    "fmt"
    "math"
)

func prime(n int) bool {
    if n == 2 {
        return true
    }

    if n%2 == 0 {
        return false
    }

    limit := int(math.Sqrt(float64(n)))
    for i := 3; i <= limit; i++ {
        if n%i == 0 {
            return false
        }
    }
    return true
}

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

    q := make([]int, 0)
    for i := 2; i <= n; i++ {
        if !prime(i) {
            continue
        }
        for p := i; p <= n; p *= i {
            q = append(q, p)
        }
    }

    fmt.Println(len(q))
    for _, e := range q {
        fmt.Print(" ", e)
    }
    fmt.Println()
}

package main

import (
	"fmt"
)

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

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

	not_prime := make([]bool, n+1)
	not_prime[1] = true
	not_prime[2] = false
	not_prime[3] = false
	for i := 2; i <= n; i++ {
		for j := 2; j <= n; j++ {
			if i*j <= n {
				not_prime[i*j] = true
			} else {
				break
			}
		}
	}

	questions := 0
	is_question := make([]bool, n+1)
	for i := 1; i <= n; i++ {
		if !not_prime[i] {
			p := i
			for p <= n {
				if !is_question[p] {
					is_question[p] = true
					questions++
				}
				p *= i
			}
		}
	}

	fmt.Println(questions)
	for i := 1; i <= n; i++ {
		if is_question[i] {
			fmt.Printf("%d ", i)
		}
	}
	fmt.Printf("\n")
}

package main

import (
	"fmt"
)

var (
	N int
	Prime []int
	Res int
	ResArr []int
)

func FindPrime() {
	for i:=0; i < 1000; i++ {
		Prime = append(Prime, 1)
	}
	Prime[0] = 0
	for i:=2; i <= 1000; i++ {
		if Prime[i-1] == 1 {
			for j:=i*2; j <=1000; j+=i {
				Prime[j-1] = 0
			}
		}
	}
}

func main() {
	FindPrime()
	fmt.Scan(&N)
	if N == 1 {
		fmt.Printf("%d", 0)
	} else {
		for i:=2; i <= N; i++ {
			if Prime[i-1] == 1 {
				j:=i;
				for j <= N {
					Res++;
					ResArr = append(ResArr, j)
					j*=i;
				}
			}
		}
		fmt.Printf("%d\n", Res)
		for _, val := range ResArr {
			fmt.Printf("%d ", val)
		}
	}
}

package main

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

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

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

	n := nextInt()
	primes := make([]bool, 1005)
	ans := make([]int, 0)
	primes[1] = true

	for i := 2; i < len(primes); i++ {
		if !primes[i] {
			for j := i * i; j < len(primes); j += i {
				primes[j] = true
			}
		}
	}

	// println(primes)

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

		if !primes[i] {
			for a <= n/i {
				a *= i
				ans = append(ans, a)
			}
		}
	}

	println(len(ans))
	for i := range ans {
		print(ans[i], " ")
	}
	println()
}

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

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

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

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

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

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

package main

import "fmt"
func main() {
    var n  int
    var a []int
    fmt.Scanf("%d",&n)
    for i:= 2; i <= n; i++{
        b := true
        for j:= 2; j < i; j++{
            if i % j == 0{
                b = false
            }
        }
        if b {
             for k := i; k <= n; k *= i{
                 a = append(a,k)
             }
        }
    }
    fmt.Println(len(a))
    for i:= 0; i < len(a); i++{
        fmt.Printf("%v ",a[i])
    }
}

package main

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

const (
	maxn int = 1000 + 5
)

var (
	n, m  int
	prime [maxn]bool
)

func abc() {
	for i := 0; i < maxn; i++ {
		prime[i] = true
	}

	for i := 2; i < maxn; i++ {
		// fmt.Print(i, " ")
		if !prime[i] {
			continue
		}
		for j := i * 2; j < maxn; j += i {
			// fmt.Print(j, " ")
			prime[j] = false
		}
	}
}
func main() {
	// file, _ := os.Open("input.txt")
	file := os.Stdin
	f := bufio.NewReader(file)
	fmt.Fscanf(f, "%d", &n)
	abc()
	res := 0
	res_ar := make([]int, 0)
	for i := 2; i <= n; i++ {
		if prime[i] {
			tmp := i
			for tmp <= n {
				res++
				res_ar = append(res_ar, tmp)
				tmp *= i
			}
		}
	}
	fmt.Println(res)
	for i := 0; i < len(res_ar); i++ {
		fmt.Print(res_ar[i], " ")
	}
}

package main

import (
    "fmt"
    "math"
)

func prime(n int) bool {
    if n == 2 {
        return true
    }

    if n%2 == 0 {
        return false
    }

    limit := int(math.Sqrt(float64(n)))
    for i := 3; i <= limit; i++ {
        if n%i == 0 {
            return false
        }
    }
    return true
}

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

    q := make([]int, 0)
    for i := 2; i < n; i++ {
        if !prime(i) {
            continue
        }
        for p := i; p <= n; p *= i {
            q = append(q, p)
        }
    }

    fmt.Println(len(q))
    for _, e := range q {
        fmt.Print(" ", e)
    }
    fmt.Println()
}

package main

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

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

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

	n := nextInt()
	primes := make([]bool, 1005)
	ans := make([]int, 0)
	primes[1] = true

	for i := 2; i < len(primes); i++ {
		if !primes[i] {
			for j := i * i; j < len(primes); j += i {
				primes[j] = true
			}
		}
	}

	// println(primes)

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

		if !primes[i] {
			for a <= n/i {
				a *= i
				ans = append(ans, a)
			}
		}
	}

	println(len(ans))
	for i := range ans {
		print(ans[i], " ")
	}
	println(n)
}

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

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

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

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

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

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

package main

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

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

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

	n := nextInt()
	primes := make([]bool, 1001)
	ans := make([]int, 0)
	primes[1] = true

	// for i := 2; i < len(primes); i++ {
	// 	if !primes[i] {
	// 		for j := i * i; j*j < len(primes); j += i {
	// 			primes[j] = true
	// 		}
	// 	}
	// }

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

		if !primes[i] {
			for a <= n/i {
				a *= i
				ans = append(ans, a)
			}
		}
	}

	println(len(ans))
	for i := range ans {
		print(ans[i], " ")
	}
	println(n)
}

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

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

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

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

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

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

package main

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

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

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

	n := nextInt()
	primes := make([]bool, 1001)
	ans := make([]int, 0)
	primes[1] = true

	// for i := 2; i < len(primes); i++ {
	// 	if !primes[i] {
	// 		for j := i * i; j*j <= len(primes); j += i {
	// 			primes[j] = true
	// 		}
	// 	}
	// }

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

	// 	if !primes[i] {
	// 		for a <= n/i {
	// 			a *= i
	// 			ans = append(ans, a)
	// 		}
	// 	}
	// }

	println(len(ans))
	for i := range ans {
		print(ans[i], " ")
	}
	println(n)
}

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

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

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

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

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

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