Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).Inserting an element in the same position he was erased from is also considered moving.Can Vasya divide the array after choosing the right element to move and its new position?

The first line contains single integer n (1 ≤ n ≤ 100000) — the size of the array. The second line contains n integers a1, a2... an (1 ≤ ai ≤ 109) — the elements of the array.

Print YES if Vasya can divide the array after moving one element. Otherwise print NO.

NoteIn the first example Vasya can move the second element to the end of the array.In the second example no move can make the division possible.In the third example Vasya can move the fourth element by one position to the left.

package main

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

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

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

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &a[i])
	}

	if canSplit(a) {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

func canSplit(a []int) bool {
	sum := int64(0)
	for _, e := range a {
		sum += int64(e)
	}

	if sum%2 != 0 {
		return false
	}

	av := make(map[int64]int)
	for _, e := range a {
		av[int64(e)]++
	}

	in := make(map[int64]int)
	cur := int64(0)
	for _, e := range a {
		cur += int64(e)
		in[int64(e)]++
		av[int64(e)]--
		if cur == sum/2 {
			return true
		} else if cur > sum/2 {
			d := cur - sum/2
			if in[d] > 0 {
				return true
			}
		} else {
			d := sum/2 - cur
			if av[d] > 0 {
				return true
			}
		}
	}

	return false
}

package main

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

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

	var n int
	Fscan(in, &n)
	a := make([]int64, n)
	s := make([]int64, n+1)
	for i := range a {
		Fscan(in, &a[i])
		s[i+1] = s[i] + a[i]
	}
	if s[n]&1 > 0 {
		Fprint(out, "NO")
		return
	}
	mp := map[int64]bool{0: true}
	for i, v := range a {
		mp[v] = true
		if mp[s[i+1]-s[n]/2] {
			Fprint(out, "YES")
			return
		}
	}
	mp = map[int64]bool{0: true}
	for i := len(a) - 1; i >= 0; i-- {
		mp[a[i]] = true
		if mp[s[n]/2-s[i]] {
			Fprint(out, "YES")
			return
		}
	}
	Fprint(out, "NO")
}

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

package main

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

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

	var n int
	Fscan(in, &n)
	a := make([]int64, n)
	s := make([]int64, n+1)
	for i := range a {
		Fscan(in, &a[i])
		s[i+1] = s[i] + a[i]
	}
	if s[n]&1 > 0 {
		Fprint(out, "NO")
		return
	}
	mp := make(map[int64]bool, n)
	mp[0] = true
	for i, v := range a {
		mp[v] = true
		if mp[s[i+1]-s[n]/2] {
			Fprint(out, "YES")
			return
		}
	}
	mp = make(map[int64]bool, n)
	mp[0] = true
	for i := len(a) - 1; i >= 0; i-- {
		v := a[i]
		mp[v] = true
		if mp[s[n]/2-s[i]] {
			Fprint(out, "YES")
			return
		}
	}
	Fprint(out, "NO")
}

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

package main

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

func Init() {
}

func Solve(io *FastIO) {
    N := io.NextInt()
    A := io.NextLongArray(N)

    var sum int64
    freq := make(map[int64]int)
    for _, v := range A {
        sum += v
        freq[v]++
    }

    if sum & 1 == 1 {
        io.Println("NO")
        return
    }

    want := sum / int64(2)
    var curr int64
    used := make(map[int64]int)
    for _, v := range A {
        if freq[want - curr] > 0 || used[curr - want] > 0 {
            io.Println("YES")
            return
        }
        curr += v
        freq[v]--
        used[v]++
    }
    io.Println("NO")
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

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

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

	var n int
	Fscan(in, &n)
	a := make([]int64, n)
	s := make([]int64, n+1)
	for i := range a {
		Fscan(in, &a[i])
		s[i+1] = s[i] + a[i]
	}
	if s[n]&1 > 0 {
		Fprint(out, "NO")
		return
	}
	mp := make(map[int64]bool, n)
	mp[0] = true
	for i, v := range a {
		mp[v] = true
		if mp[s[i+1]-s[n]/2] {
			Fprint(out, "YES")
			return
		}
	}
	mp = make(map[int64]bool, n)
	mp[0] = true
	for i := len(a) - 1; i >= 0; i-- {
		v := a[i]
		mp[v] = true
		if mp[s[n]/2-s[i+1]] {
			Fprint(out, "YES")
			return
		}
	}
	Fprint(out, "NO")
}

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

package main

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

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

	var n int
	Fscan(in, &n)
	a := make([]int64, n)
	s := make([]int64, n+1)
	for i := range a {
		Fscan(in, &a[i])
		s[i+1] = s[i] + a[i]
	}
	if s[n]&1 > 0 {
		Fprint(out, "NO")
		return
	}
	mp := make(map[int64]bool, n)
	for i, v := range a {
		mp[v] = true
		if mp[s[i+1]-s[n]/2] {
			Fprint(out, "YES")
			return
		}
	}
	Fprint(out, "NO")
}

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

package main

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

func Init() {
}

func Solve(io *FastIO) {
    N := io.NextInt()
    A := io.NextLongArray(N)

    var sum int64
    freq := make(map[int64]int)
    for _, v := range A {
        sum += v
        freq[v]++
    }

    if sum % 1 == 1 {
        io.Println("NO")
        return
    }

    want := sum / int64(2)
    var curr int64
    for _, v := range A {
        if freq[want - curr] > 0 {
            io.Println("YES")
            return
        }
        curr += v
        freq[v]--
    }
    io.Println("NO")
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

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

func Init() {
}

func Solve(io *FastIO) {
    N := io.NextInt()
    A := io.NextLongArray(N)

    var sum int64
    freq := make(map[int64]int)
    for _, v := range A {
        sum += v
        freq[v]++
    }

    if sum & 1 == 1 {
        io.Println("NO")
        return
    }

    want := sum / int64(2)
    var curr int64
    for _, v := range A {
        if freq[want - curr] > 0 {
            io.Println("YES")
            return
        }
        curr += v
        freq[v]--
    }
    io.Println("NO")
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.

The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.

If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.  Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"bytes"
)

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var n, m, K int
	fmt.Fscanf(reader, "%d %d %d\n", &n, &m, &K)
	pea := make([][]int, n)
	dp := make([][][]int, n)
	dpSrc := make([][][]byte, n)
	for i := 0;i < n;i ++ {
		var s string
		fmt.Fscanf(reader, "%s\n", &s)
		pea[i] = make([]int, m)
		dp[i] = make([][]int, m)
		dpSrc[i] = make([][]byte, m)
		for j := 0;j < m;j ++ {
			pea[i][j] = int(s[j] - '0')
			dp[i][j] = make([]int, K + 1)
			dpSrc[i][j] = make([]byte, K + 1)
			for k := 0;k < K + 1;k ++ {
				dp[i][j][k] = -1
			}
		}
	}
	for i := 0;i < m;i ++ {
		dp[0][i][pea[0][i] % (K + 1)] = pea[0][i]
	}
	for i := 1;i < n;i ++ {
		for j := 0;j < m;j ++ {
			for k := 0;k < K + 1;k ++ {
				if j != 0 && dp[i - 1][j - 1][k] != -1 {
					p := dp[i - 1][j - 1][k] + pea[i][j]
					pmod := p % (K + 1)
					if dp[i][j][pmod] < p {
						dp[i][j][pmod] = p
						dpSrc[i][j][pmod] = 'L'
					}
				}
				if j != m - 1 && dp[i - 1][j + 1][k] != -1 {
					p := dp[i - 1][j + 1][k] + pea[i][j]
					pmod := p % (K + 1)
					if dp[i][j][pmod] < p {
						dp[i][j][pmod] = p
						dpSrc[i][j][pmod] = 'R'
					}
				}
			}
		}
	}
	ans, ansPos, mod := -1, 0, 0
	for i := 0;i < m;i ++ {
		if dp[n - 1][i][0] > ans {
			ans, ansPos = dp[n - 1][i][0], i
		}
	}
	fmt.Printf("%d\n", ans)
	if ans == -1 {
		return
	}
	fmt.Printf("%d\n", ansPos + 1)
	for i := n - 1; i > 0;i -- {
		fmt.Printf("%c", dpSrc[i][ansPos][mod])
		if dpSrc[i][ansPos][mod] == 'L' {
			ansPos, mod = ansPos - 1, (mod - pea[i][ansPos] + 10 * K + 10) % (K + 1)
		} else {
			ansPos, mod = ansPos + 1, (mod - pea[i][ansPos] + 10 * K + 10) % (K + 1)
		}
	}
}


You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.

First line contains one integer n (1 ≤ n ≤ 105) — number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≤ ai ≤ 105; 0 ≤ bi ≤ 104) — number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).

Print one integer — smallest amount of money you need to spend to win the elections.

package main

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

var datas map[int][]int

func check(my, need int) (int, bool) {
	total := my + need
	cost := 0
	exp := 0
	for _, d := range datas {
		for i := 0; i <= len(d)-total && i < len(d); i++ {
			cost += d[i]
			exp++
		}

		if exp > need {
			return cost, false
		}
	}

	re := make([]int, 0, 100000-total)
	for _, d := range datas {
		if len(d) >= total {
			re = append(re, d[len(d)-total+1:]...)
		} else {
			re = append(re, d[:]...)
		}
	}

	sort.Ints(re)

	// fmt.Println(need, exp)
	for i := 0; i < need-exp; i++ {
		cost += re[i]
	}

	return cost, true
}

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

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

	datas = make(map[int][]int, n)

	var a, b, myVoteSum int
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &a, &b)
		if a == 0 || b == 0 {
			myVoteSum++
		} else {
			if d, ok := datas[a]; !ok {
				datas[a] = append(make([]int, 0, 16), b)
			} else {
				datas[a] = append(d, b)
			}
		}
	}

	if myVoteSum*2 > n {
		fmt.Println(0)
		return
	}

	for _, d := range datas {
		sort.Ints(d)
	}

	left, right := 0, n-myVoteSum

	res := 1 << 30
	for left+3 <= right {
		lmid := left + (right-left)/3
		rmid := right - (right-left)/3

		lcost, lok := check(myVoteSum, lmid)
		if !lok {
			left = lmid + 1
			continue
		}

		rcost, rok := check(myVoteSum, rmid)
		if !rok {
			left = rmid + 1
			continue
		}

		if lcost > rcost {
			left = lmid + 1
		} else {
			right = rmid - 1
		}

		res = min(res, min(lcost, rcost))
	}

	for ; left <= right; left++ {
		cost, ok := check(myVoteSum, left)
		if ok {
			res = min(res, cost)
		}
	}

	fmt.Println(res)
}

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

	return y
}

func min(x, y int) int {
	if x < y {
		return x
	}

	return y
}

package main

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

var datas map[int][]int

func check(my, need int) (int, bool) {
	total := my + need
	cost := 0
	exp := 0
	for _, d := range datas {
		for i := 0; i <= len(d)-total; i++ {
			cost += d[i]
			exp++
		}

		if exp > need {
			return cost, false
		}
	}

	re := make([]int, 0, 100000-total)
	for _, d := range datas {
		if len(d) >= total {
			re = append(re, d[len(d)-total+1:]...)
		} else {
			re = append(re, d[:]...)
		}
	}

	sort.Ints(re)

	// fmt.Println(need, exp)
	for i := 0; i < need-exp; i++ {
		cost += re[i]
	}

	return cost, true
}

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

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

	datas = make(map[int][]int, n)

	var a, b, myVoteSum int
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &a, &b)
		if a == 0 || b == 0 {
			myVoteSum++
		} else {
			if d, ok := datas[a]; !ok {
				datas[a] = append(make([]int, 0, 16), b)
			} else {
				datas[a] = append(d, b)
			}
		}
	}

	if myVoteSum*2 > n {
		fmt.Println(0)
		return
	}

	for _, d := range datas {
		sort.Ints(d)
	}

	left, right := 1, n-myVoteSum

	res := 1 << 30
	for left+3 <= right {
		lmid := left + (right-left)/3
		rmid := right - (right-left)/3

		lcost, lok := check(myVoteSum, lmid)
		if !lok {
			left = lmid + 1
			continue
		}

		rcost, rok := check(myVoteSum, rmid)
		if !rok {
			left = rmid + 1
			continue
		}

		if lcost > rcost {
			left = lmid + 1
		} else {
			right = rmid - 1
		}

		res = min(res, min(lcost, rcost))
	}

	for ; left <= right; left++ {
		cost, ok := check(myVoteSum, left)
		if ok {
			res = min(res, cost)
		}
	}

	fmt.Println(res)
}

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

	return y
}

func min(x, y int) int {
	if x < y {
		return x
	}

	return y
}


You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\{1, 1, 1, 4, 4, 2\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \{1024, 512, 512, 4\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\{1024, 1024, 4\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\{2048, 4\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) – the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in multiset. The second line of each query contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.

For each query print YES if it is possible to obtain the number $$$2048$$$ in your multiset, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first query you can win as follows: choose $$$512$$$ and $$$512$$$, and $$$s$$$ turns into $$$\{1024, 64, 1024\}$$$. Then choose $$$1024$$$ and $$$1024$$$, and $$$s$$$ turns into $$$\{2048, 64\}$$$ and you win.In the second query $$$s$$$ contains $$$2048$$$ initially.

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	var (
		count int
	)
	_, _ = fmt.Fscan(input, &count)

	for count > 0 {
		count--

		var setNum int
		_, _ = fmt.Fscan(input, &setNum)

		hasAns := false
		countMap := map[uint32]int{}
		for i := 0; i < setNum; i++ {
			var num uint32
			_, _ = fmt.Fscan(input, &num)
			if num > 2048 || hasAns {
				continue
			}
			if num == 2048 {
				hasAns = true
			}
			if _, ok := countMap[num]; ok {
				countMap[num] = countMap[num] + 1
			} else {
				countMap[num] = 1
			}
		}

		if hasAns {
			fmt.Println("YES")
			continue
		}

		for i := 1; i < 2048; i *= 2 {
			if _, ok := countMap[uint32(i)]; ok {

				if _, ok := countMap[uint32(i*2)]; ok {
					countMap[uint32(i*2)] = countMap[uint32(i)]/2 + countMap[uint32(i*2)]
				} else {
					countMap[uint32(i*2)] = countMap[uint32(i)] / 2
				}
				countMap[uint32(i)] = countMap[uint32(i)] % 2

			} else {
				countMap[uint32(i)] = 0
			}
		}

		if countMap[uint32(2048)] > 0 {
			fmt.Println("YES")
			continue
		}
		fmt.Println("NO")

	}

}

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

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

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

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

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

/*******************************************************************/
func print(b bool) {
	if b {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
}

func main() {
	table := make(map[int]int)
	for i, p := 0, 1; p <= 2048; i, p = i+1, 2*p {
		table[p] = i
	}
	for q := ReadInt(); q > 0; q-- {
		n := ReadInt()
		s := ReadIntSlice(n)
		freq := make([]int, 12)
		for _, v := range s {
			if v > 2048 {
				continue
			}
			freq[table[v]]++
		}
		for i := 0; i < 11; i++ {
			freq[i+1] += freq[i] / 2
		}
		print(freq[11] > 0)
	}

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return string(res)
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	q := 0
	fmt.Fscanf(in, "%d\n", &q)
	for ii := 0; ii < q; ii++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &a[i])
		}
		fmt.Fscanf(in, "\n")

		sort.Ints(a)
		sum := 0
		found := false
		for i := 0; i < n; i++ {
			if a[i] > 2048 {
				break
			}
			sum += a[i]
			if sum >= 2048 {
				found = true
				break
			}
		}
		if found {
			fmt.Fprintf(out, "YES\n")
		} else {
			fmt.Fprintf(out, "NO\n")
		}
	}
	return
}

func minstep(a, b byte) int {
	return min(int(a-b+26)%26, int(b-a+26)%26)
}

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

package main

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

func toInt(buf []byte) uint32 {
	n := uint32(0)
	for _, v := range buf {
		n = n*10 + uint32(v-'0')
	}

	return n
}

const TARGET = 2048

func solve(a []uint32) bool {
	nums := make([]uint32, 0, len(a))
	m := map[uint32]int{}

	for _, n := range a {
		m[n]++

		if m[n] == 2 {
			nums = append(nums, n)
		}
	}

	for m[TARGET] == 0 && len(nums) > 0 {
		n := nums[0]
		m[n] -= 2
		if m[n] < 2 {
			nums = nums[1:]
		}

		n *= 2
		m[n]++
		if m[n] == 2 {
			nums = append(nums, n)
		}
	}

	return m[TARGET] > 0
}

func main() {
	var q uint32

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

	scanner.Scan()
	q = toInt(scanner.Bytes())
	r := make([]string, q)

	for i := uint32(0); i < q; i++ {
		var n int

		scanner.Scan()
		n = int(toInt(scanner.Bytes()))

		a := make([]uint32, n)
		for j := range a {
			scanner.Scan()
			a[j] = toInt(scanner.Bytes())
		}

		res := "NO"
		if solve(a) {
			res = "YES"
		}

		r[i] = res
	}

	for _, s := range r {
		fmt.Println(s)
	}
}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	var testCase int

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

	for testCase > 0 {
		testCase--

		var x int
		_, err := fmt.Fscan(input, &x)
		if err != nil {
		}

		s := make([]int, x)
		for i := 0; i < x; i++ {
			_, err = fmt.Fscan(input, &s[i])
			if err != nil {
			}
		}

		result := "NO"
		//sort.Ints(s)
		//y := make([]int, x)
		//j := 0
		//for i := 0; i < x; {
		//	if s[i] == 2048 {
		//		result = "YES"
		//		break
		//	}
		//	if i < x-1 && s[i] == s[i+1] {
		//		yy := s[i] + s[i+1]
		//		if yy > y[j] {
		//			y[j+1] = yy
		//		} else {
		//			y[j+1] = yy + y[j]
		//		}
		//		j++
		//		i += 2
		//	} else if s[i] == y[j] {
		//		y[j+1] = s[i] + y[j]
		//		j++
		//		i++
		//	} else {
		//		i++
		//	}
		//	if y[j] == 2048 {
		//		result = "YES"
		//		break
		//	}
		//}

		if len(s) == 1 && s[0] == 2048 {
			result = "YES"
		}
		for len(s) > 1 {
			sort.Ints(s)
			//fmt.Println(s)
			if s[0] == 2048 {
				result = "YES"
				break
			} else if s[0] > 2048 {
				break
			}
			if s[0] == s[1] {
				s[0] = math.MaxInt32
				s[1] = s[1] + s[1]
			} else {
				s[0] = math.MaxInt32
			}
		}

		fmt.Println(result)
	}

}

package main

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

var scan *bufio.Scanner
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func nextWord() string {
	scan.Scan()
	str := scan.Text()
	return str
}

func nextInt() int {
	i, e := strconv.Atoi(nextWord())
	if e != nil {
		panic(e)
	}
	return i
}

func nextInt64() int64 {
	i, e := strconv.ParseInt(nextWord(), 10, 64)
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	var n, m int
	var num int64
	n = nextInt()
	for i := 0; i < n; i++ {
		m = nextInt()
		numMap := make(map[int]int)
		for j := 0; j < m; j++ {
			num = nextInt64()
			if num <= 2048 {
				numMap[int(num)]++
			}
		}
		k := 1
		for j := 1; j < 13; j++ {
			if k == 2048 {
				if numMap[k] > 0 {
					fmt.Fprintln(writer, "YES")

				} else {
					fmt.Fprintln(writer, "NO")
				}
				break
			}
			for ; numMap[k] > 1; {
				numMap[k] -= 2
				numMap[k + k]++
			}
			k += k
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"os"
)

const INF  = 1000000001

type Pair struct {
	first, second int
}

func sort(arr []int) []int {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i] < arr[right] {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort(arr[:left])
	sort(arr[left+1:])
	return arr
}

func solution(reader io.Reader, writer io.Writer) {
	var t int
	fmt.Fscanf(reader, "%d\n", &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscanf(reader, "%d\n", &n)
		var s int
		for j := 0; j < n; j++ {
			var a int
			fmt.Fscanf(reader, "%d", &a)
			if a <= 2048 {
				s += a
			}
		}
		if s >= 2048 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
		fmt.Fscanf(reader, "\n")
	}
}

func main() {

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

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

	solution(reader, writer)
}

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

package main

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

func Solve(n int, s []int) string {
	count := make(map[int]int)
	for _, elem := range s {
		count[elem] += 1
	}
	for i := 1; i <= 2048; i *= 2 {
		count[i*2] += count[i] / 2
	}
	if count[2048] > 0 {
		return "YES"
	}
	return "NO"
}

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

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

package main

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

func clear(arr []byte) []byte {
	if string(arr[len(arr)-2:len(arr)]) == "\r\n" {
		return arr[:len(arr)-2]
	} else if string(arr[len(arr)-1]) == "\n" {
		return arr[:len(arr)-1]
	}
	return arr
}

func isWin(b []byte) string {
	sum := 0
	for _, v := range strings.Split(string(clear(b)), " ") {
		value, _ := strconv.Atoi(v)
		if value > 2048 {
			continue
		}
		sum += value
		if sum >= 2048 {
			break
		}
	}
	if sum >= 2048 {
		return "YES"
	}
	return "NO"
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	line, _ := reader.ReadBytes('\n')
	q, _ := strconv.Atoi(string(clear(line)))

	for i := 0; i < q; i++ {
		reader.ReadBytes('\n')
		array, _ := reader.ReadBytes('\n')
		fmt.Printf("%v\n", isWin(array))
	}
}

package main

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

/* solution */

func solve() {

	q := readInt()
	for i := 0; i < q; i++ {
		if solveOne() {
			print("YES")
		} else {
			print("NO")
		}
	}

}

func solveOne() bool {

	n := readInt()

	var cnt [11 + 2]int

	for i := 0; i < n; i++ {
		v := readInt()
		k := 0
		for v > 0 && k <= 12 {
			v = v / 2
			k++
		}
		cnt[k-1]++
	}

	for i := 1; i <= 11; i++ {
		cnt[i] += cnt[i-1] / 2
	}

	return cnt[11] > 0

}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

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

func read() string {
	reader.Scan()
	return reader.Text()
}

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

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

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

func printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}

package main
import (
	"fmt"
	"sort"
)

func main()  {
	var query int
	fmt.Scanf("%d\n", &query)
	for i := 0; i < query; i++{
		var n int
		fmt.Scanf( "%d\n", &n)
		var number [128]int
		for j := 0; j < n; j++{
			if(j == n - 1) {
				fmt.Scanf("%d\n", &number[j])
			}else{
				fmt.Scanf("%d", &number[j])

			}
		}
		sort.Ints(number[0:n])
		start := 0
		flag := false
		number[n] = 0
		for {
			if flag || start >= n || number[start] > 2048 {
				break
			}
			//start = 0;
			//j = 5
			//4,3,2,1,0
			for j := start; j <= n; j++ {
				if number[j] == 2048 {
					flag = true
					break
				}
				if number[j] != number[start] {
					if j - start > 1 {
						for k := j - 1; k > j - 1 - (j - start) / 2; k--{
							number[k] = number[start] * 2
						}
						start = j - (j -start) / 2
					}else {
						start ++
					}
					break
				}
			}
		}
		if flag {
			fmt.Println("YES")
		}else{
			fmt.Println("NO")
		}
	}
}

package main

import (
    "fmt"
    "bufio"
    "os"
)
var input *bufio.Reader

func solve() {
    var (
        N int
    )
    fmt.Fscanf(input, "%d\n", &N)
    arr := make([]int64, N)
    for i:=0 ; i<N ; i++ {
        fmt.Fscanf(input, "%d ", &arr[i])
    }
    fmt.Fscanf(input, "\n")
    freq := make(map[int64] int)
    for i:=0 ; i<N ; i++ {
        freq[arr[i]] += 1
    }
    // check 2048 in freq
    // if not do stacking
    // if no stacking can be done, print no
    for {
        //fmt.Println(freq)
        if freq[2048] > 0 {
            fmt.Println("YES")
            return
        }
        var key int64 = 1
        flag := false
        for i:=0 ; i<=10 ; i++ {
            if freq[key] >= 2 {
                freq[key] -= 2
                freq[key*2] += 1
                flag = true
                break
            }
            key = key * 2
        }
        if flag==false {
            fmt.Println("NO")
            return
        }
    }

}

func main () {
    input = bufio.NewReader(os.Stdin)
    var T int
    fmt.Fscanf(input, "%d\n", &T)
    for i:=0 ; i<T ; i++ {
        solve()
    }
}

package main

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

var scan *bufio.Scanner
var reader io.Reader
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	reader = os.Stdin
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func main() {
	solve()
}

func solve() {
	q := nextInt()
	for i := 0; i < q; i++ {
		n := nextInt()
		s := make([]int, n)
		r := 0
		res := "No"
		for j := 0; j < n; j++ {
			s[j] = nextInt()
			if s[j] > 2048 {
				continue
			}
			if s[j] <= 2048 {
				r += s[j]
				if r >= 2048 {
					res = "Yes"
				}
			}
		}
		fmt.Fprintln(writer, res)
	}
}

func nextWord() string {
	var s string
	fmt.Fscan(reader, &s)
	return s
}

func nextInt() int {
	i, e := strconv.Atoi(nextWord())
	if e != nil {
		panic(e)
	}
	return i
}

func max(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Max(res, float64(z))
	}
	return int(res)
}

func min(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Min(res, float64(z))
	}
	return int(res)
}

func abs(x int) int {
	return int(math.Abs(float64(x)))
}

func sqrt(x int) int {
	return int(math.Sqrt(float64(x)))
}

func int2Int(x int) big.Int {
	var res big.Int
	res.SetInt64(int64(x))
	return res
}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	var (
		count int
	)
	_, _ = fmt.Fscan(input, &count)

	for count > 0 {
		count--

		var setNum int
		_, _ = fmt.Fscan(input, &setNum)

		tmp := 0
		hasAns := false
		for i := 0; i < setNum; i++ {
			var num uint32
			_, _ = fmt.Fscan(input, &num)
			if num > 2048 || hasAns {
				continue
			}
			if num == 2048 {
				hasAns = true
			}
			tmp += int(math.Log2(float64(num)))
		}

		if hasAns{
			fmt.Println("YES")
			continue
		}

		if tmp >= 20 {
			fmt.Println("YES")
			continue
		}
		fmt.Println("NO")

	}

}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	var testCase int

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

	for testCase > 0 {
		testCase--

		var x int
		_, err := fmt.Fscan(input, &x)
		if err != nil {
		}

		s := make([]int, x)
		y := make([]int, x)
		for i := 0; i < x; i++ {
			_, err = fmt.Fscan(input, &s[i])
			if err != nil {
			}
		}

		sort.Ints(s)
		j := 0
		result := "NO"
		for i := 0; i < x; {
			if s[i] == 2048{
				result = "YES"
				break
			}
			if i < x-1 && s[i] == s[i+1] {
				yy := s[i] + s[i+1]
				if yy > y[j] {
					y[j+1] = yy
				} else {
					y[j+1] = yy + y[j]
				}
				j++
				i += 2
			} else if s[i] == y[j] {
				y[j+1] = s[i] + y[j]
				j++
				i++
			} else {
				i++
			}
			if y[j] == 2048 {
				result = "YES"
				break
			}
		}
		fmt.Println(result)
	}

}

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
	var num int64
	fmt.Fscanf(bufin, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(bufin, "%d\n", &m)
		numMap := make(map[int]int)
		for j := 0; j < m; j++ {
			fmt.Fscanf(bufin, "%d\n", &num)
			if num <= 2048 {
				numMap[int(num)]++
			}
		}
		k := 1
		for j := 1; j < 13; j++ {
			for ; numMap[k] > 1; {
				numMap[k] -= 2
				numMap[k + k]++
			}
			if k == 2048 {
				if numMap[k] > 0 {
					fmt.Fprintf(bufout, "YES")
				} else {
					fmt.Fprintf(bufout, "NO")
				}
				break
			}
			k += k
		}
	}
}

package main
import (
	"fmt"
	"sort"
)

func main()  {
	var query int
	fmt.Scanln(&query)
	for i := 0; i < query; i++{
		var n int
		fmt.Scanln( &n)
		var number [128]int
		for j := 0; j < n; j++{
			fmt.Scan(&number[j])
		}
		sort.Ints(number[0:n])
		start := 0
		flag := false
		number[n] = 0
		for {
			if flag || start >= n || number[start] > 2048 {
				break
			}
			//start = 0;
			//j = 5
			//4,3,2,1,0
			for j := start; j <= n; j++ {
				if number[j] == 2048 {
					flag = true
					break
				}
				if number[j] != number[start] {
					if j - start > 1 {
						for k := j - 1; k > j - 1 - (j - start) / 2; k--{
							number[k] = number[start] * 2
						}
						start = j - (j -start) / 2
					}else {
						start ++
					}
					break
				}
			}
		}
		if flag {
			fmt.Println("YES")
		}else{
			fmt.Println("NO")
		}
	}
}

package main
import (
	"fmt"
	"sort"
)

func main()  {
	var query int
	fmt.Scanln(&query)
	for i := 0; i < query; i++{
		var n int
		var tmp string
		fmt.Scanln( &tmp)
		var number [128]int
		for j := 0; j < n; j++{
			fmt.Scan(&number[j])
		}
		fmt.Scanln()
		sort.Ints(number[0:n])
		start := 0
		flag := false
		number[n] = 0
		for {
			if flag || start >= n || number[start] > 2048 {
				break
			}
			//start = 0;
			//j = 5
			//4,3,2,1,0
			for j := start; j <= n; j++ {
				if number[j] == 2048 {
					flag = true
					break
				}
				if number[j] != number[start] {
					if j - start > 1 {
						for k := j - 1; k > j - 1 - (j - start) / 2; k--{
							number[k] = number[start] * 2
						}
						start = j - (j -start) / 2
					}else {
						start ++
					}
					break
				}
			}
		}
		if flag {
			fmt.Println("YES")
		}else{
			fmt.Println("NO")
		}
	}
}

package main
import (
	"fmt"
	"sort"
)

func main()  {
	var query int
	fmt.Scanln(&query)
	for i := 0; i < query; i++{
		var n int
		fmt.Scanln( &n)
		fmt.Printf("number %d\n", n)
		var number [128]int
		for j := 0; j < n; j++{
			fmt.Scanf("%d", &number[j])
		}
		sort.Ints(number[0:n])
		start := 0
		flag := false
		number[n] = 0
		for {
			if flag || start >= n || number[start] > 2048 {
				break
			}
			//start = 0;
			//j = 5
			//4,3,2,1,0
			for j := start; j <= n; j++ {
				if number[j] == 2048 {
					flag = true
					break
				}
				if number[j] != number[start] {
					if j - start > 1 {
						for k := j - 1; k > j - 1 - (j - start) / 2; k--{
							number[k] = number[start] * 2
						}
						start = j - (j -start) / 2
					}else {
						start ++
					}
					break
				}
			}
		}
		if flag {
			fmt.Println("YES")
		}else{
			fmt.Println("NO")
		}
	}
}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	var (
		count int
	)
	_, _ = fmt.Fscan(input, &count)

	for count > 0 {
		count--

		var setNum int
		_, _ = fmt.Fscan(input, &setNum)

		hasAns := false
		countMap := map[uint32]int{}
		for i := 0; i < setNum; i++ {
			var num uint32
			_, _ = fmt.Fscan(input, &num)
			if num > 2048 || hasAns {
				continue
			}
			if num == 2048 {
				hasAns = true
			}
			if _, ok := countMap[num]; ok {
				countMap[num] = countMap[num] + 1
			} else {
				countMap[num] = 1
			}
		}

		if hasAns {
			fmt.Println("YES")
			continue
		}

		for i := 2; i < 4096; i *= 2 {
			if _, ok := countMap[uint32(i)]; ok {

				if _, ok := countMap[uint32(i*2)]; ok {
					countMap[uint32(i*2)] = countMap[uint32(i)]/2 + countMap[uint32(i*2)]
				} else {
					countMap[uint32(i*2)] = countMap[uint32(i)] / 2
				}
				countMap[uint32(i)] = countMap[uint32(i)] % 2

			} else {
				countMap[uint32(i)] = 0
			}
		}

		if countMap[uint32(2048)] > 0 {
			fmt.Println("YES")
			continue
		}
		fmt.Println("NO")

	}

}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	var (
		count int
	)
	_, _ = fmt.Fscan(input, &count)

	for count > 0 {
		count--

		var setNum int
		_, _ = fmt.Fscan(input, &setNum)

		hasAns := false
		countMap := map[uint32]int{}
		for i := 0; i < setNum; i++ {
			var num uint32
			_, _ = fmt.Fscan(input, &num)
			if num > 2048 || hasAns {
				continue
			}
			if num == 2048 {
				hasAns = true
			}
			if _, ok := countMap[num]; ok {
				countMap[num] = countMap[num] + 1
			} else {
				countMap[num] = 1
			}
		}

		if hasAns {
			fmt.Println("YES")
			continue
		}

		for i := 1; i < 4096; i *= 2 {
			if _, ok := countMap[uint32(i)]; ok {

				if _, ok := countMap[uint32(i*2)]; ok {
					countMap[uint32(i*2)] = countMap[uint32(i)]/2 + countMap[uint32(i*2)]
				} else {
					countMap[uint32(i*2)] = countMap[uint32(i)] / 2
				}
				countMap[uint32(i)] = countMap[uint32(i)] % 2

			} else {
				countMap[uint32(i)] = 0
			}
		}

		if countMap[uint32(2048)] > 0 {
			fmt.Println("YES")
			continue
		}
		fmt.Println("NO")

	}

}


Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum  is maximally possible, where A' is already rearranged array.

First line of input data contains single integer m (1 ≤ m ≤ 2·105) — length of arrays A and B. Next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 109) — array A. Next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109) — array B.

Output m integers a'1, a'2, ..., a'm — array A' which is permutation of the array A.

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

package main

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

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

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

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

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

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

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

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

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

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

var (
	m    int
	A, B []int
)

func main() {
	m = ReadInt()
	A, B = ReadIntSlice(m), ReadIntSlice(m)

	T := []Tuple{}
	for i := 0; i < m; i++ {
		T = append(T, Tuple{idx: i, a: -1, b: B[i]})
	}
	sort.SliceStable(T, func(i, j int) bool {
		return T[i].b > T[j].b
	})
	sort.Sort(sort.IntSlice(A))

	for i := 0; i < m; i++ {
		T[i].a = A[i]
	}

	sort.SliceStable(T, func(i, j int) bool {
		return T[i].idx < T[j].idx
	})

	answers := make([]int, m)
	for i := 0; i < m; i++ {
		answers[i] = T[i].a
	}
	fmt.Println(PrintIntsLine(answers...))
}

type Tuple struct {
	idx, a, b int
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

func solve() {
	n := readInt()
	a := make([]int, n)
	b := make([]int, n)
	heapA := NewMinHeap(n)
	for i := 0; i < n; i++ {
		a[i] = readInt()
		heapA.Add(i, -a[i])
	}
	heapB := NewMinHeap(n)
	for i := 0; i < n; i++ {
		b[i] = readInt()
		heapB.Add(i, b[i])
	}
	for i := 0; i < n; i++ {
		first := heapA.Min()
		indexA := heapA.ArgMin()
		heapA.Remove(indexA)
		indexB := heapB.ArgMin()
		heapB.Remove(indexB)
		a[indexB] = -first
	}
	var buffer bytes.Buffer
	for i := 0; i < n; i++ {
		if i > 0 {
			buffer.WriteString(" ")
		}
		buffer.WriteString(strconv.Itoa(a[i]))
	}
	fmt.Println(buffer.String())
}

type MinHeap struct {
	a    []int
	vmap []int
	imap []int
	n    int
	pos  int
}

const INF = math.MaxInt32

func NewMinHeap(m int) *MinHeap {
	heap := &MinHeap{}
	m += 2
	heap.n = m
	heap.a = make([]int, heap.n)
	heap.vmap = make([]int, heap.n)
	heap.imap = make([]int, heap.n)
	heap.pos = 1
	for i := 0; i < heap.n; i++ {
		heap.a[i] = INF
		heap.vmap[i] = -1
		heap.imap[i] = -1
	}
	return heap
}

func (h *MinHeap) Add(ind, x int) int {
	ret := h.imap[ind]
	if h.imap[ind] < 0 {
		h.a[h.pos] = x
		h.vmap[h.pos] = ind
		h.imap[ind] = h.pos
		h.pos++
		h.up(h.pos - 1)
	}
	if ret != -1 {
		return h.a[ret]
	}
	return x
}

func (h *MinHeap) Update(ind, x int) int {
	ret := h.imap[ind]
	if h.imap[ind] < 0 {
		h.a[h.pos] = x
		h.vmap[h.pos] = ind
		h.imap[ind] = h.pos
		h.pos++
		h.up(h.pos - 1)
	} else {
		h.a[ret] = x
		h.up(ret)
		h.down(ret)
	}
	return x
}

func (h *MinHeap) Remove(ind int) int {
	if h.pos == 1 {
		return INF
	}
	if h.imap[ind] == -1 {
		return INF
	}

	h.pos--
	rem := h.imap[ind]
	ret := h.a[rem]
	h.vmap[rem] = h.vmap[h.pos]
	h.imap[h.vmap[h.pos]] = rem
	h.imap[ind] = -1
	h.a[rem] = h.a[h.pos]
	h.a[h.pos] = INF
	h.vmap[h.pos] = -1

	h.up(rem)
	h.down(rem)
	return ret
}

func (h *MinHeap) Min() int {
	return h.a[1]
}

func (h *MinHeap) ArgMin() int {
	return h.vmap[1]
}

func (h *MinHeap) Size() int {
	return h.pos - 1
}

func (h *MinHeap) up(cur int) {
	for c, p := cur, cur>>1; p >= 1 && h.a[p] > h.a[c]; c, p = c>>1, p>>1 {
		h.a[p], h.a[c] = h.a[c], h.a[p]
		h.imap[h.vmap[p]], h.imap[h.vmap[c]] = h.imap[h.vmap[c]], h.imap[h.vmap[p]]
		h.vmap[p], h.vmap[c] = h.vmap[c], h.vmap[p]
	}
}

func (h *MinHeap) down(cur int) {
	for c := cur; 2*c < h.pos; {
		b := 0
		if h.a[2*c] < h.a[2*c+1] {
			b = 2 * c
		} else {
			b = 2*c + 1
		}
		if h.a[b] < h.a[c] {
			h.a[c], h.a[b] = h.a[b], h.a[c]
			h.imap[h.vmap[c]], h.imap[h.vmap[b]] = h.imap[h.vmap[b]], h.imap[h.vmap[c]]
			h.vmap[c], h.vmap[b] = h.vmap[b], h.vmap[c]
			c = b
		} else {
			break
		}
	}
}

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

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

package main

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

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	A := sc.NextIntArray()
	B := sc.NextIntArray()

	var tuples = make(SortInterFace, N)
	for i := 0; i < N; i++ {
		tuples[i] = tuple{B[i], i}
	}
	sort.Ints(A)

	sort.Sort(tuples)

	ans := make([]int, N)
	for i := 0; i < N; i++ {
		ans[tuples[i].order] = A[i]
	}

	PrintI(ans...)
}

func mapToString(arr []int) []string {
	ret := make([]string, len(arr))
	for i := 0; i < len(arr); i++ {
		ret[i] = strconv.Itoa(arr[i])
	}
	return ret
}

func PrintI(args ...int) {
	fmt.Println(strings.Join(mapToString(args), " "))
}

type tuple struct {
	value int
	order int
}

type SortInterFace []tuple

func (s SortInterFace) Len() int {
	return len(s)
}
func (s SortInterFace) Less(i, j int) bool {
	return s[i].value > s[j].value
}
func (s SortInterFace) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

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

package main

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

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

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

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

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

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

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

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

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

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

var (
	m    int
	A, B []int
)

func main() {
	m = ReadInt()
	A, B = ReadIntSlice(m), ReadIntSlice(m)

	fmt.Println(PrintIntsLine(A...))
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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


The store sells $$$n$$$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them.A necklace is a set of beads connected in a circle.For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options):  And the following necklaces cannot be assembled from beads sold in the store:  The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store. We call a necklace $$$k$$$-beautiful if, when it is turned clockwise by $$$k$$$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace.    As you can see, this necklace is, for example, $$$3$$$-beautiful, $$$6$$$-beautiful, $$$9$$$-beautiful, and so on, but it is not $$$1$$$-beautiful or $$$2$$$-beautiful.In particular, a necklace of length $$$1$$$ is $$$k$$$-beautiful for any integer $$$k$$$. A necklace that consists of beads of the same color is also beautiful for any $$$k$$$.You are given the integers $$$n$$$ and $$$k$$$, and also the string $$$s$$$ containing $$$n$$$ lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $$$k$$$-beautiful necklace you can assemble.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 2000$$$). The second line of each test case contains the string $$$s$$$ containing $$$n$$$ lowercase English letters — the beads in the store. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.

Output $$$t$$$ answers to the test cases. Each answer is a positive integer — the maximum length of the $$$k$$$-beautiful necklace you can assemble.

6
6 3
abcbac
3 6
aaa
7 1000
abczgyo
5 4
ababa
20 10
aaebdbabdbbddaadaadc
20 5
ecbedececacbcbccbdec

NoteThe first test case is explained in the statement.In the second test case, a $$$6$$$-beautiful necklace can be assembled from all the letters.In the third test case, a $$$1000$$$-beautiful necklace can be assembled, for example, from beads "abzyo".

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, k := readTwoNums(reader)
		s, _ := reader.ReadString('\n')
		fmt.Println(solve(n, k, s[:n]))
	}
}

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

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

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

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

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

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

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

	return i
}

func solve(n, k int, s string) int {
	// find all divisors of k
	cnt := make(map[byte]int)

	for i := 0; i < n; i++ {
		cnt[s[i]]++
	}

	arr := make([]int, 0, len(cnt))
	for _, v := range cnt {
		arr = append(arr, v)
	}

	sort.Ints(arr)

	check := func(l, k int) bool {
		// can we have a l length segments length, each seg has k beads
		for i := len(arr) - 1; i >= 0 && arr[i] >= l && k > 0; i-- {
			x := arr[i] / l
			k -= x
		}

		return k <= 0
	}

	find := func(k int) int {
		// one segment has k
		var left, right = 1, n + 1

		for left < right {
			mid := (left + right) / 2
			if !check(mid, k) {
				right = mid
			} else {
				left = mid + 1
			}
		}
		right--
		return right * k
	}

	best := 1
	for x := 1; x*x <= k; x++ {
		if k%x != 0 {
			continue
		}

		best = max(best, find(x))

		if k/x != x {
			best = max(best, find(k/x))
		}
	}

	return best
}

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

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, k := readTwoNums(reader)
		s, _ := reader.ReadString('\n')
		fmt.Println(solve(n, k, s[:n]))
	}
}

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

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

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

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

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

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

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

	return i
}

func solve(n, k int, s string) int {
	cnt := make(map[byte]int)

	for i := 0; i < n; i++ {
		cnt[s[i]]++
	}

	cycles := make([]int, n)

	used := make([]bool, n)

	for l := n; l > 0; l-- {
		var p int
		for i := 0; i < l; i++ {
			if used[i] {
				continue
			}
			used[i] = true
			var x = 1

			j := (i + k) % l

			for !used[j] {
				x++
				used[j] = true
				j = (j + k) % l
			}
			cycles[p] = x
			p++
		}

		canFill := true

		sort.Ints(cycles[:p])
		pq := make(IntHeap, 0, len(cnt))

		for _, v := range cnt {
			heap.Push(&pq, v)
		}

		for p > 0 {
			cur := cycles[p-1]
			p--

			top := heap.Pop(&pq).(int)

			if top < cur {
				canFill = false
				break
			}

			heap.Push(&pq, top-cur)
		}

		if canFill {
			return l
		}

		for i := 0; i < n; i++ {
			used[i] = false
		}
	}
	return 0
}

// An IntHeap is a min-heap of ints.
type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func solve1(n, k int, s string) int {
	// find all divisors of k
	cnt := make(map[byte]int)

	for i := 0; i < n; i++ {
		cnt[s[i]]++
	}

	arr := make([]int, 0, len(cnt))
	for _, v := range cnt {
		arr = append(arr, v)
	}

	sort.Ints(arr)

	check := func(l, k int) bool {
		// can we have a l length segments length, each seg has k beads
		for i := len(arr) - 1; i >= 0 && arr[i] >= l && k > 0; i-- {
			x := arr[i] / l
			k -= x
		}

		return k <= 0
	}

	find := func(k int) int {
		// one segment has k
		var left, right = 1, n + 1

		for left < right {
			mid := (left + right) / 2
			if !check(mid, k) {
				right = mid
			} else {
				left = mid + 1
			}
		}
		right--
		return right * k
	}

	best := 1
	for x := 1; x*x <= k; x++ {
		if k%x != 0 {
			continue
		}

		best = max(best, find(x))

		if k/x != x {
			best = max(best, find(k/x))
		}
	}

	return best
}

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

package main

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

var (
	inn = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
)

func main() {
	defer out.Flush()
	inn.Buffer([]byte{}, 1000000)
	inn.Split(bufio.ScanWords)
	//prep
	for tt := rd(); tt > 0; tt-- {
		n, k := rd(), rd()
		s := rds()
		cnt := [26]int{}
		for _, ch := range s {
			cnt[ch-'a']++
		}
		for i := n; i > 0; i-- {
			t := i / gcd(i, k)
			sum := 0
			for j := 0; j < 26; j++ {
				sum += cnt[j] / t
			}
			if sum*t >= i {
				Fprintln(out, i)
				break
			}
		}
	}
}

//-------------------template------------------
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func maxll(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func minll(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func rd() (x int) {
	inn.Scan()
	x, _ = strconv.Atoi(string(inn.Bytes()))
	return x
}
func rdll() (x int64) {
	inn.Scan()
	x, _ = strconv.ParseInt(string(inn.Bytes()), 10, 64)
	return x
}
func rds() string {
	inn.Scan()
	return string(inn.Bytes())
}

package main

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

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

	var t, n, k int

	fmt.Fscanf(reader, "%d\n", &t)
	for ; t > 0; t-- {
		var s string
		fmt.Fscanf(reader, "%d %d\n%s\n", &n, &k, &s)
		lets := make([]int, 33)
		for i := 0; i < n; i++ {
			lets[s[i]-'a']++
		}

		sort.Ints(lets)

		maxLen := lets[32]
		if k == n {
			maxLen = n
			fmt.Println(maxLen)
			continue
		}

		//fmt.Println(lets)
		kk := make([]int, 0, 2000)
		for i := 2; i <= k; i++ {
			if k%i == 0 {
				kk = append(kk, i)
			}
		}
		for _, g := range kk {
			for zn := 1; zn <= n/g; zn++ {
				gs := 0
				for i := 32; i >= 0 && lets[i] >= zn; i-- {
					gs += (lets[i] / zn)
					if gs >= g {
						if g*zn > maxLen {
							maxLen = g * zn
						}
						break
					}
				}
			}
		}

		fmt.Println(maxLen)
	}
}


— Do you have a wish?  — I want people to stop gifting each other arrays.O_o and Another Young BoyAn array of $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$ fell down on you from the skies, along with a positive integer $$$k \le n$$$.You can apply the following operation at most $$$k$$$ times:   Choose an index $$$1 \le i \le n$$$ and an integer $$$1 \le x \le 10^9$$$. Then do $$$a_i := x$$$ (assign $$$x$$$ to $$$a_i$$$). Then build a complete undirected weighted graph with $$$n$$$ vertices numbered with integers from $$$1$$$ to $$$n$$$, where edge $$$(l, r)$$$ ($$$1 \le l < r \le n$$$) has weight $$$\min(a_{l},a_{l+1},\ldots,a_{r})$$$.You have to find the maximum possible diameter of the resulting graph after performing at most $$$k$$$ operations.The diameter of a graph is equal to $$$\max\limits_{1 \le u < v \le n}{\operatorname{d}(u, v)}$$$, where $$$\operatorname{d}(u, v)$$$ is the length of the shortest path between vertex $$$u$$$ and vertex $$$v$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le k \le n$$$). The second line of each test case contains $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the maximum possible diameter of the graph after performing at most $$$k$$$ operations.

NoteIn the first test case, one of the optimal arrays is $$$[2,4,5]$$$.The graph built on this array:   $$$\operatorname{d}(1, 2) = \operatorname{d}(1, 3) = 2$$$ and $$$\operatorname{d}(2, 3) = 4$$$, so the diameter is equal to $$$\max(2,2,4) = 4$$$.

package main

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

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

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, k int
		fmt.Fscan(r, &n, &k)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(r, &a[i])
		}
		w1 := do(n, k, a)
		fmt.Fprintln(w, w1)
	}
}

func do(n, k int, a []int) int {
	mx := int(1e9)
	if k >= n {
		return mx
	}
	b := make([]int, n)
	for i := range b {
		b[i] = i
	}
	sort.Slice(b, func(i, j int) bool {
		return a[b[i]] < a[b[j]]
	})
	t := &node{l: 1, r: n - 1}
	for i := 0; i < k-1; i++ {
		a[b[i]] = 1e9
	}
	for i := 1; i < n; i++ {
		v := a[i-1]
		if v > a[i] {
			v = a[i]
		}
		set(t, i, v)
	}
	r := 0
	for i := k - 1; i < n; i++ {
		var x, y int
		if b[i] > 0 {
			x = get(t, b[i], b[i])
			set(t, b[i], a[b[i]-1])
		}
		if b[i] < n-1 {
			y = get(t, b[i]+1, b[i]+1)
			set(t, b[i]+1, a[b[i]+1])
		}
		w := 2 * a[b[k-1]]
		if i == k-1 {
			if k < n {
				w = 2 * a[b[k]]
			} else {
				w = 2 * mx
			}
		}
		v := get(t, 1, n-1)
		if v > w {
			v = w
		}
		if r < v {
			r = v
		}
		if b[i] > 0 {
			set(t, b[i], x)
		}
		if b[i] < n-1 {
			set(t, b[i]+1, y)
		}
	}
	// dia<=2min{a_i}
	// dia<=max{min{a_i,a_{i+1}}}
	// max dia
	return r
}

type node struct {
	l, r, v int
	ln, rn  *node
}

func set(n *node, x, v int) {
	if n.l == n.r {
		n.v = v
		return
	}
	m := (n.l + n.r) / 2
	if n.ln == nil {
		n.ln = &node{l: n.l, r: m}
		n.rn = &node{l: m + 1, r: n.r}
	}
	if x <= m {
		set(n.ln, x, v)
	} else {
		set(n.rn, x, v)
	}
	n.v = n.ln.v
	if n.v < n.rn.v {
		n.v = n.rn.v
	}
}

func get(n *node, l, r int) int {
	if l <= n.l && n.r <= r {
		return n.v
	}
	m := (n.l + n.r) / 2
	if r <= m {
		return get(n.ln, l, r)
	} else if l >= m+1 {
		return get(n.rn, l, r)
	} else {
		v := get(n.ln, l, m)
		if v2 := get(n.rn, m+1, r); v < v2 {
			v = v2
		}
		return v
	}
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, k := readTwoNums(reader)
		P := readNNums(reader, n)
		res := solve(k, P)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}

	fmt.Print(buf.String())
}

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

func normalize(s string) string {

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

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

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

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

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

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

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

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

	return i
}

const X = 1000000000

func solve(k int, A []int) int {
	n := len(A)
	cnt := make([]int, n+1)

	check := func(x int) bool {
		if x > X {
			return false
		}
		// can we get x as the result within k steps
		for i := 0; i < n; i++ {
			cnt[i+1] = cnt[i]
			if 2*A[i] < x {
				cnt[i+1]++
			}
		}

		for i := 0; i+1 < n; i++ {
			kk := k
			if A[i] < x {
				kk--
			}
			if A[i+1] < x {
				kk--
			}
			if kk < 0 {
				continue
			}
			x := cnt[i] + cnt[n] - cnt[i+2]
			if x <= kk {
				return true
			}
		}

		return false
	}

	l, r := 0, X+1

	for l < r {
		mid := (l + r) / 2
		if !check(mid) {
			r = mid
		} else {
			l = mid + 1
		}
	}

	return r - 1
}

package main

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

type void struct{}
var member void

var (
	reader bufio.Reader
	writer bufio.Writer
)

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

func btoi(b bool) int {
	if b {
		return 1
	} else {
		return 0
	}
}

func solve() {
	var n, k int
	scan(&n, &k)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		scan(&a[i])
	}

	if n == 2 {
		if k == 1 {
			printf("%v\n", max(a[0], a[1]))
		} else {
			printf("%v\n", 1000000000)
		}
		return
	}

	var f func(int) bool = func(mid int) bool {
		pref := make([]int, n)
		for i := 0; i < n; i++ {
			if i > 0 {
				pref[i] = pref[i - 1]
			}
			if a[i] * 2 < mid {
				pref[i]++
			}
		}

		suf := make([]int, n)
		for i := n - 1; i >= 0; i-- {
			if i + 1 < n {
				suf[i] = suf[i + 1]
			}
			if a[i] * 2 < mid {
				suf[i]++
			}
		}

		for i := 1; i < n - 2; i++ {
			var now int = btoi(a[i] < mid) + btoi(a[i + 1] < mid)
			if now + pref[i - 1] + suf[i + 2] <= k {
				return true
			}
		}

		{
			var now int = btoi(a[0] < mid) + btoi(a[1] < mid)
			if now + suf[2] <= k {
				return true
			}
		}

		{
			var now int = btoi(a[n - 2] < mid) + btoi(a[n - 1] < mid)
			if now + pref[n - 3] <= k {
				return true
			}
		}

		return false
	};

	var l, r int = 0, 1e9 + 1
	for ; r - l > 1; {
		var mid int = (l + r) / 2
		if f(mid) {
			l = mid
		} else {
			r = mid
		}
	}

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

func main() {
	inp, err := os.Open("in.txt")
	if err == nil {
		os.Stdin = inp
		outp, _ := os.Create("out.txt")
		os.Stdout = outp
		defer outp.Close()
		defer inp.Close()
	}
	reader = *bufio.NewReader(os.Stdin)
	writer = *bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var T int
	T = 1
	scan(&T)

	for ; T > 0; T-- {
		solve()
	}
}

func scan(a ...interface{}) (n int, err error) {
	return fmt.Fscan(&reader, a...)
}

func printf(format string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(&writer, format, a...)
}

package main

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

func readLine() string {
	s, err := in.ReadString('\n')
	if err != nil {
		panic(err)
	}
	s = strings.ReplaceAll(s, "\n", "")
	s = strings.ReplaceAll(s, "\r", "")
	return s
}

func readLines(n int) []string {
	res := make([]string, n)
	for i := 0; i < n; i++ {
		res[i] = readLine()
	}
	return res
}

func readInt() int {
	n, err := strconv.ParseInt(readLine(), 10, 32)
	if err != nil {
		panic(err)
	}
	return int(n)
}

func readInt2() (int, int) {
	as := readInts(2)
	return as[0], as[1]
}

func readInt3() (int, int, int) {
	as := readInts(3)
	return as[0], as[1], as[2]
}

func readUint() uint64 {
	n, err := strconv.ParseUint(readLine(), 10, 64)
	if err != nil {
		panic(err)
	}
	return n
}

func readInts(n int) []int {
	s := readLine()
	as := strings.SplitN(s, " ", n)
	if len(as) != n {
		panic("invalid len")
	}
	arr := make([]int, n)
	for k, a := range as {
		x, _ := strconv.ParseInt(a, 10, 64)
		arr[k] = int(x)
	}
	return arr
}

func readStrings(n int) []string {
	s := readLine()
	as := strings.SplitN(s, " ", n)
	if len(as) != n {
		panic("invalid len")
	}
	return as
}

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

const N, MAXN int = 1e5 + 7, 1e9

var in = bufio.NewReader(os.Stdin)
var a, b [N]int

func maxVal(u, v int) int {
	if u > v {
		return u
	}
	return v
}

func minVal(u, v int) int {
	if u < v {
		return u
	}
	return v
}

func check(n, k, val int) bool {
	cnt := 0
	for i := 1; i <= n; i++ {
		b[i] = a[i]
		if a[i]*2 < val {
			cnt++
			b[i] = MAXN
		}
	}
	if cnt > k {
		return false
	} else if cnt == k {
		maxv := 0
		for i := 1; i < n; i++ {
			maxv = maxVal(maxv, minVal(b[i], b[i+1]))
		}
		return maxv >= val
	} else if cnt+1 == k {
		maxv := 0
		for i := 1; i <= n; i++ {
			maxv = maxVal(maxv, b[i])
		}
		return maxv >= val
	} else {
		return true
	}
}

func main() {
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t, n, k, l, r, mid, ans int
	fmt.Fscan(in, &t)
	for ; t != 0; t-- {
		fmt.Fscan(in, &n, &k)
		for i := 1; i <= n; i++ {
			fmt.Fscan(in, &a[i])
		}
		l, r, ans = 1, MAXN, -1
		for l <= r {
			mid = (l + r) >> 1
			if check(n, k, mid) {
				l, ans = mid+1, mid
			} else {
				r = mid - 1
			}
		}
		fmt.Fprintln(out, ans)
	}

}

package main

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

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

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, k int
		fmt.Fscan(r, &n, &k)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(r, &a[i])
		}
		if ti == 33 {
			fmt.Fprintln(w, n, k)
			for i := range a {
				fmt.Fprint(w, a[i], " ")
			}
			fmt.Fprintln(w)
		}
		w1 := do(n, k, a)
		fmt.Fprintln(w, w1)
	}
}

func do(n, k int, a []int) int {
	if k >= n {
		return 1e9
	}
	b := make([]int, n)
	for i := range b {
		b[i] = i
	}
	sort.Slice(b, func(i, j int) bool {
		return a[b[i]] < a[b[j]]
	})
	for i := 0; i < k; i++ {
		a[b[i]] = 1e9
	}
	r := a[b[k]]
	x := 2 * r
	for i := 1; i < n; i++ {
		y := a[i-1]
		if y > a[i] {
			y = a[i]
		}
		if y >= x {
			r = x
			break
		}
		if r < y {
			r = y
		}
	}
	return r
}

package main

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

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

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, k int
		fmt.Fscan(r, &n, &k)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(r, &a[i])
		}
		w1 := do(n, k, a)
		fmt.Fprintln(w, w1)
	}
}

func do(n, k int, a []int) int {
	if k >= n {
		return 1e9
	}
	b := make([]int, n)
	for i := range b {
		b[i] = i
	}
	sort.Slice(b, func(i, j int) bool {
		return a[b[i]] < a[b[j]]
	})
	for i := 0; i < k; i++ {
		a[b[i]] = 1e9
	}
	x := 2 * a[b[k]]
	r := 0
	for i := 1; i < n; i++ {
		y := a[i-1]
		if y > a[i] {
			y = a[i]
		}
		if y >= x {
			r = x
			break
		}
		if r < y {
			r = y
		}
	}
	return r
}