Let's call an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$ a $$$k$$$-extension for some non-negative integer $$$k$$$ if for all possible pairs of indices $$$1 \leq i, j \leq n$$$ the inequality $$$k \cdot |i - j| \leq min(a_i, a_j)$$$ is satisfied. The expansion coefficient of the array $$$a$$$ is the maximal integer $$$k$$$ such that the array $$$a$$$ is a $$$k$$$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.You are given an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Find its expansion coefficient.

The first line contains one positive integer $$$n$$$ — the number of elements in the array $$$a$$$ ($$$2 \leq n \leq 300\,000$$$). The next line contains $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces ($$$0 \leq a_i \leq 10^9$$$).

Print one non-negative integer — expansion coefficient of the array $$$a_1, a_2, \ldots, a_n$$$.

NoteIn the first test, the expansion coefficient of the array $$$[6, 4, 5, 5]$$$ is equal to $$$1$$$ because $$$|i-j| \leq min(a_i, a_j)$$$, because all elements of the array satisfy $$$a_i \geq 3$$$. On the other hand, this array isn't a $$$2$$$-extension, because $$$6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5$$$ is false.In the second test, the expansion coefficient of the array $$$[0, 1, 2]$$$ is equal to $$$0$$$ because this array is not a $$$1$$$-extension, but it is $$$0$$$-extension.

package main

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

func main() {

	var read = bufio.NewReader(os.Stdin)
	var write = bufio.NewWriter(os.Stdout)
	defer write.Flush()
	var n int
	fmt.Fscan(read, &n)
	mink := 1000000000
	for i := 0; i < n; i++ {
		var x int
		fmt.Fscan(read, &x)
		d := i
		if (n - 1 - i) > d {
			d = n - 1 - i
		}
		k := x / d
		if k < mink {
			mink = k
		}
	}
	fmt.Fprint(write, mink)

}

package main

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

var DEBUG = true

func main() {
	defer Flush()

	N, A := readInts(0)

	k := 1001001001

	for i, a := range A {
		if 0 < i {
			k1 := a/i + 1
			k = min(k, k1)
			for a < k*i {
				k--
			}
		}
		if i < N-1 {
			d := N - 1 - i
			k1 := a/d + 1
			k = min(k, k1)
			for a < k*d {
				k--
			}
		}
	}
	println(k)
}

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

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

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

func dbgf(f string, args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintf(os.Stderr, f, args...)
}

func dbg(args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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 minf(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}

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

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

func maxf(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

func absf(a float64) float64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}

package main

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

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

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

	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())

	if err != nil {
		fmt.Println("err getting n ", err)
	}

	arr := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		arr[i], _ = strconv.Atoi(scanner.Text())
	}

	minSeen := math.MaxInt32
	for i := 0; i < len(arr); i++ {
		if i != 0 {
			minSeen = min(minSeen, min(arr[0], arr[i])/i)
		}
		if i != len(arr)-1 {
			minSeen = min(minSeen, min(arr[i], arr[len(arr)-1])/(len(arr)-1-i))
		}
	}

	fmt.Println(minSeen)
}

package main

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

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

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

func Solve(n int, a []int) int {
	k := int(math.Pow10(9))
	for i, elem := range a {
		d := max(i, n-i-1)
		k = min(k, elem/d)
	}
	return k
}

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

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

package main

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())

	if err != nil {
		fmt.Println("err getting n ", err)
	}

	arr := make([]int, n)
	index := 0
	for {
		more := scanner.Scan()
		if !more {
			break
		}
		arrStr := strings.Fields(scanner.Text())
		for i := 0; i < len(arrStr); i++ {
			temp, err := strconv.Atoi(arrStr[i])
			if err != nil {
				fmt.Println(err)
			}
			arr[index] = temp
			index++
		}
	}

	if index != n {
		fmt.Println("index did not finish,", index)
	}

	minSeen := math.MaxInt32
	for i := 0; i < len(arr); i++ {
		if i != 0 {
			minSeen = min(minSeen, min(arr[0], arr[i])/i)
		}
		if i != len(arr)-1 {
			minSeen = min(minSeen, min(arr[i], arr[len(arr)-1])/(len(arr)-1-i))
		}
	}

	fmt.Println(minSeen)
}

package main

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

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

func readInt(reader *bufio.Reader) int {
	str, _ := reader.ReadString('\n')
	i, _ := strconv.Atoi(str[:len(str)-1])
	return i
}

func readline(reader *bufio.Reader) string {
	str, _ := reader.ReadString('\n')
	return str[:len(str)-1]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	arr := make([]int, n)
	scanner.Scan()
	arrStr := strings.Split(scanner.Text(), " ")
	for i := 0; i < n; i++ {
		arr[i], _ = strconv.Atoi(arrStr[i])
	}
	fmt.Println("input = ", n, arr)

	minSeen := math.MaxInt32
	for i := 0; i < len(arr); i++ {
		if i != 0 {
			minSeen = min(minSeen, min(arr[0], arr[i])/i)
		}
		if i != len(arr)-1 {
			minSeen = min(minSeen, min(arr[i], arr[len(arr)-1])/(len(arr)-1-i))
		}
	}

	fmt.Println(minSeen)
}

package main

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())

	if err != nil {
		fmt.Println("err getting n ", err)
	}

	arr := make([]int, n)
	index := 0
	for {
		more := scanner.Scan()
		if !more {
			break
		}
		arrStr := strings.Fields(scanner.Text())
		for i := 0; i < len(arrStr); i++ {
			temp, err := strconv.Atoi(arrStr[i])
			if err != nil {
				fmt.Fprintln(os.Stderr, err)
			}
			arr[index] = temp
			index++
		}
	}

	if index != n {
		fmt.Println("index did not finish,", index)
	}

	minSeen := math.MaxInt32
	for i := 0; i < len(arr); i++ {
		if i != 0 {
			minSeen = min(minSeen, min(arr[0], arr[i])/i)
		}
		if i != len(arr)-1 {
			minSeen = min(minSeen, min(arr[i], arr[len(arr)-1])/(len(arr)-1-i))
		}
	}

	fmt.Println(minSeen)
}

package main

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())

	if err != nil {
		fmt.Println("err getting n ", err)
	}

	arr := make([]int, n)
	index := 0
	for {
		more := scanner.Scan()
		if !more {
			break
		}
		arrStr := strings.Fields(scanner.Text())
		for i := 0; i < len(arrStr); i++ {
			temp, err := strconv.Atoi(arrStr[i])
			if err != nil {
				fmt.Println(err)
			}
			arr[index] = temp
			index++
		}
	}

	minSeen := math.MaxInt32
	for i := 0; i < len(arr); i++ {
		if i != 0 {
			minSeen = min(minSeen, min(arr[0], arr[i])/i)
		}
		if i != len(arr)-1 {
			minSeen = min(minSeen, min(arr[i], arr[len(arr)-1])/(len(arr)-1-i))
		}
	}

	fmt.Println(minSeen)
}


The Narrator has an integer array $$$a$$$ of length $$$n$$$, but he will only tell you the size $$$n$$$ and $$$q$$$ statements, each of them being three integers $$$i, j, x$$$, which means that $$$a_i \mid a_j = x$$$, where $$$|$$$ denotes the bitwise OR operation.Find the lexicographically smallest array $$$a$$$ that satisfies all the statements.An array $$$a$$$ is lexicographically smaller than an array $$$b$$$ of the same length if and only if the following holds:   in the first position where $$$a$$$ and $$$b$$$ differ, the array $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.

In the first line you are given with two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$). In the next $$$q$$$ lines you are given with three integers $$$i$$$, $$$j$$$, and $$$x$$$ ($$$1 \le i, j \le n$$$, $$$0 \le x < 2^{30}$$$) — the statements. It is guaranteed that all $$$q$$$ statements hold for at least one array.

On a single line print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{30}$$$) — array $$$a$$$.

package main

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

const MOD int64 = 1000000007

var n, q int

var a [][3]int

var graph [][][2]int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

	fmt.Fscan(read, &n, &q)

	a = make([][3]int, q)

	graph = make([][][2]int, n)

	for j := 0; j < q; j++ {
		fmt.Fscan(read, &a[j][0], &a[j][1], &a[j][2])
		a[j][0]--
		a[j][1]--

		if a[j][0] == a[j][1] {
			graph[a[j][0]] = append(graph[a[j][0]], [2]int{a[j][1], a[j][2]})
		} else {
			graph[a[j][0]] = append(graph[a[j][0]], [2]int{a[j][1], a[j][2]})
			graph[a[j][1]] = append(graph[a[j][1]], [2]int{a[j][0], a[j][2]})
		}

	}

	solve()
	fmt.Println()

}

type pair struct {
	v int
	idx []int
}

func solve()  {

	ans := make([]int, n)

	for b := 30; b>= 0; b-- {

		mp := make(map[int]bool)
		seen := make([]bool, n)

		for i := 0; i < q; i++ {
			if (a[i][2] >> uint(b)) & 0x1 == 0 {
				mp[a[i][0]] = true
				mp[a[i][1]] = true

				seen[a[i][0]] = true
				seen[a[i][1]] = true
			} else {
				if a[i][0] == a[i][1] {

					ans[a[i][0]] = ans[a[i][0]] | (1 << uint(b))

					seen[a[i][0]] = true

				}
			}
		}

		for k,_ := range mp {

			for j := 0; j < len(graph[k]); j++ {
				idx := graph[k][j][0]
				if  seen[idx] {
					continue
				}
				seen[idx] = true

				ans[idx] = ans[idx] | (1 << uint(b))
			}
		}

		for i := 0; i < n; i++ {
			if seen[i] {
				continue
			}
			seen[i] = true

			ed := graph[i]

			for j := 0; j < len(ed); j++ {
				e := ed[j]

				if seen[e[0]] {
					continue
				}

				seen[e[0]] = true

				idx := e[0]

				ans[idx] = ans[idx] | (1 << uint(b))
			}

		}
	}

	for j := 0; j < n; j++ {
		fmt.Print(ans[j], " ")
	}
}

//IQ = 87

//........105....99...87..87..87..87.87.......87....

//            86

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

package main

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

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

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

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

const mx = 30

func do(n, m int, a [][3]int) []int {
	r := make([]int, n)
	for i := range r {
		r[i] = 1<<mx - 1
	}
	for _, a := range a {
		i, j, x := a[0]-1, a[1]-1, a[2]
		r[i] &= x
		r[j] &= x
	}
	t := make(map[int][]int)
	for _, a := range a {
		i, j := a[0]-1, a[1]-1
		t[i] = append(t[i], j)
		t[j] = append(t[j], i)
	}
	for i := range r {
		if len(t[i]) == 0 {
			r[i] = 0
			continue
		}
		s := r[t[i][0]]
		for k := 1; k < len(t[i]); k++ {
			j := t[i][k]
			if i == j {
				s = 0
				break
			}
			s &= r[j]
		}
		r[i] ^= s
	}
	return r
}

package main

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

const MOD int64 = 1000000007

var n, q int

var a [][3]int

var graph [][][2]int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

	fmt.Fscan(read, &n, &q)

	a = make([][3]int, q)

	graph = make([][][2]int, n)

	for j := 0; j < q; j++ {
		fmt.Fscan(read, &a[j][0], &a[j][1], &a[j][2])
		a[j][0]--
		a[j][1]--

		graph[a[j][0]] = append(graph[a[j][0]], [2]int{a[j][1], a[j][2]})
		graph[a[j][1]] = append(graph[a[j][1]], [2]int{a[j][0], a[j][2]})

	}

	solve()
	fmt.Println()

}

type pair struct {
	v int
	idx []int
}

func solve()  {

	ans := make([]int, n)

	for b := 30; b>= 0; b-- {

		mp := make(map[int]bool)
		seen := make([]bool, n)

		for i := 0; i < q; i++ {
			if (a[i][2] >> uint(b)) & 0x1 == 0 {
				mp[a[i][0]] = true
				mp[a[i][1]] = true

				seen[a[i][0]] = true
				seen[a[i][1]] = true
			}
		}

		for k,_ := range mp {

			for j := 0; j < len(graph[k]); j++ {
				idx := graph[k][j][0]
				if  seen[idx] {
					continue
				}
				seen[idx] = true

				ans[idx] = ans[idx] | (1 << uint(b))
			}
		}

		for i := 0; i < n; i++ {
			if seen[i] {
				continue
			}
			seen[i] = true

			ed := graph[i]

			for j := 0; j < len(ed); j++ {
				e := ed[j]

				if seen[e[0]] && e[0] != i {
					continue
				}

				seen[e[0]] = true

				idx := e[0]

				ans[idx] = ans[idx] | (1 << uint(b))
			}

		}
	}

	for j := 0; j < n; j++ {
		fmt.Print(ans[j], " ")
	}
}

//IQ = 87

//........105....99...87..87..87..87.87.......87....

//            86

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

package main

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

const MOD int64 = 1000000007

var n, q int

var a [][3]int

var graph [][][2]int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

	fmt.Fscan(read, &n, &q)

	a = make([][3]int, q)

	graph = make([][][2]int, n)

	for j := 0; j < q; j++ {
		fmt.Fscan(read, &a[j][0], &a[j][1], &a[j][2])
		a[j][0]--
		a[j][1]--

		if a[j][0] < a[j][1] {
			graph[a[j][0]] = append(graph[a[j][0]], [2]int{a[j][1], a[j][2]})
		} else {
			graph[a[j][1]] = append(graph[a[j][1]], [2]int{a[j][0], a[j][2]})
		}
	}

	solve()
	fmt.Println()

}

type pair struct {
	v int
	idx []int
}

func solve()  {

	ans := make([]int, n)

	for b := 30; b>= 0; b-- {

		mp := make(map[int]bool)
		seen := make([]bool, n)

		for i := 0; i < q; i++ {
			if (a[i][2] >> uint(b)) & 0x1 == 0 {
				mp[a[i][0]] = true
				mp[a[i][1]] = true

				seen[a[i][0]] = true
				seen[a[i][1]] = true
			}
		}

		for k,_ := range mp {

			for j := 0; j < len(graph[k]); j++ {
				idx := graph[k][j][0]
				if  seen[idx] {
					continue
				}
				seen[idx] = true

				ans[idx] = ans[idx] | (1 << uint(b))
			}
		}

		for i := 0; i < n; i++ {
			if seen[i] {
				continue
			}
			seen[i] = true

			ed := graph[i]

			for j := 0; j < len(ed); j++ {
				e := ed[j]

				if seen[e[0]] && e[0] != i {
					continue
				}

				seen[e[0]] = true

				idx := e[0]

				ans[idx] = ans[idx] | (1 << uint(b))
			}

		}
	}

	for j := 0; j < n; j++ {
		fmt.Print(ans[j], " ")
	}
}

//IQ = 87

//........105....99...87..87..87..87.87.......87....

//            86

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

package main

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

const MOD int64 = 1000000007

var n, q int

var a [][3]int

var graph [][][2]int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

	fmt.Fscan(read, &n, &q)

	a = make([][3]int, q)

	graph = make([][][2]int, n)

	for j := 0; j < q; j++ {
		fmt.Fscan(read, &a[j][0], &a[j][1], &a[j][2])
		a[j][0]--
		a[j][1]--

		if a[j][0] < a[j][1] {
			graph[a[j][0]] = append(graph[a[j][0]], [2]int{a[j][1], a[j][2]})
		} else {
			graph[a[j][1]] = append(graph[a[j][1]], [2]int{a[j][0], a[j][2]})
		}
	}

	solve()
	fmt.Println()

}

type pair struct {
	v int
	idx []int
}

func solve()  {

	ans := make([]int, n)

	for b := 30; b>= 0; b-- {

		mp := make(map[int]bool)
		seen := make([]bool, n)

		for i := 0; i < q; i++ {
			if (a[i][2] >> uint(b)) & 0x1 == 0 {
				mp[a[i][0]] = true
				mp[a[i][1]] = true

				seen[a[i][0]] = true
				seen[a[i][1]] = true
			}
		}

		for k,_ := range mp {

			for j := 0; j < len(graph[k]); j++ {
				idx := graph[k][j][0]
				if  seen[idx] {
					continue
				}
				seen[idx] = true

				ans[idx] = ans[idx] | (1 << uint(b))
			}
		}

		for i := 0; i < n; i++ {
			if seen[i] {
				continue
			}
			seen[i] = true

			ed := graph[i]

			for j := 0; j < len(ed); j++ {
				e := ed[j]

				if seen[e[0]] && e[0] != i {
					continue
				}

				idx := e[0]

				ans[idx] = ans[idx] | (1 << uint(b))
			}

		}
	}

	for j := 0; j < n; j++ {
		fmt.Print(ans[j], " ")
	}
}

//IQ = 87

//........105....99...87..87..87..87.87.......87....

//            86

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


You are given two arrays: an array $$$a$$$ consisting of $$$n$$$ zeros and an array $$$b$$$ consisting of $$$n$$$ integers.You can apply the following operation to the array $$$a$$$ an arbitrary number of times: choose some subsegment of $$$a$$$ of length $$$k$$$ and add the arithmetic progression $$$1, 2, \ldots, k$$$ to this subsegment — i. e. add $$$1$$$ to the first element of the subsegment, $$$2$$$ to the second element, and so on. The chosen subsegment should be inside the borders of the array $$$a$$$ (i.e., if the left border of the chosen subsegment is $$$l$$$, then the condition $$$1 \le l \le l + k - 1 \le n$$$ should be satisfied). Note that the progression added is always $$$1, 2, \ldots, k$$$ but not the $$$k, k - 1, \ldots, 1$$$ or anything else (i.e., the leftmost element of the subsegment always increases by $$$1$$$, the second element always increases by $$$2$$$ and so on).Your task is to find the minimum possible number of operations required to satisfy the condition $$$a_i \ge b_i$$$ for each $$$i$$$ from $$$1$$$ to $$$n$$$. Note that the condition $$$a_i \ge b_i$$$ should be satisfied for all elements at once.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$) — the number of elements in both arrays and the length of the subsegment, respectively. The second line of the input contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 10^{12}$$$), where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.

Print one integer — the minimum possible number of operations required to satisfy the condition $$$a_i \ge b_i$$$ for each $$$i$$$ from $$$1$$$ to $$$n$$$.

NoteConsider the first example. In this test, we don't really have any choice, so we need to add at least five progressions to make the first element equals $$$5$$$. The array $$$a$$$ becomes $$$[5, 10, 15]$$$.Consider the second example. In this test, let's add one progression on the segment $$$[1; 3]$$$ and two progressions on the segment $$$[4; 6]$$$. Then, the array $$$a$$$ becomes $$$[1, 2, 3, 2, 4, 6]$$$.

package main

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

const (
	INF = 3e5 + 10
	L0  = int64(0)
	L1  = int64(1)
)

var n int64

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

	var k int64
	Fscan(in, &n, &k)

	a := make([]int64, n)
	b := make([]int64, n)
	for i := L0; i < n; i++ {
		Fscan(in, &a[i])
	}

	cur := L0
	ans := L0
	cnt := L0
	for i := n - 1; i >= 0; i-- {
		a[i] -= cur
		if a[i] > 0 {
			mx := min(i+1, k)
			nd := (a[i] + mx - 1) / mx
			cur += nd * mx
			cnt += nd
			b[i-mx+1] += nd
			ans += nd
		}
		cur -= cnt
		cnt -= b[i]
	}
	Fprintln(out, ans)

}

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

	return a
}


This is the easy version of the problem. The only difference between the versions is the constraints on $$$n$$$, $$$k$$$, $$$a_i$$$, and the sum of $$$n$$$ over all test cases. You can make hacks only if both versions of the problem are solved.Note the unusual memory limit.You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, and an integer $$$k$$$.The cost of an array of integers $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$ is $$$$$$\max\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right) - \min\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right).$$$$$$Here, $$$\lfloor \frac{x}{y} \rfloor$$$ denotes the integer part of the division of $$$x$$$ by $$$y$$$. Find the minimum cost of an array $$$p$$$ such that $$$1 \le p_i \le k$$$ for all $$$1 \le i \le n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 3000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_1 \le a_2 \le \ldots \le a_n \le 3000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$.

For each test case, print a single integer — the minimum possible cost of an array $$$p$$$ satisfying the condition above.

NoteIn the first test case, the optimal array is $$$p = [1, 1, 1, 2, 2]$$$. The resulting array of values of $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ is $$$[4, 5, 6, 4, 5]$$$. The cost of $$$p$$$ is $$$\max\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) - \min\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) = 6 - 4 = 2$$$. We can show that there is no array (satisfying the condition from the statement) with a smaller cost.In the second test case, one of the optimal arrays is $$$p = [12, 12, 12, 12, 12]$$$, which results in all $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ being $$$0$$$.In the third test case, the only possible array is $$$p = [1, 1, 1]$$$.

package main

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

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

	n := readInt(in)
	for i := 0; i < n; i++ {
		solution(in, out)
	}
}

func solution(in *bufio.Reader, out *bufio.Writer) {
	v := readArrInt(in)
	k := v[1]
	arr := readArrInt(in)

	best := math.MaxInt
	for i := 0; i <= 3000; i++ {
		tt := highestLowOffK(arr, k, i)
		if tt >= 0 {
			best = Min(best, i-tt)
			if best == 0 {
				break
			}
		}
	}

	out.WriteString(strconv.Itoa(best) + "\n")

}

func highestLowOffK(arr []int, k int, highest int) int {
	tops := math.MinInt
	low := 0
	high := highest

	for low <= high {
		mid := (low + high) / 2
		if canMakeAllBetween(arr, k, mid, highest) {
			tops = mid
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	return tops
}

func canMakeAllBetween(arr []int, k int, low int, high int) bool {
	for _, val := range arr {
		if !canMakeOneBetween(val, 1, k, low, high) {
			return false
		}
	}
	return true
}

func canMakeOneBetween(val int, low int, high int, lowtarget int, hightarget int) bool {
	for {
		if val/high > hightarget {
			return false
		}

		if val/low < lowtarget {
			return false
		}

		mid := (low + high) / 2
		if val/mid > hightarget {
			low = mid + 1
		} else if val/mid < lowtarget {
			high = mid - 1
		} else {
			return true
		}
	}
}

func Max(sum int, sum2 int) int {
	if sum > sum2 {
		return sum
	}
	return sum2

}

func Min(sum int, sum2 int) int {
	if sum < sum2 {
		return sum
	}
	return sum2
}

func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

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

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

package main

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

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

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

func rw(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 {
	ans := -1
	for v := 0; v <= a[0]; v++ {
		m1 := -1
		m2 := -1
		for _, va := range a {
			k2 := k
			if v > 0 && va/v < k {
				k2 = va / v
			}
			m := va / k2
			if m1 < 0 || m1 < m {
				m1 = m
			}
			if m2 < 0 || m2 > m {
				m2 = m
			}
		}
		if ans < 0 || ans > m1-m2 {
			ans = m1 - m2
		}
	}
	return ans
}

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)
		A := readNNums(reader, n)
		res := solve(A, k)
		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
}

func solve(A []int, k int) int {
	n := len(A)
	if n == 1 {
		return 0
	}
	ans := 1 << 30
	for v := 0; v <= A[0]; v++ {
		// if min value is v
		var tmp int
		for i := 0; i < n; i++ {
			p := k
			if v > 0 {
				p = min(k, A[i]/v)
			}
			tmp = max(A[i]/p-v, tmp)
		}
		ans = min(ans, tmp)
	}

	return ans
}

func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

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
}

package main

import (
	"bufio"
	"fmt"
	"os"
)
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
}
func abs(x int)int{
	if x<0{
		return -x
	}
	return x
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for t > 0{
		t--
		var n, k int
		fmt.Fscan(in,&n, &k)
		a := make([]int, n+5)
		mi := 989999
		for i:=1;i<=n;i++{
			fmt.Fscan(in,&a[i])
			mi = min(mi,a[i])
		}
		ret :=100000009
		for i:=0;i<=mi;i++{
			check := false
			ma := -1
			for j:=1;j<=n;j++{
				l := 1
				r := k
				ans := -1
				for l<=r{
					mid := (l+r)>>1
					if a[j]/mid >= i{
						ans = mid
						l = mid+1
					}else{
						r = mid-1
					}
				}
				if a[j]/ans==i{
					check = true
				}
				ma = max(ma,a[j]/ans)
			}
			if check {
				ret = min(ret,ma-i)
			}
		}
		fmt.Fprintln(out,ret)
	}
}

package main

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

const MOD int64 = 1000000007

var n, k int

var a[]int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

type Item struct {
	rightEnd int
	divideBy int
}

const LOCAL = false

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	if LOCAL {

		n = 1e5
		k = 1e5

		a = make([]int, 1e5)

		for i := 1; i <= 1e5; i++ {
			a[i - 1] = i
		}

		st := time.Now().UnixNano()
		solve()
		en := time.Now().UnixNano()

		fmt.Println((en - st)/1000000)

		return
	}

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &n, &k)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &a[j])
		}

		fmt.Println(solve())
	}
}

type pair struct {
	v int
	idx []int
}

func solve() int {

	var mn2 int = 1e6

	for i := a[n - 1]; i >= a[n - 1]/k; i-- {
		mx := i

		if i == 0 {
			return 0
		}

		var mn int = 1e6

		can := false

		for j := 0; j < n; j++ {
			if a[j] < mx {
				mn = min(mn, a[j])

			} else if a[j] > mx {
				if a[j]/k > mx {
					break
				}

				d := a[j]/mx
				if d > k {
					d = k
				} else {
					if a[j]/(d) > mx {
						d++
					}
				}

				t := a[j]/d

				if t == mx {
					can = true
				}

				mn = min(mn, t)

			} else {
				can = true
				mn = min(mn, a[j])
			}
		}

		if can {
			mn2 = min(mn2, mx - mn)
		}
	}
	return mn2
}

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

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

type intIntTreeMap struct {
	endNode   *nodeIntIntTreeMap
	beginNode *nodeIntIntTreeMap
	count     int
	// Less returns a < b
	Less func(a int, b int) bool
}

type nodeIntIntTreeMap struct {
	right   *nodeIntIntTreeMap
	left    *nodeIntIntTreeMap
	parent  *nodeIntIntTreeMap
	isBlack bool
	key     int
	value   int
}

// New creates and returns new TreeMap.
// Parameter less is a function returning a < b.
func newIntIntTreeMap(less func(a int, b int) bool) *intIntTreeMap {
	endNode := &nodeIntIntTreeMap{isBlack: true}
	return &intIntTreeMap{beginNode: endNode, endNode: endNode, Less: less}
}

// Len returns total count of elements in a map.
// Complexity: O(1).
func (t *intIntTreeMap) Len() int { return t.count }

// Set sets the value and silently overrides previous value if it exists.
// Complexity: O(log N).
func (t *intIntTreeMap) Set(key int, value int) {
	parent := t.endNode
	current := parent.left
	less := true
	for current != nil {
		parent = current
		switch {
		case t.Less(key, current.key):
			current = current.left
			less = true
		case t.Less(current.key, key):
			current = current.right
			less = false
		default:
			current.value = value
			return
		}
	}
	x := &nodeIntIntTreeMap{parent: parent, value: value, key: key}
	if less {
		parent.left = x
	} else {
		parent.right = x
	}
	if t.beginNode.left != nil {
		t.beginNode = t.beginNode.left
	}
	t.insertFixup(x)
	t.count++
}

// Del deletes the value.
// Complexity: O(log N).
func (t *intIntTreeMap) Del(key int) {
	z := t.findNode(key)
	if z == nil {
		return
	}
	if t.beginNode == z {
		if z.right != nil {
			t.beginNode = z.right
		} else {
			t.beginNode = z.parent
		}
	}
	t.count--
	removeNodeIntIntTreeMap(t.endNode.left, z)
}

// Clear clears the map.
// Complexity: O(1).
func (t *intIntTreeMap) Clear() {
	t.count = 0
	t.beginNode = t.endNode
	t.endNode.left = nil
}

// Get retrieves a value from a map for specified key and reports if it exists.
// Complexity: O(log N).
func (t *intIntTreeMap) Get(id int) (int, bool) {
	node := t.findNode(id)
	if node == nil {
		node = t.endNode
	}
	return node.value, node != t.endNode
}

// Contains checks if key exists in a map.
// Complexity: O(log N)
func (t *intIntTreeMap) Contains(id int) bool { return t.findNode(id) != nil }

// Range returns a pair of iterators that you can use to go through all the keys in the range [from, to].
// More specifically it returns iterators pointing to lower bound and upper bound.
// Complexity: O(log N).
func (t *intIntTreeMap) Range(from, to int) (forwardIteratorIntIntTreeMap, forwardIteratorIntIntTreeMap) {
	return t.LowerBound(from), t.UpperBound(to)
}

// LowerBound returns an iterator pointing to the first element that is not less than the given key.
// Complexity: O(log N).
func (t *intIntTreeMap) LowerBound(key int) forwardIteratorIntIntTreeMap {
	result := t.endNode
	node := t.endNode.left
	if node == nil {
		return forwardIteratorIntIntTreeMap{tree: t, node: t.endNode}
	}
	for {
		if t.Less(node.key, key) {
			if node.right != nil {
				node = node.right
			} else {
				return forwardIteratorIntIntTreeMap{tree: t, node: result}
			}
		} else {
			result = node
			if node.left != nil {
				node = node.left
			} else {
				return forwardIteratorIntIntTreeMap{tree: t, node: result}
			}
		}
	}
}

// UpperBound returns an iterator pointing to the first element that is greater than the given key.
// Complexity: O(log N).
func (t *intIntTreeMap) UpperBound(key int) forwardIteratorIntIntTreeMap {
	result := t.endNode
	node := t.endNode.left
	if node == nil {
		return forwardIteratorIntIntTreeMap{tree: t, node: t.endNode}
	}
	for {
		if !t.Less(key, node.key) {
			if node.right != nil {
				node = node.right
			} else {
				return forwardIteratorIntIntTreeMap{tree: t, node: result}
			}
		} else {
			result = node
			if node.left != nil {
				node = node.left
			} else {
				return forwardIteratorIntIntTreeMap{tree: t, node: result}
			}
		}
	}
}

// Iterator returns an iterator for tree map.
// It starts at the first element and goes to the one-past-the-end position.
// You can iterate a map at O(N) complexity.
// Method complexity: O(1)
func (t *intIntTreeMap) Iterator() forwardIteratorIntIntTreeMap {
	return forwardIteratorIntIntTreeMap{tree: t, node: t.beginNode}
}

// Reverse returns a reverse iterator for tree map.
// It starts at the last element and goes to the one-before-the-start position.
// You can iterate a map at O(N) complexity.
// Method complexity: O(log N)
func (t *intIntTreeMap) Reverse() reverseIteratorIntIntTreeMap {
	node := t.endNode.left
	if node != nil {
		node = mostRightIntIntTreeMap(node)
	}
	return reverseIteratorIntIntTreeMap{tree: t, node: node}
}

func (t *intIntTreeMap) findNode(id int) *nodeIntIntTreeMap {
	current := t.endNode.left
	for current != nil {
		switch {
		case t.Less(id, current.key):
			current = current.left
		case t.Less(current.key, id):
			current = current.right
		default:
			return current
		}
	}
	return nil
}

func mostLeftIntIntTreeMap(x *nodeIntIntTreeMap) *nodeIntIntTreeMap {
	for x.left != nil {
		x = x.left
	}
	return x
}

func mostRightIntIntTreeMap(x *nodeIntIntTreeMap) *nodeIntIntTreeMap {
	for x.right != nil {
		x = x.right
	}
	return x
}

func successorIntIntTreeMap(x *nodeIntIntTreeMap) *nodeIntIntTreeMap {
	if x.right != nil {
		return mostLeftIntIntTreeMap(x.right)
	}
	for x != x.parent.left {
		x = x.parent
	}
	return x.parent
}

func predecessorIntIntTreeMap(x *nodeIntIntTreeMap) *nodeIntIntTreeMap {
	if x.left != nil {
		return mostRightIntIntTreeMap(x.left)
	}
	for x.parent != nil && x != x.parent.right {
		x = x.parent
	}
	return x.parent
}

func rotateLeftIntIntTreeMap(x *nodeIntIntTreeMap) {
	y := x.right
	x.right = y.left
	if x.right != nil {
		x.right.parent = x
	}
	y.parent = x.parent
	if x == x.parent.left {
		x.parent.left = y
	} else {
		x.parent.right = y
	}
	y.left = x
	x.parent = y
}

func rotateRightIntIntTreeMap(x *nodeIntIntTreeMap) {
	y := x.left
	x.left = y.right
	if x.left != nil {
		x.left.parent = x
	}
	y.parent = x.parent
	if x == x.parent.left {
		x.parent.left = y
	} else {
		x.parent.right = y
	}
	y.right = x
	x.parent = y
}

func (t *intIntTreeMap) insertFixup(x *nodeIntIntTreeMap) {
	root := t.endNode.left
	x.isBlack = x == root
	for x != root && !x.parent.isBlack {
		if x.parent == x.parent.parent.left {
			y := x.parent.parent.right
			if y != nil && !y.isBlack {
				x = x.parent
				x.isBlack = true
				x = x.parent
				x.isBlack = x == root
				y.isBlack = true
			} else {
				if x != x.parent.left {
					x = x.parent
					rotateLeftIntIntTreeMap(x)
				}
				x = x.parent
				x.isBlack = true
				x = x.parent
				x.isBlack = false
				rotateRightIntIntTreeMap(x)
				break
			}
		} else {
			y := x.parent.parent.left
			if y != nil && !y.isBlack {
				x = x.parent
				x.isBlack = true
				x = x.parent
				x.isBlack = x == root
				y.isBlack = true
			} else {
				if x == x.parent.left {
					x = x.parent
					rotateRightIntIntTreeMap(x)
				}
				x = x.parent
				x.isBlack = true
				x = x.parent
				x.isBlack = false
				rotateLeftIntIntTreeMap(x)
				break
			}
		}
	}
}

// nolint: gocyclo
//noinspection GoNilness
func removeNodeIntIntTreeMap(root *nodeIntIntTreeMap, z *nodeIntIntTreeMap) {
	var y *nodeIntIntTreeMap
	if z.left == nil || z.right == nil {
		y = z
	} else {
		y = successorIntIntTreeMap(z)
	}
	var x *nodeIntIntTreeMap
	if y.left != nil {
		x = y.left
	} else {
		x = y.right
	}
	var w *nodeIntIntTreeMap
	if x != nil {
		x.parent = y.parent
	}
	if y == y.parent.left {
		y.parent.left = x
		if y != root {
			w = y.parent.right
		} else {
			root = x // w == nil
		}
	} else {
		y.parent.right = x
		w = y.parent.left
	}
	removedBlack := y.isBlack
	if y != z {
		y.parent = z.parent
		if z == z.parent.left {
			y.parent.left = y
		} else {
			y.parent.right = y
		}
		y.left = z.left
		y.left.parent = y
		y.right = z.right
		if y.right != nil {
			y.right.parent = y
		}
		y.isBlack = z.isBlack
		if root == z {
			root = y
		}
	}
	if removedBlack && root != nil {
		if x != nil {
			x.isBlack = true
		} else {
			for {
				if w != w.parent.left {
					if !w.isBlack {
						w.isBlack = true
						w.parent.isBlack = false
						rotateLeftIntIntTreeMap(w.parent)
						if root == w.left {
							root = w
						}
						w = w.left.right
					}
					if (w.left == nil || w.left.isBlack) && (w.right == nil || w.right.isBlack) {
						w.isBlack = false
						x = w.parent
						if x == root || !x.isBlack {
							x.isBlack = true
							break
						}
						if x == x.parent.left {
							w = x.parent.right
						} else {
							w = x.parent.left
						}
					} else {
						if w.right == nil || w.right.isBlack {
							w.left.isBlack = true
							w.isBlack = false
							rotateRightIntIntTreeMap(w)
							w = w.parent
						}
						w.isBlack = w.parent.isBlack
						w.parent.isBlack = true
						w.right.isBlack = true
						rotateLeftIntIntTreeMap(w.parent)
						break
					}
				} else {
					if !w.isBlack {
						w.isBlack = true
						w.parent.isBlack = false
						rotateRightIntIntTreeMap(w.parent)
						if root == w.right {
							root = w
						}
						w = w.right.left
					}
					if (w.left == nil || w.left.isBlack) && (w.right == nil || w.right.isBlack) {
						w.isBlack = false
						x = w.parent
						if !x.isBlack || x == root {
							x.isBlack = true
							break
						}
						if x == x.parent.left {
							w = x.parent.right
						} else {
							w = x.parent.left
						}
					} else {
						if w.left == nil || w.left.isBlack {
							w.right.isBlack = true
							w.isBlack = false
							rotateLeftIntIntTreeMap(w)
							w = w.parent
						}
						w.isBlack = w.parent.isBlack
						w.parent.isBlack = true
						w.left.isBlack = true
						rotateRightIntIntTreeMap(w.parent)
						break
					}
				}
			}
		}
	}
}

// ForwardIterator represents a position in a tree map.
// It is designed to iterate a map in a forward order.
// It can point to any position from the first element to the one-past-the-end element.
type forwardIteratorIntIntTreeMap struct {
	tree *intIntTreeMap
	node *nodeIntIntTreeMap
}

// Valid reports if an iterator's position is valid.
// In other words it returns true if an iterator is not at the one-past-the-end position.
func (i forwardIteratorIntIntTreeMap) Valid() bool { return i.node != i.tree.endNode }

// Next moves an iterator to the next element.
// It panics if goes out of bounds.
func (i *forwardIteratorIntIntTreeMap) Next() {
	if i.node == i.tree.endNode {
		panic("out of bound iteration")
	}
	i.node = successorIntIntTreeMap(i.node)
}

// Prev moves an iterator to the previous element.
// It panics if goes out of bounds.
func (i *forwardIteratorIntIntTreeMap) Prev() {
	i.node = predecessorIntIntTreeMap(i.node)
	if i.node == nil {
		//panic("out of bound iteration")
	}
}

// Key returns a key at an iterator's position
func (i forwardIteratorIntIntTreeMap) Key() int { return i.node.key }

// Value returns a value at an iterator's position
func (i forwardIteratorIntIntTreeMap) Value() int { return i.node.value }

// ReverseIterator represents a position in a tree map.
// It is designed to iterate a map in a reverse order.
// It can point to any position from the one-before-the-start element to the last element.
type reverseIteratorIntIntTreeMap struct {
	tree *intIntTreeMap
	node *nodeIntIntTreeMap
}

// Valid reports if an iterator's position is valid.
// In other words it returns true if an iterator is not at the one-before-the-start position.
func (i reverseIteratorIntIntTreeMap) Valid() bool { return i.node != nil }

// Next moves an iterator to the next element in reverse order.
// It panics if goes out of bounds.
func (i *reverseIteratorIntIntTreeMap) Next() {
	if i.node == nil {
		panic("out of bound iteration")
	}
	i.node = predecessorIntIntTreeMap(i.node)
}

// Prev moves an iterator to the previous element in reverse order.
// It panics if goes out of bounds.
func (i *reverseIteratorIntIntTreeMap) Prev() {
	if i.node != nil {
		i.node = successorIntIntTreeMap(i.node)
	} else {
		i.node = i.tree.beginNode
	}
	if i.node == i.tree.endNode {
		panic("out of bound iteration")
	}
}

// Key returns a key at an iterator's position
func (i reverseIteratorIntIntTreeMap) Key() int { return i.node.key }

// Value returns a value at an iterator's position
func (i reverseIteratorIntIntTreeMap) Value() int { return i.node.value }

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1706D2(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	ge := [3001]int{}
	var T, n, k, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k)
		up := -1
		for ; n > 0; n-- {
			Fscan(in, &v)
			for i := up + 1; i <= v; i++ {
				ge[i] = v
			}
			up = v
		}
		if up <= k {
			Fprintln(out, 0)
			continue
		}
		ans := int(1e9)
	o:
		for mx := up / k; mx <= up; mx++ {
			mi := mx
			for j := 1; (j-1)*(mx+1) <= up; j++ {
				v := ge[(j-1)*(mx+1)]
				if v >= j*(mx+1) {
					j = v/(mx+1) + 1
				}
				if v/j < mi {
					mi = v / j
					if mx-mi >= ans {
						continue o
					}
				}
			}
			ans = mx - mi
		}
		Fprintln(out, ans)
	}
}

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

package main

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

const cf = true

func solve() {
	var n, k int
	fmt.Fscan(in, &n, &k)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscan(in, &arr[i])
	}
	ans := 3000
	for p := 0; p <= 3000; p++ {
		maxP := p
		good := true
		for i := range arr {
			pi := arr[i] + 1
			if p != 0 {
				pi = arr[i] / p
			}
			if pi == 0 {
				good = false
				break
			}
			pi = min(pi, k)
			maxP = max(maxP, arr[i]/pi)
			if pi > k {
				good = false
				break
			}
		}
		if !good {
			continue
		}
		ans = min(ans, maxP-p)
	}
	fmt.Fprintln(out, ans)
}

func main() {
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

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

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

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

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

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

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

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

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

var exists = struct{}{}

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

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

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

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

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

type Ordered interface {
	Integer | Float | ~string
}

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

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

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

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

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

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

package main

import (
	"bufio"
	"fmt"
	"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 {
	sort.Ints(a)
	ans := -1
	for i := 1; i <= k; i++ {
		min := a[0] / i
		if min == 0 {
			ans2 := a[n-1] / k
			if ans < 0 || ans > ans2 {
				ans = ans2
			}
			break
		}
		max := min
		for j := 1; j < n; j++ {
			k2 := a[j] / min
			if k2 > k {
				k2 = k
			}
			max2 := a[j] / k2
			if max < max2 {
				max = max2
			}
		}
		ans2 := max - min
		if ans < 0 || ans > ans2 {
			ans = ans2
		}
	}
	return 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])
		}
		w1 := do(n, k, a)
		fmt.Fprintln(w, w1)
	}
}

func do(n, k int, a []int) int {
	sort.Ints(a)
	ans := -1
	for i := 1; i <= k; i++ {
		min := a[0] / i
		max := min
		for j := 1; j < n; j++ {
			k2 := k
			if min != 0 {
				if v := a[j] / min; k2 > v {
					k2 = v
				}
			}
			max2 := a[j] / k2
			if max < max2 {
				max = max2
			}
		}
		ans2 := max - min
		if ans < 0 || ans > ans2 {
			ans = ans2
		}
	}
	return ans
}


You are given an array $$$a$$$ of $$$n$$$ integers, where $$$n$$$ is odd. You can make the following operation with it:  Choose one of the elements of the array (for example $$$a_i$$$) and increase it by $$$1$$$ (that is, replace it with $$$a_i + 1$$$). You want to make the median of the array the largest possible using at most $$$k$$$ operations.The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $$$[1, 5, 2, 3, 5]$$$ is $$$3$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n$$$ is odd, $$$1 \le k \le 10^9$$$) — the number of elements in the array and the largest number of operations you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print a single integer — the maximum possible median after the operations.

NoteIn the first example, you can increase the second element twice. Than array will be $$$[1, 5, 5]$$$ and it's median is $$$5$$$.In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $$$3$$$.In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $$$[5, 1, 2, 5, 3, 5, 5]$$$ and the median will be $$$5$$$.

package main

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

/* solution */

func solve() {

	n, k := readInt(), readInt()
	arr := make([]int, n+1)
	for i := 0; i < n; i++ {
		arr[i] = readInt()
	}
	arr[n] = 2000000001

	sort.Ints(arr)

	half := n / 2
	cur := half

	for {
		if arr[cur] == arr[cur+1] {
			cur++
		} else if k >= cur-half+1 {
			arr[cur]++
			k -= cur - half + 1
		} else {
			println(strconv.Itoa(arr[cur]))
			return
		}
	}

}

/* stubs */

func main() {

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

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

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

	solve()

}

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

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

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

func print(s string) {
	writer.WriteString(s)
}

func println(s string) {
	print(s)
	print("\n")
}


International Women's Day is coming soon! Polycarp is preparing for the holiday.There are $$$n$$$ candy boxes in the shop for sale. The $$$i$$$-th box contains $$$d_i$$$ candies.Polycarp wants to prepare the maximum number of gifts for $$$k$$$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $$$k$$$. In other words, two boxes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) can be combined as a gift if $$$d_i + d_j$$$ is divisible by $$$k$$$.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 100$$$) — the number the boxes and the number the girls. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$), where $$$d_i$$$ is the number of candies in the $$$i$$$-th box.

Print one integer — the maximum number of the boxes Polycarp can give as gifts.

NoteIn the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(2, 3)$$$;  $$$(5, 6)$$$;  $$$(1, 4)$$$. So the answer is $$$6$$$.In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(6, 8)$$$;  $$$(2, 3)$$$;  $$$(1, 4)$$$;  $$$(5, 7)$$$. So the answer is $$$8$$$.In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(1, 2)$$$;  $$$(6, 7)$$$. So the answer is $$$4$$$.

package main

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

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

	var n, k int
	var v int = 0
	fmt.Fscanf(buf, "%d %d\n", &n, &k)

	mat := make([]int, k)

	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &v)
		mat[v%k]++
	}
	fmt.Fscanf(buf, "\n")
	//fmt.Printf("%v\n",mat)
	ans := mat[0] / 2
	for i := 1; i <= k/2; i++ {
		if mat[i] > 0 && mat[k-i] > 0 {
			if i == k-i {
				ans += mat[i] / 2
			} else {
				if mat[i] < mat[k-i] {
					ans += mat[i]
				} else {
					ans += mat[k-i]
				}
			}
		}
	}
	fmt.Printf("%d\n", ans*2)

}

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

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

func (prob Prob) Solve() {
    n := prob.NextInt()
    m := prob.NextInt()
    var cnt [200000] int
    for i := 0; i < n; i++ {
        cnt[prob.NextInt() % m]++
    }
    res := 0
    for i := 0; i < m; i++ {
        j := (m - i) % m
        if i == j {
            res += cnt[i] / 2 * 2
        } else if i < j {
            res += Min(cnt[i], cnt[j]) * 2
        }
    }
    fmt.Printf("%d\n", res)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}

package main

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

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 getLine() string {
	s, _ := reader.ReadString('\n')
	for len(s) > 0 && (s[len(s)-1] == '\n' || s[len(s)-1] == '\r') {
		s = s[:len(s)-1]
	}
	return s
}

func main() {
	var n, k int
	scanf("%d %d\n", &n, &k)
	counts := make([]int, k)
	for i := 0; i < n; i++ {
		var x int
		scanf("%d", &x)
		counts[x%k]++
	}
	result := 0
	for i := 1; i*2 < k; i++ {
		if counts[i] < counts[k-i] {
			result += counts[i]
		} else {
			result += counts[k-i]
		}
	}
	if k%2 == 0 {
		result += counts[k/2] / 2
	}
	result = result*2 + counts[0]/2*2
	fmt.Println(result)
}

/*
URL:
https://codeforces.com/problemset/problem/1133/B
*/

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 (
	n, k int
	D    []int

	R [100 + 5]int
)

func main() {
	n, k = ReadInt2()
	D = ReadIntSlice(n)

	for i := 0; i < n; i++ {
		r := D[i] % k
		R[r]++
	}
	PrintfDebug("R: %v\n", R[:k])

	ans := 0
	for i := 0; i <= k/2; i++ {
		if i != k-i && i != 0 {
			ans += 2 * Min(R[i], R[k-i])
		} else {
			ans += R[i] - (R[i] % 2)
		}
	}
	fmt.Println(ans)
}

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

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

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

/*********** 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"
	. "fmt"
	"os"
)

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
)

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

func main() {
	defer out.Flush()
	var n, k int
	Fscan(in, &n, &k)
	a := make([]int, n)
	cnt := [100]int{}
	for i := 0; i < n; i++ {
		Fscan(in, &a[i])
		a[i] %= k
		cnt[a[i]]++
	}
	var ans = 0
	for i := 0; i < k; i++ {
		var mn int
		if (k-i)%k == i {
			mn = cnt[i] / 2
		} else {
			mn = min(cnt[i], cnt[k-i])
			cnt[i] -= mn
			cnt[k-i] -= mn
		}
		ans += mn
	}
	Fprint(out, ans*2)

}

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

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

func (prob Prob) Solve() {
    n := prob.NextInt()
    m := prob.NextInt()
    var cnt [200000] int
    for i := 0; i < n; i++ {
        cnt[prob.NextInt() % m]++
    }
    res := 0
    for i := 0; i < m; i++ {
        j := (m - i) % m
        if i == j {
            res += cnt[i] / 2 * 2
        } else if i < j {
            res += Min(cnt[i], cnt[j])
        }
    }
    fmt.Printf("%d\n", res)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

func (prob Prob) Solve() {
    n := prob.NextInt()
    m := prob.NextInt()
    var cnt [200000] int
    for i := 0; i < n; i++ {
        cnt[prob.NextInt() % m]++
    }
    res := 0
    for i := 0; i < m; i++ {
        res += cnt[i] / 2 * 2
    }
    fmt.Printf("%d\n", res)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
)

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

func main() {
	defer out.Flush()
	var n, k int
	Fscan(in, &n, &k)
	a := make([]int, n)
	cnt := [100]int{}
	for i := 0; i < n; i++ {
		Fscan(in, &a[i])
		a[i] %= k
		cnt[a[i]]++
	}
	var ans = 0
	for i := 0; i < k; i++ {
		var mn int
		if (k-i)%k == i {
			mn = cnt[i] / 2
		} else {
			mn = min(cnt[i], cnt[k-i])
			cnt[i] -= mn
			cnt[k-i] -= mn
		}
		Fprintln(out, mn)
		ans += mn
	}
	Fprint(out, ans*2)

}


After rejecting $$$10^{100}$$$ data structure problems, Errorgorn is very angry at Anton and decided to kill him.Anton's DNA can be represented as a string $$$a$$$ which only contains the characters "ANTON" (there are only $$$4$$$ distinct characters). Errorgorn can change Anton's DNA into string $$$b$$$ which must be a permutation of $$$a$$$. However, Anton's body can defend against this attack. In $$$1$$$ second, his body can swap $$$2$$$ adjacent characters of his DNA to transform it back to $$$a$$$. Anton's body is smart and will use the minimum number of moves.To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string $$$B$$$. Can you help him?

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 100000)$$$ — the number of testcases. The first and only line of each testcase contains $$$1$$$ string $$$a$$$ ($$$1 \leq |a| \leq 100000$$$). $$$a$$$ consists of only the characters "A", "N", "O" and "T". It is guaranteed that the sum of $$$|a|$$$ over all testcases does not exceed $$$100000$$$.

For each testcase, print a single string, $$$b$$$. If there are multiple answers, you can output any one of them. $$$b$$$ must be a permutation of the string $$$a$$$.

NoteFor the first testcase, it takes $$$7$$$ seconds for Anton's body to transform NNOTA to ANTON: NNOTA $$$\to$$$ NNOAT $$$\to$$$ NNAOT $$$\to$$$ NANOT $$$\to$$$ NANTO $$$\to$$$ ANNTO $$$\to$$$ ANTNO $$$\to$$$ ANTON. Note that you cannot output strings such as AANTON, ANTONTRYGUB, AAAAA and anton as it is not a permutation of ANTON.For the second testcase, it takes $$$2$$$ seconds for Anton's body to transform AANN to NAAN. Note that other strings such as NNAA and ANNA will also be accepted.

package main

import (
	"fmt"
)

func Max(vars ...int64) int64 {
	r := vars[0]
	for _, v := range vars {
		if v > r {
			r = v
		}
	}
	return r
}

func Min(vars ...int64) int64 {
	r := vars[0]
	for _, v := range vars {
		if v < r {
			r = v
		}
	}
	return r
}

var T int64
var S []byte
var N int64

func cal(R []byte) int64 {
	mp, mp0 := make(map[byte]int64), make(map[byte]int64)
	for i := int64(0); i < N; i++ {
		a := R[i]
		if _, ok := mp[a]; !ok {
			mp[a] = i
		}
		mp0[a] = i
	}

	var res int64
	for i := int64(0); i < N; i++ {
		a := S[i]
		for b, v := range mp {
			if b == a {
				continue
			}

			if v < mp[a] {
				res += mp0[b] - v + 1
			}
		}

		mp[a]++
	}
	return res
}

func dfs(cs []byte) [][]byte {
	if len(cs) == 1 {
		return [][]byte{cs}
	}

	res0 := dfs(cs[1:])
	res := [][]byte{}
	for _, vs := range res0 {
		lv := len(vs)
		for i := 0; i <= lv; i++ {
			cur := make([]byte, i)
			copy(cur, vs[:i])
			cur = append(cur, cs[0])
			cur = append(cur, vs[i:]...)
			res = append(res, cur)
		}
	}
	return res
}

func solve() string {
	mp := make(map[byte]int64)
	for i := int64(0); i < N; i++ {
		a := S[i]
		if _, ok := mp[a]; !ok {
			mp[a] = 0
		}
		mp[a]++
	}

	cs := []byte{}
	for k, _ := range mp {
		cs = append(cs, k)
	}

	css := dfs(cs)

	res, num := []byte{}, int64(-1)
	for _, cs := range css {
		r := []byte{}
		for _, c := range cs {
			for i := int64(0); i < mp[c]; i++ {
				r = append(r, c)
			}
		}

		n := cal(r)
		//fmt.Print64ln(string(r), n)
		if n > num {
			num = n
			res = r
		}
	}

	return string(res)
}

func main() {
	fmt.Scanf("%d\n", &T)

	for T > 0 {
		T--
		var s string
		fmt.Scanf("%s\n", &s)
		S = []byte(s)
		N = int64(len(S))
		fmt.Println(solve())
	}
}

package main

import (
	"bufio"
	"bytes"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	perm4 := [][]byte{
		{0, 1, 2, 3}, {0, 1, 3, 2}, {0, 2, 1, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}, {0, 3, 2, 1},
		{1, 0, 2, 3}, {1, 0, 3, 2}, {1, 2, 0, 3}, {1, 2, 3, 0}, {1, 3, 0, 2}, {1, 3, 2, 0},
		{2, 0, 1, 3}, {2, 0, 3, 1}, {2, 1, 0, 3}, {2, 1, 3, 0}, {2, 3, 0, 1}, {2, 3, 1, 0},
		{3, 0, 1, 2}, {3, 0, 2, 1}, {3, 1, 0, 2}, {3, 1, 2, 0}, {3, 2, 0, 1}, {3, 2, 1, 0},
	}
	const S = "ANOT"
	P := ['Z']byte{
		'A': 0,
		'N': 1,
		'O': 2,
		'T': 3,
	}
	solve := func(Case int) {
		var s []byte
		Fscan(in, &s)

		n := len(s)

		//pos := ['Z'][]int{}
		//for i, b := range s {
		//	pos[b] = append(pos[b], i)
		//}
		cnt := [4]int{}
		for i := range S {
			cnt[i] = bytes.Count(s, []byte{S[i]})
		}
		for i, b := range s {
			s[i] = P[b]
		}

		mxD := int64(-1)
		ans := []byte{}
		for _, p := range perm4 {
			d := int64(0)

			c := [4]int{}
			right := cnt
			for i, b := range s {
				k := 0
				tar := 0
				for ; p[k] != b; k++ {
					tar += cnt[p[k]]
					i += right[p[k]]
				}
				tar += c[b]
				right[b]--
				d += int64(i-tar)
			}

			if d > mxD {
				t := make([]byte, 0, n)
				for _, i := range p {
					t = append(t, bytes.Repeat([]byte{S[i]}, cnt[i])...)
				}
				mxD, ans = d, t
			}
		}
		Fprintf(out, "%s\n", ans)
	}

	T := 1
	Fscan(in, &T) //
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}
}

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

package main

import (
	"fmt"
)

func Max(vars ...int) int {
	r := vars[0]
	for _, v := range vars {
		if v > r {
			r = v
		}
	}
	return r
}

func Min(vars ...int) int {
	r := vars[0]
	for _, v := range vars {
		if v < r {
			r = v
		}
	}
	return r
}

var T int32
var S []byte
var N int

func cal(R []byte) int {
	mp, mp0 := make(map[byte]int), make(map[byte]int)
	for i := 0; i < N; i++ {
		a := R[i]
		if _, ok := mp[a]; !ok {
			mp[a] = i
		}
		mp0[a] = i
	}

	var res int
	for i := 0; i < N; i++ {
		a := S[i]
		for b, v := range mp {
			if b == a {
				continue
			}

			if v < mp[a] {
				res += mp0[b] - v + 1
			}
		}

		mp[a]++
	}
	return res
}

func dfs(cs []byte) [][]byte {
	if len(cs) == 1 {
		return [][]byte{cs}
	}

	res0 := dfs(cs[1:])
	res := [][]byte{}
	for _, vs := range res0 {
		lv := len(vs)
		for i := 0; i <= lv; i++ {
			cur := make([]byte, i)
			copy(cur, vs[:i])
			cur = append(cur, cs[0])
			cur = append(cur, vs[i:]...)
			res = append(res, cur)
		}
	}
	return res
}

func solve() string {
	mp := make(map[byte]int)
	for i := 0; i < N; i++ {
		a := S[i]
		if _, ok := mp[a]; !ok {
			mp[a] = 0
		}
		mp[a]++
	}

	cs := []byte{}
	for k, _ := range mp {
		cs = append(cs, k)
	}

	css := dfs(cs)

	res, num := []byte{}, -1
	for _, cs := range css {
		r := []byte{}
		for _, c := range cs {
			for i := 0; i < mp[c]; i++ {
				r = append(r, c)
			}
		}

		n := cal(r)
		//fmt.Println(string(r), n)
		if n > num {
			num = n
			res = r
		}
	}

	return string(res)
}

func main() {
	fmt.Scanf("%d\n", &T)

	for T > 0 {
		T--
		var s string
		fmt.Scanf("%s\n", &s)
		S = []byte(s)
		N = len(S)
		fmt.Println(solve())
	}
}

package main

import (
	"fmt"
)

func Max(vars ...int) int {
	r := vars[0]
	for _, v := range vars {
		if v > r {
			r = v
		}
	}
	return r
}

func Min(vars ...int) int {
	r := vars[0]
	for _, v := range vars {
		if v < r {
			r = v
		}
	}
	return r
}

var T int32
var S []byte
var N int

func cal(R []byte) int {
	mp := make(map[byte]int)
	for i := 0; i < N; i++ {
		a := R[i]
		if _, ok := mp[a]; !ok {
			mp[a] = i
		}
	}

	var res int
	for i := 0; i < N; i++ {
		a := S[i]
		mi := N
		for _, v := range mp {
			mi = Min(mi, v)
		}

		res += mp[a] - mi
		mp[a]++
	}
	return res
}

func dfs(cs []byte) [][]byte {
	if len(cs) == 1 {
		return [][]byte{cs}
	}

	res0 := dfs(cs[1:])
	res := [][]byte{}
	for _, vs := range res0 {
		lv := len(vs)
		for i := 0; i <= lv; i++ {
			cur := make([]byte, i)
			copy(cur, vs[:i])
			cur = append(cur, cs[0])
			cur = append(cur, vs[i:]...)
			res = append(res, cur)
		}
	}
	return res
}

func solve() string {
	mp := make(map[byte]int)
	for i := 0; i < N; i++ {
		a := S[i]
		if _, ok := mp[a]; !ok {
			mp[a] = 0
		}
		mp[a]++
	}

	cs := []byte{}
	for k, _ := range mp {
		cs = append(cs, k)
	}

	css := dfs(cs)

	res, num := []byte{}, -1
	for _, cs := range css {
		r := []byte{}
		for _, c := range cs {
			for i := 0; i < mp[c]; i++ {
				r = append(r, c)
			}
		}

		n := cal(r)
		// fmt.Println(r, n)
		if n > num {
			num = n
			res = r
		}
	}

	return string(res)
}

func main() {
	fmt.Scanf("%d\n", &T)

	for T > 0 {
		T--
		var s string
		fmt.Scanf("%s\n", &s)
		S = []byte(s)
		N = len(S)
		fmt.Println(solve())
	}
}

package main

import (
	"fmt"
	"math"
)

func Max(vars ...int) int {
	r := vars[0]
	for _, v := range vars {
		if v > r {
			r = v
		}
	}
	return r
}

func Min(vars ...int) int {
	r := vars[0]
	for _, v := range vars {
		if v < r {
			r = v
		}
	}
	return r
}

var T int32
var S []byte
var N int

func cal(R []byte) int {
	mp := make(map[byte]int)
	for i := 0; i < N; i++ {
		a := R[i]
		if _, ok := mp[a]; !ok {
			mp[a] = i
		}
	}

	var res int
	for i := 0; i < N; i++ {
		a := S[i]
		mi := N
		for _, v := range mp {
			mi = Min(mi, v)
		}

		res += mp[a] - mi
		mp[a]++
	}
	return res
}

func dfs(cs []byte) [][]byte {
	if len(cs) == 1 {
		return [][]byte{cs}
	}

	res0 := dfs(cs[1:])
	res := [][]byte{}
	for _, vs := range res0 {
		lv := len(vs)
		for i := 0; i <= lv; i++ {
			cur := make([]byte, i)
			copy(cur, vs[:i])
			cur = append(cur, cs[0])
			cur = append(cur, vs[i:]...)
			res = append(res, cur)
		}
	}
	return res
}

func solve() string {
	mp := make(map[byte]int)
	for i := 0; i < N; i++ {
		a := S[i]
		if _, ok := mp[a]; !ok {
			mp[a] = 0
		}
		mp[a]++
	}

	cs := []byte{}
	for k, _ := range mp {
		cs = append(cs, k)
	}

	css := dfs(cs)

	res, num := []byte{}, math.MaxInt
	for _, cs := range css {
		r := []byte{}
		for _, c := range cs {
			for i := 0; i < mp[c]; i++ {
				r = append(r, c)
			}
		}

		n := cal(r)
		if n < num {
			num = n
			res = r
		}
	}

	return string(res)
}

func main() {
	fmt.Scanf("%d\n", &T)

	for T > 0 {
		T--
		var s string
		fmt.Scanf("%s\n", &s)
		S = []byte(s)
		N = len(S)
		fmt.Println(solve())
	}
}

package main

import (
	"fmt"
	"sort"
)

var T int32
var S []byte

func solve() string {
	mp := make(map[byte][]int)
	ln := len(S)
	for i := 0; i < ln; i++ {
		a := S[i]
		if _, ok := mp[a]; !ok {
			mp[a] = []int{}

		}
		mp[a] = append(mp[a], i)
	}

	cs := []byte{}
	for k, _ := range mp {
		cs = append(cs, k)
	}

	sort.Slice(cs, func(i0, j0 int) bool {
		a, b := cs[i0], cs[j0]
		va, vb := mp[a], mp[b]
		la, lb := len(va), len(vb)
		i, j := 0, 0
		c := 0
		for j < lb {
			for i < la && va[i] < vb[j] {
				i++
			}
			c += la - i
			j++
		}

		d := 0
		i, j = 0, 0
		for i < la {
			for j < lb && vb[j] < va[i] {
				j++
			}
			c += lb - j
			i++
		}

		return c >= d
	})

	res := []byte{}
	for _, c := range cs {
		for i := 0; i < len(mp[c]); i++ {
			res = append(res, c)
		}
	}

	return string(res)
}

func main() {
	fmt.Scanf("%d\n", &T)

	for T > 0 {
		T--
		var s string
		fmt.Scanf("%s\n", &s)
		S = []byte(s)
		fmt.Println(solve())
	}
}

package main

import (
	"fmt"
)

type Node struct {
	next *Node
	pre  *Node
	val  byte
}

func newNode(val byte) *Node {
	node := new(Node)
	node.val = val
	return node
}

func (node *Node) append(nn *Node) {
	nn.next = node.next
	nn.pre = node
	node.next.pre = nn
	node.next = nn
}

var T int32
var S []byte

func solve() string {
	mp := make(map[byte]*Node)

	head, tail := newNode('-'), newNode('-')
	head.next = tail
	tail.pre = head
	ln := len(S)

	for i := 0; i < ln; i++ {
		a := S[i]
		if node, ok := mp[a]; !ok {
			mp[a] = newNode(a)
			head.append(mp[a])

		} else {
			nn := newNode(a)
			node.append(nn)
			mp[a] = nn
		}
	}

	res := []byte{}
	node := head.next
	for node.next != nil {
		res = append(res, node.val)
		node = node.next
	}

	return string(res)
}

func main() {
	fmt.Scanf("%d\n", &T)

	for T > 0 {
		T--
		var s string
		fmt.Scanf("%s\n", &s)
		S = []byte(s)
		fmt.Println(solve())
	}
}

package main

import (
	"fmt"
)

type Node struct {
	next *Node
	pre  *Node
	val  byte
}

func newNode(val byte) *Node {
	node := new(Node)
	node.val = val
	return node
}

func (node *Node) append(nn *Node) {
	nn.next = node.next
	nn.pre = node
	node.next.pre = nn
	node.next = nn
}

var T int32
var S []byte

func solve() string {
	mp := make(map[byte]*Node)

	head, tail := newNode('-'), newNode('-')
	head.next = tail
	tail.pre = head
	ln := len(S)

	for i := 0; i < ln; i++ {
		a := S[i]
		if node, ok := mp[a]; !ok {
			mp[a] = newNode(a)
			head.append(mp[a])

		} else {
			nn := newNode(a)
			node.append(nn)
			mp[a] = nn
		}
	}

	res := []byte{}
	node := head.next
	for node.next != nil {
		res = append(res, node.val)
		node = node.next
	}

	return string(res)
}

func main() {
	fmt.Scanf("%d", &T)

	for T > 0 {
		T--
		var s string
		fmt.Scanf("%s", &s)
		S = []byte(s)
		fmt.Println(solve())
	}
}


An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:   initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i. e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≤ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.

The first line contains two integers n and U (3 ≤ n ≤ 105, 1 ≤ U ≤ 109) — the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≤ E1 < E2... < En ≤ 109). It is guaranteed that all Ei are given in increasing order.

If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .

package main

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

var cs map[int]int = make(map[int]int)

func Init() {}
func Solve(io *FastIO) {
	n := io.NextInt()
	u := io.NextInt()
	a := io.NextIntArray(n)
	nu := float64(-1)
	var j int
	for i := 0; i < n-1; i++ {
		j = sort.Search(n, func(j int) bool { return a[j]-a[i] > u }) - 1
		if j > i+1 {
			nu = math.Max(nu, float64(a[j]-a[i+1])/float64(a[j]-a[i]))
		}
	}
	if nu < 0 {
		io.Println(-1)
	} else {
		io.Println(nu)
	}
}

type FastIO struct {
	//by megaspazz
	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 res * sgn
}
func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = int64(-1)
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = res*10 + int64(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
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() + 1
	}
	return arr
}
func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}
func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextLong()
	}
	return arr
}
func (io *FastIO) NextString() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}
func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}
func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}
func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}
func IsLineBreakChar(c byte) bool {
	switch c {
	case 0, '\n', '\r':
		return true
	default:
		return false
	}
}
func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

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

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 toInt(buf []byte) (o int) {
	for _, v := range buf {
		o = o*10 + int(v-'0')
	}
	return
}

type pair struct {
	first int
	second uint8
}

type ll []int64

func (a ll) Len() int {return len(a)}
func (a ll) Swap(i,j int) {a[i], a[j] = a[j], a[i]}
func (a ll) Less(i,j int) bool {
	return a[i] < a[j]
}

var (
	n, U int
	a [100000]int
)

func main() {
	in := bufio.NewReader(os.Stdin)
	//in, _ := os.Open("a.txt")
	fmt.Fscanf(in, "%d %d\n", &n, &U)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &a[i])
	}
	ans := -1.0
	for i := 0; i < n - 2; i++ {
		l := i + 2
		r := n - 1
		for r - l > 1 {
			mid := (l + r) / 2
			if a[mid] - a[i] <= U {
				l = mid
			} else {
				r = mid - 1
			}
		}
		if l > r {
			l , r = r, l
		}
		res := -1
		if a[l] - a[i] <= U {
			res = l
		}
		if a[r] - a[i] <= U {
			res = r
		}
		if res != -1 {
			ans = math.Max(ans, float64(a[res] - a[i + 1]) / float64(a[res] - a[i]))
		}
	}
	fmt.Printf("%.9f\n", ans)
}


One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.Help site X cope with the challenging task of rating distribution. Find the optimal distribution.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of users on the site. The next line contains integer sequence a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a sequence of integers b1, b2, ..., bn. Number bi means that user i gets bi of rating as a present. The printed sequence must meet the problem conditions.  If there are multiple optimal solutions, print any of them.

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

func main() {
	in.Split(bufio.ScanWords)
	n := readInt()
	a := make([]int, n)
	for i := range a {
		a[i] = readInt()
	}
	order := make([]int, n)
	for i := range order {
		order[i] = i
	}
	sort.Sort(inPlace{order, a})
	last := 0
	b := make([]int, n)
	for _, i := range order {
		last++
		if last < a[i] {
			last = a[i]
		}
		b[i] = last
	}
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for i, x := range b {
		fmt.Fprint(out, x)
		if i+1 == n {
			fmt.Fprint(out, "\n")
		} else {
			fmt.Fprint(out, " ")
		}
	}
}

type inPlace struct {
	order, a []int
}

func (s inPlace) Len() int           { return len(s.a) }
func (s inPlace) Swap(i, j int)      { s.order[i], s.order[j] = s.order[j], s.order[i] }
func (s inPlace) Less(i, j int) bool { return s.a[s.order[i]] < s.a[s.order[j]] }

package main

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

var scanner *bufio.Scanner

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

type User struct {
  Pos, Request, Rating int
}
type Users []*User
func (users Users) Len() int {
  return len(users)
}
func (users Users) Swap(i, j int) {
  users[i], users[j] = users[j], users[i]
}
func (users Users) Less(i, j int) bool {
  return users[i].Request < users[j].Request
}

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

  n := getI()
  users := make([]*User, n)
  for pos := range users {
    users[pos] = &User{ pos, getI(), 0 }
  }
  sort.Sort(Users(users))

  users[0].Rating = users[0].Request
  previous := users[0]
  for i := 1; i < n; i++ {
    user := users[i]
    if user.Request > previous.Rating {
      user.Rating = user.Request
    } else {
      user.Rating = previous.Rating + 1
    }
    previous = user
  }

  result := make([]int, n)
  for _, user := range users {
    result[user.Pos] = user.Rating
  }

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

package main

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

type User struct {
    r,p int
}

type UserSlice []User

func (u UserSlice) Len() int { return len(u) }
func (u UserSlice) Swap(i, j int) { u[i], u[j] = u[j], u[i] }
func (u UserSlice) Less(i, j int) bool { return u[i].r < u[j].r }

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    writer := bufio.NewWriter(os.Stdout)
    var n int
    fmt.Scan(&n)
    a := make(UserSlice,n)
    for i := 0; i < n; i++ {
        scanner.Scan()
        a[i].r, _ = strconv.Atoi(scanner.Text())
        a[i].p = i
    }
    sort.Sort(a)
    ans := make([]int,n)
    for i := 0; i < n; i++ {
        if i != 0 {
            if a[i].r <= a[i-1].r {
                a[i].r = a[i-1].r+1
            }
        }
        ans[a[i].p] = a[i].r
    }
    for i := 0; i < n; i++ {
        writer.WriteString(strconv.Itoa(ans[i]))
        if i == (n-1) { writer.WriteRune('\n') } else { writer.WriteRune(' ') }
    }
    writer.Flush()
}

package main

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

type Person struct {
	i, x int
}

type People []Person

func (p People) Len() int { return len(p) }
func (p People) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p People) Less(i, j int) bool { return p[i].x < p[j].x }

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]Person, n)
	for i := 0; i < n; i++ {
		a[i].i = i
		fmt.Fscanf(reader, "%d", &a[i].x)
	}
	sort.Sort(People(a))

	b := make([]int, n)
	x := 0
	for i := range a {
		if a[i].x > x {
			x = a[i].x
		}
		b[a[i].i] = x
		x++
	}
	pretty := fmt.Sprint(b)
	pretty = pretty[1:len(pretty)-1]
	fmt.Fprintln(writer, pretty)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, _ := reader.ReadString('\n')
	mins, _ := reader.ReadString('\n')
	out, err := process(strings.TrimSpace(n), strings.TrimSpace(mins))
	if err != nil {
		panic(err)
	}
	os.Stdout.Write([]byte(out))
}

type User struct {
	Min    int
	Rating int
}

type ByMin []*User

func (a ByMin) Len() int      { return len(a) }
func (a ByMin) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByMin) Less(i, j int) bool {
	if a[i].Min == a[j].Min {
		return i < j
	}
	return a[i].Min < a[j].Min
}

func process(in0 string, in1 string) (string, error) {
	n, err := strconv.Atoi(in0)
	if err != nil {
		return "", err
	}
	users := []*User{}
	for _, s := range strings.Split(in1, " ") {
		m, err := strconv.Atoi(s)
		if err != nil {
			return "", err
		}
		users = append(users, &User{Min: m})
	}

	orig := append([]*User{}, users...)
	ratings(n, users)
	s := []string{}
	for _, u := range orig {

		s = append(s, strconv.Itoa(u.Rating))
	}
	return strings.Join(s, " "), nil
}

func ratings(n int, users []*User) {
	sort.Stable(ByMin(users))
	last := -1
	for _, u := range users {

		if u.Min > last {
			last = u.Min
		} else {
			last++
		}
		u.Rating = last
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, _ := reader.ReadString('\n')
	mins, _ := reader.ReadString('\n')
	out, err := process(strings.TrimSpace(n), strings.TrimSpace(mins))
	if err != nil {
		panic(err)
	}
	os.Stdout.Write([]byte(out))
}

type User struct {
	Index  int
	Min    int
	Rating int
}

type ByIndex []User

func (a ByIndex) Len() int           { return len(a) }
func (a ByIndex) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByIndex) Less(i, j int) bool { return a[i].Index < a[j].Index }

type ByMin []User

func (a ByMin) Len() int      { return len(a) }
func (a ByMin) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByMin) Less(i, j int) bool {
	if a[i].Min == a[j].Min {
		return a[i].Index < a[j].Index
	}
	return a[i].Min < a[j].Min
}

func process(in0 string, in1 string) (string, error) {
	n, err := strconv.Atoi(in0)
	if err != nil {
		return "", err
	}
	users := []User{}
	for i, s := range strings.Split(in1, " ") {
		m, err := strconv.Atoi(s)
		if err != nil {
			return "", err
		}
		users = append(users, User{Index: i, Min: m})
	}

	ratings(n, users)
	s := []string{}
	for _, u := range users {

		s = append(s, strconv.Itoa(u.Rating))
	}
	return strings.Join(s, " "), nil
}

func ratings(n int, users []User) {
	sort.Sort(ByMin(users))
	last := -1
	for i, u := range users {

		if u.Min > last {
			last = u.Min
		} else {
			last++
		}
		users[i].Rating = last
	}

	sort.Sort(ByIndex(users))
}

package main

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

type User struct {
    r,p int
}

type UserSlice []User

func (u UserSlice) Len() int { return len(u) }
func (u UserSlice) Swap(i, j int) { u[i], u[j] = u[j], u[i] }
func (u UserSlice) Less(i, j int) bool { return u[i].r < u[j].r }

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    writer := bufio.NewWriter(os.Stdout)
    var n int
    fmt.Scan(&n)
    a := make(UserSlice,n)
    for i := 0; i < n; i++ {
        scanner.Scan()
        a[i].r, _ = strconv.Atoi(scanner.Text())
        a[i].p = i
    }
    sort.Sort(a)
    ans := make([]int,n)
    for i := 0; i < n; i++ {
        if i != 0 {
            if a[i].r == a[i-1].r {
                a[i].r++
            }
        }
        ans[a[i].p] = a[i].r
    }
    for i := 0; i < n; i++ {
        writer.WriteString(strconv.Itoa(ans[i]))
        if i == (n-1) { writer.WriteRune('\n') } else { writer.WriteRune(' ') }
    }
    writer.Flush()
}