You and your friend are participating in a TV show "Run For Your Prize".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?

The first line contains one integer n (1 ≤ n ≤ 105) — the number of prizes. The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 106 - 1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.

Print one integer — the minimum number of seconds it will take to collect all prizes.

NoteIn the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.

package main

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

func main() {
	// arr := make([]int, 0)
	// reader := bufio.NewReader(os.Stdin)
	input := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(input, &n)
	var arr [2000000]bool
	for i := 0; i < n; i++ {
		var val int
		fmt.Fscan(input, &val)
		arr[val] = true
	}

	p1 := 1
	p2 := 1000000
	ans_p1 := 0
	ans_p2 := 0
	for {
		if p1 > p2 {
			break
		}
		if p1 == p2 {
			if arr[p1] {
				ans_p1 = p1 - 1
			}
			break
		}
		if arr[p1] {
			ans_p1 = p1 - 1
		}
		if arr[p2] {
			ans_p2 = 1000000 - p2
		}
		p1++
		p2--
	}
	if ans_p1 > ans_p2 {
		fmt.Println(ans_p1)
	} else {
		fmt.Println(ans_p2)
	}
}

package main

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

func main() {
	// arr := make([]int, 0)
	// reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanf("%d", &n)
	var arr [2000000]bool
	for i := 0; i < n; i++ {
		var val int
		fmt.Scanf("%d", &val)
		arr[val] = true
	}

	p1 := 1
	p2 := 1000000
	ans_p1 := 0
	ans_p2 := 0
	for {
		if p1 > p2 {
			break
		}
		if p1 == p2 {
			if arr[p1] {
				ans_p1 = p1 - 1
			}
			break
		}
		if arr[p1] {
			ans_p1 = p1 - 1
		}
		if arr[p2] {
			ans_p2 = 1000000 - p2
		}
		p1++
		p2--
	}
	if ans_p1 > ans_p2 {
		fmt.Println(ans_p1)
	} else {
		fmt.Println(ans_p2)
	}
}


A $$$\mathbf{0}$$$-indexed array $$$a$$$ of size $$$n$$$ is called good if for all valid indices $$$i$$$ ($$$0 \le i \le n-1$$$), $$$a_i + i$$$ is a perfect square$$$^\dagger$$$.Given an integer $$$n$$$. Find a permutation$$$^\ddagger$$$ $$$p$$$ of $$$[0,1,2,\ldots,n-1]$$$ that is good or determine that no such permutation exists.$$$^\dagger$$$ An integer $$$x$$$ is said to be a perfect square if there exists an integer $$$y$$$ such that $$$x = y^2$$$.$$$^\ddagger$$$ An array $$$b$$$ is a permutation of an array $$$a$$$ if $$$b$$$ consists of the elements of $$$a$$$ in arbitrary order. For example, $$$[4,2,3,4]$$$ is a permutation of $$$[3,2,4,4]$$$ while $$$[1,2,2]$$$ is not a permutation of $$$[1,2,3]$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output $$$n$$$ distinct integers $$$p_0, p_1, \dots, p_{n-1}$$$ ($$$0 \le p_i \le n-1$$$) — the permutation $$$p$$$ — if the answer exists, and $$$-1$$$ otherwise.

package main

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

func Solve(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int

	Fscan(in, &t)

	// [0, n-1]  存在 a(0, n-2) 使得 a + (n-1) 是平方数, 则 p[a-1:] 一定可满足要求
	// 左侧也要递归满足要求
	var build func(n int, arr []int) bool
	build = func(n int, arr []int) bool {
		if n < 2 {
			return true
		}
		if n == 2 {
			arr[0], arr[1] = 1, 0
			return true
		}
		a := n-1
		var ok bool
		for ; a >= 0; a-- {
			b := a+n-1
			// b是否能开平方
			c := -1
			for j := 0; j*j <= b; j++ {
				if j*j == b {
					c = j
					break
				}
			}
			if c != -1 {
				ok = true
				break
			}
		}
		if ok {
			for i := a; i < n; i++ {
				arr[i] = n-1+a-i
			}
			return build(a, arr)
		}
		return false
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		if build(n, a) {
			Fprintln(out, strings.Trim(strings.Trim(Sprintf("%v", a), "["), "]"))
		} else {
			Fprintln(out, "-1")
		}
	}

	_, _ = in, out
}

func Solve1(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int
	Fscan(in, &t)

	var a []int

	var recurse func(r int)
	recurse = func(r int) {
		if r < 0 {
			return
		}
		// s := sort.Search(2*r, func(i int) bool { return (i+1)*(i+1) > 2*r })
		s := int(math.Sqrt(float64(2*r)))
		s = s*s
		l := s-r
		recurse(l-1)
		for ; l <= r; l, r = l+1, r-1 {
			a[l], a[r] = r, l
		}
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a = make([]int, n+1)
		recurse(n-1)
		for i := 0; i < n; i++ {
			Fprint(out, a[i], " ")
		}
		Fprint(out, "\n")
	}

}

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

package main

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

func Solve(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int

	Fscan(in, &t)

	// [0, n-1]  存在 a(0, n-2) 使得 a + (n-1) 是平方数, 则 p[a-1:] 一定可满足要求
	// 左侧也要递归满足要求
	var build func(n int, arr []int) bool
	build = func(n int, arr []int) bool {
		if n < 2 {
			return true
		}
		if n == 2 {
			arr[0], arr[1] = 1, 0
			return true
		}
		a := n-1
		var ok bool
		for ; a >= 0; a-- {
			b := a+n-1
			// b是否能开平方
			c := -1
			for j := 0; j*j <= b; j++ {
				if j*j == b {
					c = j
					break
				}
			}
			if c != -1 {
				ok = true
				break
			}
		}
		if ok {
			for i := a; i < n; i++ {
				arr[i] = n-1+a-i
			}
			return build(a, arr)
		}
		return false
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		if build(n, a) {
			Fprintln(out, strings.Trim(strings.Trim(Sprintf("%v", a), "["), "]"))
		} else {
			Fprintln(out, "-1")
		}
	}

	_, _ = in, out
}

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

package main

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

const MAXN int = 2e5

var dp, square, isSquare, ans [MAXN + 7]int
var top int = 0

func IntAbs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}

func myinit() {
	for i := 0; i <= MAXN; i++ {
		dp[i] = -1
		isSquare[i] = 0
	}
	for i := 0; i*i <= MAXN; i++ {
		square[top] = i * i
		isSquare[square[top]] = 1
		top++
	}
	for i, h := 1, 0; i <= MAXN; i++ {
		for square[h] < 2*i && h < top {
			h++
		}
		if i <= 3 || isSquare[i-1] == 1 {
			dp[i] = 0
		}
		if dp[i] == -1 {
			// fmt.Println(i)
			continue
		}
		for j := h; j < top && square[j] >= 2*i; j++ {
			dp[square[j]-i+1] = i
		}
	}
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t, n int
	var ch byte
	myinit()
	fmt.Fscan(in, &t)
	for ; t != 0; t-- {
		fmt.Fscan(in, &n)
		if dp[n] == -1 {
			fmt.Fprintln(out, -1)
			continue
		}
		for cur, j := n, n; cur != 0; cur = dp[cur] {
			temp := dp[cur]
			// fmt.Fprintln(out, cur, temp)
			if temp == 0 {
				if cur == 3 {
					// fmt.Fprintln(out, " here2")
					ans[1], ans[2], ans[3] = 1, 0, 2
				} else {
					for k := 0; k < cur; k++ {
						ans[j] = k
						j--
					}
				}
			} else {
				l := cur - temp
				for k := 0; k < l; k++ {
					ans[j] = temp + k
					j--
				}
			}
		}
		for i := 1; i <= n; i++ {
			if i == n {
				ch = '\n'
			} else {
				ch = ' '
			}
			fmt.Fprintf(out, "%d%c", ans[i], ch)
		}
	}

}

package main

import (
	"fmt"
	"sort"
)

func main() {
	mem := make([]int, 450)
	for i := 0; i <= 449; i++ {
		mem[i] = i * i
	}

	var t int
	var n int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n)
		output := make([]int, n)
		max_el := n - 1
		curr_n := n

		for max_el > 0 {
			indx := sort.SearchInts(mem, max_el)
			var put_idx int
			if mem[indx] == max_el {
				put_idx = 0
			} else {
				put_idx = mem[indx] - max_el
			}

			for k := put_idx; k < curr_n; k++ {
				output[k] = curr_n - (k - put_idx + 1)
			}
			curr_n = put_idx
			max_el = curr_n - 1
		}
		for _, e := range output {
			fmt.Printf("%d ", e)
		}
		fmt.Printf("\n")
	}
}

package main

import (
	"fmt"
	"strconv"
	"strings"
)

var dp = make(map[int]string)

func main() {
	var numline int
	dp[0] = "0"
	fmt.Scanf("%d\n", &numline)
	for i := 0; i < numline; i++ {
		var checkNum int
		fmt.Scanf("%d\n", &checkNum)
		result := genPermu(checkNum - 1)
		fmt.Println(result)
	}
}

func getClosest(num int) int {
	for i := 0; i <= num; i++ {
		if i*i >= num {
			return i * i
		}
	}

	return 0
}

func genPermu(num int) string {
	if value, ok := dp[num]; ok {
		return value
	}
	remainer := getClosest(num) - num
	result := make([]string, 0)
	iter := num
	count := 0
	for ; iter >= remainer; iter-- {
		count++
		result = append(result, strconv.Itoa(iter))
	}
	// fmt.Printf("Remainer: %d, Count:%d\n", remainer, count)

	if remainer == 0 {
		dp[num] = strings.Join(result, " ")
	} else {
		dp[num] = genPermu(num-count) + " " + strings.Join(result, " ")

	}

	return dp[num]
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--

		n := readNum(reader)

		res := solve(n)

		for i := 0; i < n; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}

	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(n int) []int {
	res := make([]int, n)

	var rec func(r int)

	rec = func(r int) {
		if r < 0 {
			return
		}
		s := int(math.Sqrt(float64(r * 2)))
		s *= s
		l := s - r
		rec(l - 1)
		for l <= r {
			res[l] = r
			res[r] = l
			l++
			r--
		}
	}
	rec(n - 1)

	return res
}

package main

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

var p_arr [100_001]int

func Solve(testCaseIdx int, reader io.Reader) {
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n int
	fmt.Fscan(reader, &n)
	p := p_arr[0:n]
	for k := 0; k < n; k++ {
		p[k] = k
	}

	for x := n - 1; x > 0; {
		a := 0
		for ; a * a < x; a++ {
		}
		sqr := a * a
		start := sqr - x
		for k := 0; k <= x - start; k++ {
			p[start + k] = x - k
		}
		x = start - 1
	}

	for k := 0; k < n; k++ {
		fmt.Fprintf(writer, "%d ", p[k])
	}
	fmt.Fprintln(writer, "")
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var testCaseCount int
	fmt.Fscan(reader, &testCaseCount)
	for k := 0; k < testCaseCount; k++ {
		Solve(k, reader)
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"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 int
		fmt.Fscan(r, &n)
		w1 := do(n)
		for _, v := range w1 {
			fmt.Fprint(w, v, " ")
		}
		fmt.Fprintln(w)
	}
}

func do(n int) []int {
	nextSquare := func(x int) int {
		y := int(math.Sqrt(float64(x)))
		if y*y == x {
			return x
		}
		y++
		return y * y
	}
	a := make([]int, n)
	n--
	for n >= 0 {
		s := nextSquare(n) - n
		t := s
		for n >= s {
			a[n] = t
			n--
			t++
		}
	}
	return a
}

package main

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

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 < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		g := 1
		for g*g <= n {
			g++
		}
		aa := make([]int, n)
		for i := n - 1; i >= 1; i-- {
			for g*g-i >= n || aa[g*g-i] != 0 {
				g--
			}
			aa[g*g-i] = i
		}
		for _, v := range aa {
			fmt.Fprintf(out, "%d ", v)
		}
		fmt.Fprintln(out)
	}
}

package main

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

func init() {}

func isSqr(i int) bool {
	x := int(math.Sqrt(F(i)))
	return x*x == i
}

func solve() {
	n := get()
	x := int64(math.Ceil(math.Sqrt(F(n - 1))))
	a := ints(n, 0)
	y := n - 1
	for x >= 0 && y >= 0 {
		next := y
		for L(y+next) >= x*x {
			next--
		}
		last := y
		for i := next + 1; i <= last; i++ {
			a[i] = y
			y--
		}
		x--
	}
	if y != -1 {
		putsln("-1")
		return
	}
	puta(a)
}

const (
	once       = false
	useBuf     = false
	maxBufSize = 10_000_000
	YES        = "YES"
	NO         = "NO"
)

var (
	splitFunc = bufio.ScanWords
)

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	in.Split(splitFunc)
	if useBuf {
		in.Buffer(make([]byte, maxBufSize), maxBufSize)
	}

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

	if once {
		solve()
		return
	}

	for t := get(); t > 0; t-- {
		solve()
	}
}

var (
	in  *bufio.Scanner
	out *bufio.Writer
)

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

func geta(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = get()
	}
	return a
}

func geta1(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = get() - 1
	}
	return a
}

func get64() int64 {
	x, _ := strconv.ParseInt(gets(), 10, 64)
	return x
}

func get64a(n int) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = get64()
	}
	return a
}

func get64a1(n int) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = get64() - 1
	}
	return a
}

func getf() float64 {
	x, _ := strconv.ParseFloat(gets(), 64)
	return x
}

func getfa(n int) []float64 {
	a := make([]float64, n)
	for i := range a {
		a[i] = getf()
	}
	return a
}

func gets() string {
	scan()
	return in.Text()
}

func scanN(n int) {
	for n > 0 {
		scan()
		n--
	}
}

func scan() {
	in.Scan()
}

func putc(c rune) {
	out.WriteRune(c)
}

func line() {
	putc('\n')
}

func space() {
	putc(' ')
}

func put(x int) {
	out.WriteString(strconv.Itoa(x))
}

func putln(i int) {
	put(i)
	line()
}

func puta(a []int) {
	for _, v := range a {
		put(v)
		space()
	}
	line()
}

func put64(x int64) {
	out.WriteString(strconv.FormatInt(x, 10))
}

func put64ln(x int64) {
	put64(x)
	line()
}

func put64a(a []int64) {
	for _, v := range a {
		put64(v)
		space()
	}
	line()
}

func puts(s string) {
	out.WriteString(s)
}

func putsln(s string) {
	puts(s)
	line()
}

func yn(y bool) {
	if y {
		yes()
		return
	}
	no()
}

func yes() {
	puts(YES)
	line()
}

func no() {
	puts(NO)
	line()
}

func putf(x float64) {
	out.WriteString(strconv.FormatFloat(x, 'f', -1, 64))
}

func putfln(x float64) {
	putf(x)
	line()
}

func putfa(a []float64) {
	for _, v := range a {
		putf(v)
		space()
	}
	line()
}

type IntTp interface {
	int | int64
}

type Tp interface {
	IntTp | float64
}

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

func fabs(x float64) float64 {
	return math.Abs(x)
}

func max1[T Tp](x T, y T) T {
	if x > y {
		return x
	}
	return y
}

func max[T Tp](xs ...T) T {
	r := xs[0]
	for _, x := range xs[1:] {
		r = max1(r, x)
	}
	return r
}

func maxa[T Tp](a []T) (i int, val T) {
	i, val = 0, a[0]
	for j := 1; j < len(a); j++ {
		if a[j] <= val {
			continue
		}
		i = j
		val = a[j]
	}
	return
}

func min1[T Tp](x T, y T) T {
	if x < y {
		return x
	}
	return y
}

func min[T Tp](xs ...T) T {
	r := xs[0]
	for _, x := range xs[1:] {
		r = min1(r, x)
	}
	return r
}

func mina[T Tp](a []T) (i int, val T) {
	i, val = 0, a[0]
	for j := 1; j < len(a); j++ {
		if a[j] >= val {
			continue
		}
		i = j
		val = a[j]
	}
	return
}

func L(i int) int64 {
	return int64(i)
}

func F(i int) float64 {
	return float64(i)
}

func ints(n int, val int) (a []int) {
	a = make([]int, n)
	if val == 0 {
		return
	}
	for i := range a {
		a[i] = val
	}
	return
}

func int64s(n int, val int64) (a []int64) {
	a = make([]int64, n)
	if val == 0 {
		return
	}
	for i := range a {
		a[i] = val
	}
	return
}

func floats(n int, val float64) (a []float64) {
	a = make([]float64, n)
	if val == 0 {
		return
	}
	for i := range a {
		a[i] = val
	}
	return
}

const heapBase = 4

func children(i int) (int, int) {
	start := heapBase * i
	return start + 1, start + (1 + heapBase)
}

func parent(i int) int {
	return (i - 1) / heapBase
}

package main

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

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

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

func maxSquare(a int) int {
	tmp := int(math.Sqrt(float64(a)))
	if tmp*tmp == a {
		return tmp * tmp
	} else {
		return (tmp + 1) * (tmp + 1)
	}
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var niter int
	fmt.Fscan(in, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n int
		fmt.Fscan(in, &n)
		res := make([]int, n)
		rem := n - 1
		for i := n - 1; i >= 0; {
			from := maxSquare(i)
			looped := 0
			for j := i; from-j <= rem; j-- {
				res[j] = from - j
				looped++
			}
			i = rem - looped
			rem = rem - looped
			if i == 0 {
				break
			}
		}
		for i := 0; i < n; i++ {
			fmt.Fprintf(out, "%d ", res[i])
		}
		fmt.Fprintln(out)
	}
}

package main

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

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

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

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

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

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

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

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

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

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

var in = bufio.NewReader(os.Stdin)

func main() {
	t := readInt()

	nextSqr := make([]int, 100001)
	c := 317
	for i := 100000; i >= 0; i-- {
		if i == (c-1)*(c-1) {
			c--
		}
		nextSqr[i] = c * c
	}

	for i := 0; i < t; i++ {
		n := readInt()
		a := make([]string, n)
		for x := n - 1; x >= 0; {
			diff := nextSqr[x] - x
			for s := diff; s <= x; s++ {
				a[s] = strconv.Itoa(x - (s - diff))
			}
			x = diff - 1
		}
		fmt.Println(strings.Join(a, " "))
	}
}

package main

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

const cf = true

func solve() {
	var n int
	fmt.Fscan(in, &n)
	ans := make([]int, n)
	curNum := n - 1
	cur := n - 1
	for cur >= 0 {
		maxSq := 0
		for curNum > maxSq*maxSq {
			maxSq++
		}
		nextNum := maxSq*maxSq - cur - 1
		for i := nextNum + 1; i <= curNum; i++ {
			ans[cur] = maxSq*maxSq - cur
			cur--
		}
		curNum = nextNum
	}
	for i := range ans {
		fmt.Fprint(out, ans[i], " ")
	}
	fmt.Fprintln(out)
}

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

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

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

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

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

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

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

func (s *set[T]) sortedItems() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	sort.Slice(items, func(i, j int) bool {
		return items[i] < items[j]
	})
	return items
}

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

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

var exists = struct{}{}

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

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

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

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

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

type Ordered interface {
	Integer | Float | ~string
}

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

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

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

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

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

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

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	cases := readInt(input)
	for asdf := 0; asdf < cases; asdf++ {
		n := readInt(input)
		solution := solve(n - 1)
		for i := 0; i < len(solution); i++ {
			fmt.Print(solution[i], " ")
		}
		fmt.Println()
	}
}

func isSquare(n int) bool {
	int_root := int(math.Sqrt(float64(n)))
	return int_root*int_root == n
}

func solve(n int) []int {
	if n == 0 {
		return []int{0}
	} else if n == 1 {
		return []int{1, 0}
	} else {
		for i := n; i >= 0; i-- {
			if isSquare(n + i) {
				solution := solve(i - 1)
				for j := n; j >= i; j-- {
					solution = append(solution, j)
				}
				return solution
			}
		}
	}
	return []int{}
}

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 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 readInt64(in *bufio.Reader) int64 {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return int64(n)
}

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"
	"math"
	"os"
)

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

var a = make([]int, 1e5)

func solve(n int) bool {
	if n == 0 {
		return true
	}
	s := int(math.Sqrt(float64(n - 1)))
	if s*s < n-1 {
		s++
	}
	p := s*s - (n - 1)
	for i := 0; p+i < n; i++ {
		a[p+i] = n - 1 - i
	}
	return solve(p)
}

func main() {
	defer out.Flush()

	var tc, n int
	for fmt.Fscan(in, &tc); tc > 0; tc-- {
		fmt.Fscan(in, &n)
		if !solve(n) {
			fmt.Fprintln(out, -1)
		} else {
			for i := 0; i < n; i++ {
				fmt.Fprintf(out, "%d ", a[i])
			}
			fmt.Fprintln(out)
		}
	}
}

package main

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

func Solve(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int

	Fscan(in, &t)

	// [0, n-1]  存在 a(0, n-2) 使得 a + (n-1) 是平方数, 则 p[a-1:] 一定可满足要求
	// 左侧也要递归满足要求
	var build func(n int, arr []int) bool
	build = func(n int, arr []int) bool {
		if n < 2 {
			return true
		}
		if n == 2 {
			arr[0], arr[1] = 1, 0
			return true
		}
		a := n-1
		var ok bool
		for ; a >= 0; a-- {
			b := a+n-1
			// b是否能开平方
			c := -1
			for j := 0; j*j <= b; j++ {
				if j*j == b {
					c = j
					break
				}
			}
			if c != -1 {
				ok = true
				break
			}
		}
		if ok {
			for i := a; i < n; i++ {
				arr[i] = n-1+a-i
			}
			return build(a, arr)
		}
		return false
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		if build(n, a) {
			Fprintln(out, strings.Trim(strings.Trim(Sprintf("%v", a), "["), "]"))
		} else {
			Fprintln(out, "-1")
		}
	}

	_, _ = in, out
}

func Solve1(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int
	Fscan(in, &t)

	var a []int

	var recurse func(r int)
	recurse = func(r int) {
		if r < 0 {
			return
		}
		// why not?
		s := sort.Search(2*r, func(i int) bool { return i*i+2*i+1 > 2*r })
		// s := int(math.Sqrt(float64(2*r)))
		s = s*s
		l := s-r
		recurse(l-1)
		for ; l <= r; l, r = l+1, r-1 {
			a[l], a[r] = r, l
		}
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a = make([]int, n+1)
		recurse(n-1)
		for i := 0; i < n; i++ {
			Fprint(out, a[i], " ")
		}
		Fprint(out, "\n")
	}

}

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

package main

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

func Solve(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int

	Fscan(in, &t)

	// [0, n-1]  存在 a(0, n-2) 使得 a + (n-1) 是平方数, 则 p[a-1:] 一定可满足要求
	// 左侧也要递归满足要求
	var build func(n int, arr []int) bool
	build = func(n int, arr []int) bool {
		if n < 2 {
			return true
		}
		if n == 2 {
			arr[0], arr[1] = 1, 0
			return true
		}
		a := n-1
		var ok bool
		for ; a >= 0; a-- {
			b := a+n-1
			// b是否能开平方
			c := -1
			for j := 0; j*j <= b; j++ {
				if j*j == b {
					c = j
					break
				}
			}
			if c != -1 {
				ok = true
				break
			}
		}
		if ok {
			for i := a; i < n; i++ {
				arr[i] = n-1+a-i
			}
			return build(a, arr)
		}
		return false
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		if build(n, a) {
			Fprintln(out, strings.Trim(strings.Trim(Sprintf("%v", a), "["), "]"))
		} else {
			Fprintln(out, "-1")
		}
	}

	_, _ = in, out
}

func Solve1(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int
	Fscan(in, &t)

	var a []int

	var recurse func(r int)
	recurse = func(r int) {
		if r < 0 {
			return
		}
		s := sort.Search(2*r, func(i int) bool { return (i+1)*(i+1) > 2*r })
		// s := int(math.Sqrt(float64(2*r)))
		s = s*s
		l := s-r
		recurse(l-1)
		for ; l <= r; l, r = l+1, r-1 {
			a[l], a[r] = r, l
		}
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a = make([]int, n+1)
		recurse(n-1)
		for i := 0; i < n; i++ {
			Fprint(out, a[i], " ")
		}
		Fprint(out, "\n")
	}

}

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

package main

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

func Solve(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int

	Fscan(in, &t)

	// [0, n-1]  存在 a(0, n-2) 使得 a + (n-1) 是平方数, 则 p[a-1:] 一定可满足要求
	// 左侧也要递归满足要求
	var build func(n int, arr []int) bool
	build = func(n int, arr []int) bool {
		if n < 2 {
			return true
		}
		if n == 2 {
			arr[0], arr[1] = 1, 0
			return true
		}
		a := n-1
		var ok bool
		for ; a >= 0; a-- {
			b := a+n-1
			// b是否能开平方
			c := -1
			for j := 0; j*j <= b; j++ {
				if j*j == b {
					c = j
					break
				}
			}
			if c != -1 {
				ok = true
				break
			}
		}
		if ok {
			for i := a; i < n; i++ {
				arr[i] = n-1+a-i
			}
			return build(a, arr)
		}
		return false
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		if build(n, a) {
			Fprintln(out, strings.Trim(strings.Trim(Sprintf("%v", a), "["), "]"))
		} else {
			Fprintln(out, "-1")
		}
	}

	_, _ = in, out
}

const N int = 1e5+5

func Solve1(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int
	a := [N]int{}

	Fscan(in, &t)

	var recurse func(r int)
	recurse = func(r int) {
		if r < 0 {
			return
		}
		s := sort.Search(2*r, func(i int) bool { return (i+1)*(i+1) > 2*r })
		// s := int(math.Sqrt(float64(2*r)))
		s = s*s
		l := s-r
		recurse(l-1)
		for ; l <= r; l, r = l+1, r-1 {
			a[l], a[r] = r, l
		}
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		recurse(n-1)
		for i := 0; i < n; i++ {
			Fprint(out, a[i], " ")
		}
		Fprint(out, "\n")
	}

}

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

package main

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

func Solve(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int

	Fscan(in, &t)

	// [0, n-1]  存在 a(0, n-2) 使得 a + (n-1) 是平方数, 则 p[a-1:] 一定可满足要求
	// 左侧也要递归满足要求
	var build func(n int, arr []int) bool
	build = func(n int, arr []int) bool {
		if n < 2 {
			return true
		}
		if n == 2 {
			arr[0], arr[1] = 1, 0
			return true
		}
		a := n-1
		var ok bool
		for ; a >= 0; a-- {
			b := a+n-1
			// b是否能开平方
			c := -1
			for j := 0; j*j <= b; j++ {
				if j*j == b {
					c = j
					break
				}
			}
			if c != -1 {
				ok = true
				break
			}
		}
		if ok {
			for i := a; i < n; i++ {
				arr[i] = n-1+a-i
			}
			return build(a, arr)
		}
		return false
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		if build(n, a) {
			Fprintln(out, strings.Trim(strings.Trim(Sprintf("%v", a), "["), "]"))
		} else {
			Fprintln(out, "-1")
		}
	}

	_, _ = in, out
}

const N int = 1e5+5

func Solve1(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int
	a := [N]int{}

	Fscan(in, &t)

	var recurse func(r int)
	recurse = func(r int) {
		if r < 0 {
			return
		}
		s := sort.Search(2*r, func(i int) bool { return (i+1)*(i+1) >= 2*r+1 })
		s = s*s
		l := s-r
		recurse(l-1)
		for ; l <= r; l, r = l+1, r-1 {
			a[l], a[r] = r, l
		}
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		recurse(n-1)
		for i := 0; i < n; i++ {
			Fprint(out, a[i], " ")
		}
		Fprint(out, "\n")
	}

}

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

package main

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

func Solve(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int

	Fscan(in, &t)

	// [0, n-1]  存在 a(0, n-2) 使得 a + (n-1) 是平方数, 则 p[a-1:] 一定可满足要求
	// 左侧也要递归满足要求
	var build func(n int, arr []int) bool
	build = func(n int, arr []int) bool {
		if n < 2 {
			return true
		}
		if n == 2 {
			arr[0], arr[1] = 1, 0
			return true
		}
		a := n-1
		var ok bool
		for ; a >= 0; a-- {
			b := a+n-1
			// b是否能开平方
			c := -1
			for j := 0; j*j <= b; j++ {
				if j*j == b {
					c = j
					break
				}
			}
			if c != -1 {
				ok = true
				break
			}
		}
		if ok {
			for i := a; i < n; i++ {
				arr[i] = n-1+a-i
			}
			return build(a, arr)
		}
		return false
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		if build(n, a) {
			Fprintln(out, strings.Trim(strings.Trim(Sprintf("%v", a), "["), "]"))
		} else {
			Fprintln(out, "-1")
		}
	}

	_, _ = in, out
}

const N int = 1e5+5

func Solve1(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int
	a := [N]int{}

	Fscan(in, &t)

	var recurse func(r int)
	recurse = func(r int) {
		if r < 0 {
			return
		}
		s := sort.Search(2*r, func(i int) bool { return (i+1)*(i+1) > 2*r })
		s = s*s
		l := s-r
		recurse(l-1)
		for ; l <= r; l, r = l+1, r-1 {
			a[l], a[r] = r, l
		}
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		recurse(n-1)
		for i := 0; i < n; i++ {
			Fprint(out, a[i], " ")
		}
		Fprint(out, "\n")
	}

}

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

package main

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

func Solve(_in io.Reader, _out io.Writer) {
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()

	var t, n int

	Fscan(in, &t)

	// [0, n-1]  存在 a(0, n-2) 使得 a + (n-1) 是平方数, 则 p[a-1:] 一定可满足要求
	// 左侧也要递归满足要求
	var build func(n int, arr []int) bool
	build = func(n int, arr []int) bool {
		if n == 1 {
			return true
		}
		if n == 2 {
			arr[0], arr[1] = 1, 0
			return true
		}
		a := 0
		var ok bool
		for ; a < n; a++ {
			b := a+n-1
			// b是否能开平方
			c := -1
			for j := 0; j*j <= b; j++ {
				if j*j == b {
					c = j
					break
				}
			}
			if c != -1 {
				ok = true
				break
			}
		}
		if ok {
			for i := a; i < n; i++ {
				arr[i] = n-1+a-i
			}
			return build(a, arr)
		}
		return false
	}

	for ; t > 0; t-- {
		Fscan(in, &n)
		a := make([]int, n)
		if build(n, a) {
			Fprintln(out, strings.Trim(strings.Trim(Sprintf("%v", a), "["), "]"))
		} else {
			Fprintln(out, "-1")
		}
	}

	_, _ = in, out
}

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

package main

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

const MAXN int = 2e5

var dp, square, isSquare, ans [MAXN + 7]int
var top int = 0

func IntAbs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}

func myinit() {
	for i := 0; i <= MAXN; i++ {
		dp[i] = -1
		isSquare[i] = 0
	}
	for i := 0; i*i <= MAXN; i++ {
		square[top] = i * i
		isSquare[square[top]] = 1
		top++
	}
	for i, h := 1, 0; i <= MAXN; i++ {
		for square[h] < 2*i && h < top {
			h++
		}
		if i <= 3 || isSquare[i-1] == 1 {
			dp[i] = 0
		}
		if dp[i] == -1 {
			fmt.Println(i)
			continue
		}
		for j := h; j < top && square[j] >= 2*i; j++ {
			dp[square[j]-i+1] = i
		}
	}
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t, n int
	var ch byte
	myinit()
	fmt.Fscan(in, &t)
	for ; t != 0; t-- {
		fmt.Fscan(in, &n)
		if dp[n] == -1 {
			fmt.Fprintln(out, -1)
			continue
		}
		for cur, j := n, n; cur != 0; cur = dp[cur] {
			temp := dp[cur]
			// fmt.Fprintln(out, cur, temp)
			if temp == 0 {
				if cur == 3 {
					// fmt.Fprintln(out, " here2")
					ans[1], ans[2], ans[3] = 1, 0, 2
				} else {
					for k := 0; k < cur; k++ {
						ans[j] = k
						j--
					}
				}
			} else {
				l := cur - temp
				for k := 0; k < l; k++ {
					ans[j] = temp + k
					j--
				}
			}
		}
		for i := 1; i <= n; i++ {
			if i == n {
				ch = '\n'
			} else {
				ch = ' '
			}
			fmt.Fprintf(out, "%d%c", ans[i], ch)
		}
	}

}

package main

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

const MAXN int = 1e5

var dp, square, ans [MAXN + 7]int
var top int = 0

func IntAbs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}

func isSquare(val int) bool {
	if val <= 1 {
		return true
	}
	temp := int(math.Floor(math.Sqrt(float64(val))))
	return temp*temp == val
}

func myinit() {
	for i := 0; i <= MAXN; i++ {
		dp[i] = -1
	}
	for i := 0; i*i <= MAXN; i++ {
		square[top] = i * i
		top++
	}
	for i, h := 1, 0; i <= MAXN; i++ {
		for square[h] <= 2*i && h < top {
			h++
		}
		if i <= 3 || isSquare(i-1) {
			dp[i] = 0
		}
		if dp[i] == -1 {
			continue
		}
		for j := h; j < top && square[j] > 2*i; j++ {
			dp[square[j]-i+1] = i
		}
	}
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t, n int
	var ch byte
	myinit()
	fmt.Fscan(in, &t)
	for ; t != 0; t-- {
		fmt.Fscan(in, &n)
		if dp[n] == -1 {
			fmt.Fprintln(out, -1)
			continue
		}
		for cur, j := n, n; cur != 0; cur = dp[cur] {
			temp := dp[cur]
			// fmt.Fprintln(out, cur, temp)
			if temp == 0 {
				if cur == 3 {
					// fmt.Fprintln(out, " here2")
					ans[1], ans[2], ans[3] = 1, 0, 2
				} else {
					for k := 0; k < cur; k++ {
						ans[j] = k
						j--
					}
				}
			} else {
				l := cur - temp
				for k := 0; k < l; k++ {
					ans[j] = temp + k
					j--
				}
			}
		}
		for i := 1; i <= n; i++ {
			if i == n {
				ch = '\n'
			} else {
				ch = ' '
			}
			fmt.Fprintf(out, "%d%c", ans[i], ch)
		}
	}

}

package main

import (
	"fmt"
	"sort"
)

func main() {
	mem := make([]int, 450)
	for i := 0; i <= 449; i++ {
		mem[i] = i * i
	}

	var t int
	var n int
	fmt.Scanf("%d", &t)
	for i := 0; i < t; i++ {
		fmt.Scanf("%d", &n)
		output := make([]int, n)
		max_el := n - 1
		curr_n := n

		for max_el > 0 {
			indx := sort.SearchInts(mem, max_el)
			var put_idx int
			if mem[indx] == max_el {
				put_idx = 0
			} else {
				put_idx = mem[indx] - max_el
			}

			for k := put_idx; k < curr_n; k++ {
				output[k] = curr_n - (k - put_idx + 1)
			}
			curr_n = put_idx
			max_el = curr_n - 1
		}
		for _, e := range output {
			fmt.Printf("%d ", e)
		}
		fmt.Printf("\n")
	}
}

package main

import (
	"fmt"
	"strconv"
	"strings"
)

var dp = make(map[int]string)

func main() {
	var numline int
	dp[0] = "0"
	fmt.Scanf("%d\n", &numline)
	for i := 0; i < numline; i++ {
		var checkNum int
		fmt.Scanf("%d\n", &checkNum)
		result := genPermu(checkNum)
		fmt.Println(result)
	}
}

func getClosest(num int) int {
	for i := 0; i <= num; i++ {
		if i*i >= num {
			return i * i
		}
	}

	return 0
}

func genPermu(num int) string {
	if value, ok := dp[num]; ok {
		return value
	}
	remainer := getClosest(num) - num
	result := make([]string, 0)
	iter := num
	count := 0
	for ; iter >= remainer; iter-- {
		count++
		result = append(result, strconv.Itoa(iter))
	}
	// fmt.Printf("Remainer: %d, Count:%d\n", remainer, count)

	if remainer == 0 {
		dp[num] = strings.Join(result, " ")
	} else {
		dp[num] = genPermu(num-count) + " " + strings.Join(result, " ")

	}

	return dp[num]
}


This is the hard version of the problem. The only difference between the two versions is the constraint on $$$n$$$. You can make hacks only if all versions of the problem are solved.A forest is an undirected graph without cycles (not necessarily connected).Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $$$1$$$ to $$$n$$$, and they would like to add edges to their forests such that:   After adding edges, both of their graphs are still forests.  They add the same edges. That is, if an edge $$$(u, v)$$$ is added to Mocha's forest, then an edge $$$(u, v)$$$ is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.

The first line contains three integers $$$n$$$, $$$m_1$$$ and $$$m_2$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le m_1, m_2 < n$$$) — the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next $$$m_1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edges in Mocha's forest. Each of the next $$$m_2$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edges in Diana's forest.

The first line contains only one integer $$$h$$$, the maximum number of edges Mocha and Diana can add. Each of the next $$$h$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edge you add each time. If there are multiple correct answers, you can print any one of them.

NoteIn the first example, we cannot add any edge.In the second example, the initial forests are as follows.We can add an edge $$$(2, 4)$$$.

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

type edge struct {
	a, b int
}

func rw(r io.Reader, w io.Writer) {
	var n, m1, m2 int
	fmt.Fscan(r, &n, &m1, &m2)
	e1 := make([]edge, m1)
	for i := 0; i < m1; i++ {
		fmt.Fscan(r, &e1[i].a, &e1[i].b)
	}
	e2 := make([]edge, m2)
	for i := 0; i < m2; i++ {
		fmt.Fscan(r, &e2[i].a, &e2[i].b)
	}
	w1 := do(n, e1[:m1], e2[:m2])
	fmt.Fprintln(w, len(w1))
	for _, v := range w1 {
		fmt.Fprintln(w, v.a, v.b)
	}
}

func getF(f []int, x int) int {
	if f[x] != x {
		f[x] = getF(f, f[x])
	}
	return f[x]
}

func newF(n int) []int {
	f := make([]int, n+1)
	for i := 1; i <= n; i++ {
		f[i] = i
	}
	return f
}

func newInitF(n int, e []edge) []int {
	f := newF(n)
	for _, v := range e {
		union(f, v.a, v.b)
	}
	return f
}

func union(f []int, i, j int) {
	fi, fj := getF(f, i), getF(f, j)
	f[fi] = fj
}

func same(f []int, i, j int) bool {
	return getF(f, i) == getF(f, j)
}

func getP(f []int, n, j int) []int {
	var p []int
	for i := 1; i <= n; i++ {
		if !same(f, i, j) {
			p = append(p, i)
		}
	}
	return p
}

func do(n int, e1, e2 []edge) []edge {
	f1 := newInitF(n, e1)
	f2 := newInitF(n, e2)
	var r []edge
	for i := 2; i <= n; i++ {
		if !same(f1, 1, i) && !same(f2, 1, i) {
			r = append(r, edge{1, i})
			union(f1, 1, i)
			union(f2, 1, i)
		}
	}
	p1 := getP(f1, n, 1)
	p2 := getP(f2, n, 1)

	for len(p1) > 0 && len(p2) > 0 {
		if same(f1, p1[0], 1) && same(f2, p1[0], 1) {
			p1 = p1[1:]
			continue
		}
		if same(f1, p2[0], 1) && same(f2, p2[0], 1) {
			p2 = p2[1:]
			continue
		}
		r = append(r, edge{p1[0], p2[0]})
		union(f1, p1[0], p2[0])
		union(f2, p1[0], p2[0])
	}
	return r
}

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

type edge struct {
	a, b int
}

func rw(r io.Reader, w io.Writer) {
	var n, m1, m2 int
	fmt.Fscan(r, &n, &m1, &m2)
	e1 := make([]edge, m1)
	for i := 0; i < m1; i++ {
		fmt.Fscan(r, &e1[i].a, &e1[i].b)
	}
	e2 := make([]edge, m2)
	for i := 0; i < m2; i++ {
		fmt.Fscan(r, &e2[i].a, &e2[i].b)
	}
	w1 := do(n, e1[:m1], e2[:m2])
	fmt.Fprintln(w, len(w1))
	for _, v := range w1 {
		fmt.Fprintln(w, v.a, v.b)
	}
}

func getF(f []int, x int) int {
	if f[x] != x {
		f[x] = getF(f, f[x])
	}
	return f[x]
}

func newF(n int) []int {
	f := make([]int, n+1)
	for i := 1; i <= n; i++ {
		f[i] = i
	}
	return f
}

func newInitF(n int, e []edge) []int {
	f := newF(n)
	for _, v := range e {
		union(f, v.a, v.b)
	}
	return f
}

func union(f []int, i, j int) {
	fi, fj := getF(f, i), getF(f, j)
	f[fi] = fj
}

func same(f []int, i, j int) bool {
	return getF(f, i) == getF(f, j)
}

func getP(f []int) []int {
	var p []int
	f1 := getF(f, 1)
	for i := 2; i <= len(f)-1; i++ {
		if getF(f, i) == f1 {
			p = append(p, i)
		}
	}
	return p
}

func do(n int, e1, e2 []edge) []edge {
	f1 := newInitF(n, e1)
	f2 := newInitF(n, e2)
	var r []edge
	for i := 2; i <= n; i++ {
		if !same(f1, 1, i) && !same(f2, 1, i) {
			r = append(r, edge{1, i})
			union(f1, 1, i)
			union(f2, 1, i)
		}
	}
	p1 := getP(f1)
	p2 := getP(f2)

	for len(p1) > 0 && len(p2) > 0 {
		if same(f1, p1[0], 1) && same(f2, p1[0], 1) {
			p1 = p1[1:]
			continue
		}
		if same(f1, p2[0], 1) && same(f2, p2[0], 1) {
			p2 = p2[1:]
			continue
		}
		r = append(r, edge{p1[0], p2[0]})
		union(f1, p1[0], p2[0])
		union(f2, p1[0], p2[0])
	}
	return r
}

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

type edge struct {
	a, b int
}

func rw(r io.Reader, w io.Writer) {
	var n, m1, m2 int
	fmt.Fscan(r, &n, &m1, &m2)
	e1 := make([]edge, m1)
	for i := 0; i < m1; i++ {
		fmt.Fscan(r, &e1[i].a, &e1[i].b)
	}
	e2 := make([]edge, m2)
	for i := 0; i < m2; i++ {
		fmt.Fscan(r, &e2[i].a, &e2[i].b)
	}
	w1 := do(n, e1[:m1], e2[:m2])
	fmt.Fprintln(w, len(w1))
	for _, v := range w1 {
		fmt.Fprintln(w, v.a, v.b)
	}
}

func getF(f []int, x int) int {
	if f[x] != x {
		f[x] = getF(f, f[x])
	}
	return f[x]
}

func newF(n int) []int {
	f := make([]int, n+1)
	for i := 1; i <= n; i++ {
		f[i] = i
	}
	return f
}

func newInitF(n int, e []edge) []int {
	f := newF(n)
	for _, v := range e {
		union(f, v.a, v.b)
	}
	return f
}

func union(f []int, i, j int) {
	fi, fj := getF(f, i), getF(f, j)
	f[fi] = fj
}

func same(f []int, i, j int) bool {
	return getF(f, i) == getF(f, j)
}

func getP(f []int, n, j int) []int {
	var p []int
	for i := 1; i <= n; i++ {
		if !same(f, i, j) {
			p = append(p, i)
		}
	}
	return p
}

func do(n int, e1, e2 []edge) []edge {
	return do2(n, e1, e2)
}

var _, _ = do1, do2

func do1(n int, e1, e2 []edge) []edge {
	f1 := newInitF(n, e1)
	f2 := newInitF(n, e2)
	var r []edge
	for i := 2; i <= n; i++ {
		if !same(f1, 1, i) && !same(f2, 1, i) {
			r = append(r, edge{1, i})
			union(f1, 1, i)
			union(f2, 1, i)
		}
	}
	p1 := getP(f1, n, 1)
	p2 := getP(f2, n, 1)

	for len(p1) > 0 && len(p2) > 0 {
		if same(f1, p1[0], 1) && same(f2, p1[0], 1) {
			p1 = p1[1:]
			continue
		}
		if same(f1, p2[0], 1) && same(f2, p2[0], 1) {
			p2 = p2[1:]
			continue
		}
		r = append(r, edge{p1[0], p2[0]})
		union(f1, p1[0], p2[0])
		union(f2, p1[0], p2[0])
	}
	return r
}

func do2(n int, e1, e2 []edge) []edge {
	if len(e1) < len(e2) {
		e1, e2 = e2, e1
	}
	f1 := newInitF(n, e1)
	f2 := newInitF(n, e2)
	row := map[int]map[int]struct{}{}
	col := map[int]map[int]struct{}{}
	rep := map[int]map[int]int{}
	for i := 1; i <= n; i++ {
		x, y := getF(f1, i), getF(f2, i)
		if row[x] == nil {
			row[x] = map[int]struct{}{}
		}
		row[x][y] = struct{}{}
		if col[y] == nil {
			col[y] = map[int]struct{}{}
		}
		col[y][x] = struct{}{}
		if rep[x] == nil {
			rep[x] = map[int]int{}
		}
		rep[x][y] = i
	}

	x := make([]int, 0, len(row))
	for k := range row {
		x = append(x, k)
	}
	for i, xi := range x {
		if len(row[xi]) > 1 {
			x[0], x[i] = x[i], x[0]
			break
		}
	}

	var ans []edge
	for len(x) >= 2 {
		r0 := row[x[0]]
		r1 := row[x[1]]

		var y0, y1 int
		for y0 = range r0 {
			for y1 = range r1 {
				if y0 != y1 {
					break
				}
			}
		}

		ans = append(ans, edge{rep[x[0]][y0], rep[x[1]][y1]})

		if len(r0) > len(r1) {
			x[0], x[1] = x[1], x[0]
		}

		if len(col[y0]) > len(col[y1]) {
			y0, y1 = y1, y0
		}

		mergeRow(row, col, x[0], x[1], rep)
		mergeCol(row, col, y0, y1, rep)

		x = x[1:]
	}
	return ans
}

func mergeRow(row, col map[int]map[int]struct{}, x0, x1 int, rep map[int]map[int]int) {
	for y := range row[x0] {
		row[x1][y] = struct{}{}
		rep[x1][y] = rep[x0][y]
		delete(col[y], x0)
		col[y][x1] = struct{}{}
	}
}

func mergeCol(row, col map[int]map[int]struct{}, y0, y1 int, rep map[int]map[int]int) {
	for x := range col[y0] {
		col[y1][x] = struct{}{}
		rep[x][y1] = rep[x][y0]
		delete(row[x], y0)
		row[x][y1] = struct{}{}
	}
}


Tsumugi brought $$$n$$$ delicious sweets to the Light Music Club. They are numbered from $$$1$$$ to $$$n$$$, where the $$$i$$$-th sweet has a sugar concentration described by an integer $$$a_i$$$.Yui loves sweets, but she can eat at most $$$m$$$ sweets each day for health reasons.Days are $$$1$$$-indexed (numbered $$$1, 2, 3, \ldots$$$). Eating the sweet $$$i$$$ at the $$$d$$$-th day will cause a sugar penalty of $$$(d \cdot a_i)$$$, as sweets become more sugary with time. A sweet can be eaten at most once.The total sugar penalty will be the sum of the individual penalties of each sweet eaten.Suppose that Yui chooses exactly $$$k$$$ sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?Since Yui is an undecided girl, she wants you to answer this question for every value of $$$k$$$ between $$$1$$$ and $$$n$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 200\ 000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 200\ 000$$$).

You have to output $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ on a single line, separed by spaces, where $$$x_k$$$ is the minimum total sugar penalty Yui can get if she eats exactly $$$k$$$ sweets.

NoteLet's analyze the answer for $$$k = 5$$$ in the first example. Here is one of the possible ways to eat $$$5$$$ sweets that minimize total sugar penalty:  Day $$$1$$$: sweets $$$1$$$ and $$$4$$$  Day $$$2$$$: sweets $$$5$$$ and $$$3$$$  Day $$$3$$$ : sweet $$$6$$$ Total penalty is $$$1 \cdot a_1 + 1 \cdot a_4 + 2 \cdot a_5 + 2 \cdot a_3 + 3 \cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30$$$. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats $$$5$$$ sweets, hence $$$x_5 = 30$$$.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	q := 1
	//fmt.Fscanf(in, "%d\n", &q)
	for ii := 0; ii < q; ii++ {
		n, m := 0, 0
		fmt.Fscanf(in, "%d %d\n", &n, &m)
		a := make([]int, n)
		sum := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &a[i])
		}
		fmt.Fscanf(in, "\n")
		sort.Ints(a)
		sum[0] = int64(a[0])
		for i := 1; i < n; i++ {
			sum[i] = sum[i-1] + int64(a[i])
		}
		f := make([]int64, n)
		for i := 0; i < m; i++ {
			f[i] = sum[i]
		}
		for i := m; i < n; i++ {
			f[i] = f[i-m] + sum[i]
		}
		fmt.Fprintf(out, "%d", f[0])
		for i := 1; i < n; i++ {
			fmt.Fprintf(out, " %d", f[i])
		}
		fmt.Fprintf(out, "\n")
	}
	return
}

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

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

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

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

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

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

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

// 	for i := 0; i < len(A); i++ {
// 		str := strconv.Itoa(A[i])
// 		// 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)
// }

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n, m int
var A []int
var answers []int64

func main() {
	n, m = ReadInt2()
	A = ReadIntSlice(n)
	answers = make([]int64, n)

	sort.Sort(sort.IntSlice(A))

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

	for i := 0; i < n; i++ {
		if i < m {
			answers[i] = sums[i+1]
			continue
		}

		answers[i] = answers[i-m] + sums[i+1]
	}

	for i := 0; i < n; i++ {
		if i == n {
			fmt.Printf("%d\n", answers[i])
		} else {
			fmt.Printf("%d ", answers[i])
		}
	}
}

func PrintIntsLine(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		// str := strconv.Itoa(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)
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

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

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

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

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

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

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

// 	for i := 0; i < len(A); i++ {
// 		str := strconv.Itoa(A[i])
// 		// 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)
// }

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n, m int
var A []int
var answers []int64

func main() {
	n, m = ReadInt2()
	A = ReadIntSlice(n)
	// answers = []int64{}
	answers = make([]int64, n)

	sort.Sort(sort.IntSlice(A))
	// fmt.Println(A)

	memo := make([]int64, n)
	for i := 0; i < m; i++ {
		memo[i] = int64(A[i])
	}
	for i := m; i < n; i++ {
		memo[i] = memo[i-m] + int64(A[i])
	}

	answers[0] = int64(A[0])
	for i := 1; i < n; i++ {
		answers[i] = answers[i-1] + memo[i]
	}
	// for i := 0; i < n; i++ {
	// 	if i == n {
	// 		fmt.Printf("%d\n", answers[i])
	// 	} else {
	// 		fmt.Printf("%d ", answers[i])
	// 	}
	// }
	fmt.Println(PrintIntsLine(answers...))
}

func PrintIntsLine(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		// str := strconv.Itoa(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)
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

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

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

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

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

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

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

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

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

	return string(res)
}

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

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n, m int
var A []int
var answers []int64

func main() {
	n, m = ReadInt2()
	A = ReadIntSlice(n)
	answers = make([]int64, n)

	sort.Sort(sort.IntSlice(A))

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

	for i := 0; i < n; i++ {
		if i < m {
			answers[i] = sums[i+1]
			continue
		}

		answers[i] = answers[i-m] + sums[i+1]
	}
	fmt.Println(PrintInts64Line(answers...))
}

/*
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
*/

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


A piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations — choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.

The first line contains two integers n and k (1 ≤ n ≤ 105; 0 ≤ k ≤ 109) — the number of elements in the array and the number of operations you are allowed to perform, correspondingly. The third line contains a sequence of n integers a1, a2, ..., an (|ai| ≤ 109) — the initial array. The numbers in the lines are separated by single spaces.

In a single line print two numbers — the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.

NoteIn the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6, 4, 4, 0, 4, where number 4 occurs 3 times.In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5, 5, 5, if we increase each by one, we get 6, 6, 6. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3, 2, 2, 2, 2, where number 2 occurs 4 times.

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/231/C

package main

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

func getPrefixSum(p []int64, i, j int) int64 {
	if j == 0 {
		return p[i]
	}
	return p[i] - p[j-1]
}

func Solve(n int, k int, a []int) (int, int) {
	sort.Ints(a)
	p := make([]int64, n)
	p[0] = int64(a[0])
	for i := 1; i < n; i++ {
		p[i] = p[i-1] + int64(a[i])
	}
	i := 0
	j := 0
	maxLength := 0
	maxValue := 0
	for i < n {
		for int64(a[i])*int64(i-j+1)-getPrefixSum(p, i, j) > int64(k) {
			j += 1
		}
		if i-j+1 > maxLength {
			maxLength = i - j + 1
			maxValue = a[i]
		}
		i += 1
	}
	return maxLength, maxValue
}

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

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

	count, value := Solve(n, k, a)
	fmt.Fprintf(writer, "%d %d\n", count, value)
}