You are given a rectangular parallelepiped with sides of positive integer lengths $$$A$$$, $$$B$$$ and $$$C$$$. Find the number of different groups of three integers ($$$a$$$, $$$b$$$, $$$c$$$) such that $$$1\leq a\leq b\leq c$$$ and parallelepiped $$$A\times B\times C$$$ can be paved with parallelepipeds $$$a\times b\times c$$$. Note, that all small parallelepipeds have to be rotated in the same direction.For example, parallelepiped $$$1\times 5\times 6$$$ can be divided into parallelepipeds $$$1\times 3\times 5$$$, but can not be divided into parallelepipeds $$$1\times 2\times 3$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. Each of the next $$$t$$$ lines contains three integers $$$A$$$, $$$B$$$ and $$$C$$$ ($$$1 \leq A, B, C \leq 10^5$$$) — the sizes of the parallelepiped.

For each test case, print the number of different groups of three points that satisfy all given conditions.

NoteIn the first test case, rectangular parallelepiped $$$(1, 1, 1)$$$ can be only divided into rectangular parallelepiped with sizes $$$(1, 1, 1)$$$.In the second test case, rectangular parallelepiped $$$(1, 6, 1)$$$ can be divided into rectangular parallelepipeds with sizes $$$(1, 1, 1)$$$, $$$(1, 1, 2)$$$, $$$(1, 1, 3)$$$ and $$$(1, 1, 6)$$$.In the third test case, rectangular parallelepiped $$$(2, 2, 2)$$$ can be divided into rectangular parallelepipeds with sizes $$$(1, 1, 1)$$$, $$$(1, 1, 2)$$$, $$$(1, 2, 2)$$$ and $$$(2, 2, 2)$$$.

package main

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

func CalDiv(n int) []int {
	res := make([]int, n+1)

	for i := 1; i <= n; i++ {
		for j := i; j <= n; j += i {
			res[j]++
		}
	}

	return res
}

func Gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func IsMatch(ta, tb, tc int) bool {
	if (ta&1) != 0 && (tb&2) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&1) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&1) != 0 && (tb&4) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&1) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&2) != 0 && (tc&1) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&4) != 0 && (tc&1) != 0 {
		return true
	} else {
		return false
	}
}

func OneCase(div_cnt []int, a, b, c int) int {
	ab := Gcd(a, b)
	bc := Gcd(b, c)
	ac := Gcd(a, c)
	abc := Gcd(ab, c)

	//fmt.Println(ab)

	state_cnt := make([]int, 8)
	state_cnt[7] = div_cnt[abc]                                          //111
	state_cnt[6] = div_cnt[ab] - div_cnt[abc]                            //110
	state_cnt[5] = div_cnt[ac] - div_cnt[abc]                            //101
	state_cnt[3] = div_cnt[bc] - div_cnt[abc]                            //011
	state_cnt[4] = div_cnt[a] - div_cnt[ac] - div_cnt[ab] + div_cnt[abc] //100
	state_cnt[2] = div_cnt[b] - div_cnt[bc] - div_cnt[ab] + div_cnt[abc] //010
	state_cnt[1] = div_cnt[c] - div_cnt[ac] - div_cnt[bc] + div_cnt[abc] //001

	//fmt.Println(state_cnt)

	res := 0

	for ta := 1; ta <= 7; ta++ {
		for tb := ta; tb <= 7; tb++ {
			for tc := tb; tc <= 7; tc++ {
				if IsMatch(ta, tb, tc) { //match a b c
					var tmp int
					if ta == tb && tb == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) * (state_cnt[ta] + 2) / 6
					} else if ta == tb {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tc]
					} else if ta == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tb]
					} else if tb == tc {
						tmp = state_cnt[tb] * (state_cnt[tb] + 1) / 2 * state_cnt[ta]
					} else {
						tmp = state_cnt[ta] * state_cnt[tb] * state_cnt[tc]
					}

					if tmp != 0 {
						res += tmp
						//fmt.Println(ta, tb, tc, tmp)
					}
				}
			}
		}
	}

	return res
}

func main() {
	in := bufio.NewReader(os.Stdin)
	div_cnt := CalDiv(100005)

	for {
		var n int
		_, err := fmt.Scanln(&n)
		if err != nil {
			break
		}

		for i := 0; i < n; i++ {
			var a, b, c int
			fmt.Fscanf(in, "%d%d%d\n", &a, &b, &c)

			fmt.Println(OneCase(div_cnt, a, b, c))
		}

	}
}

package main

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

func CalDiv(n int) []int {
	res := make([]int, n+1)

	for i := 1; i <= n; i++ {
		for j := i; j <= n; j += i {
			res[j]++
		}
	}

	return res
}

func Gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func IsMatch(ta, tb, tc int) bool {
	if (ta&1) != 0 && (tb&2) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&1) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&1) != 0 && (tb&4) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&1) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&2) != 0 && (tc&1) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&4) != 0 && (tc&1) != 0 {
		return true
	} else {
		return false
	}
}

func OneCase(div_cnt []int, a, b, c int) int {
	ab := Gcd(a, b)
	bc := Gcd(b, c)
	ac := Gcd(a, c)
	abc := Gcd(ab, c)

	//fmt.Println(ab)

	state_cnt := make([]int, 8)
	state_cnt[7] = div_cnt[abc]                                          //111
	state_cnt[6] = div_cnt[ab] - div_cnt[abc]                            //110
	state_cnt[5] = div_cnt[ac] - div_cnt[abc]                            //101
	state_cnt[3] = div_cnt[bc] - div_cnt[abc]                            //011
	state_cnt[4] = div_cnt[a] - div_cnt[ac] - div_cnt[ab] + div_cnt[abc] //100
	state_cnt[2] = div_cnt[b] - div_cnt[bc] - div_cnt[ab] + div_cnt[abc] //010
	state_cnt[1] = div_cnt[c] - div_cnt[ac] - div_cnt[bc] + div_cnt[abc] //001

	//fmt.Println(state_cnt)

	res := 0

	for ta := 1; ta <= 7; ta++ {
		for tb := ta; tb <= 7; tb++ {
			for tc := tb; tc <= 7; tc++ {
				if IsMatch(ta, tb, tc) { //match a b c
					var tmp int
					if ta == tb && tb == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) * (state_cnt[ta] + 2) / 6
					} else if ta == tb {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tc]
					} else if ta == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tb]
					} else if tb == tc {
						tmp = state_cnt[tb] * (state_cnt[tb] + 1) / 2 * state_cnt[ta]
					} else {
						tmp = state_cnt[ta] * state_cnt[tb] * state_cnt[tc]
					}

					if tmp != 0 {
						res += tmp
						//fmt.Println(ta, tb, tc, tmp)
					}
				}
			}
		}
	}

	return res
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 16384)
	out := bufio.NewWriterSize(os.Stdout, 16384)

	div_cnt := CalDiv(100005)

	for {
		var n int
		_, err := fmt.Scanln(&n)
		if err != nil {
			break
		}

		for i := 0; i < n; i++ {
			var a, b, c int
			fmt.Fscanf(in, "%d%d%d\n", &a, &b, &c)

			fmt.Fprintln(out, OneCase(div_cnt, a, b, c))
		}

		out.Flush()
	}
}

package main

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

func CalDiv(n int) []int {
	res := make([]int, n+1)

	for i := 1; i <= n; i++ {
		for j := i; j <= n; j += i {
			res[j]++
		}
	}

	return res
}

func Gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func IsMatch(ta, tb, tc int) bool {
	if (ta&1) != 0 && (tb&2) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&1) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&1) != 0 && (tb&4) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&1) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&2) != 0 && (tc&1) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&4) != 0 && (tc&1) != 0 {
		return true
	} else {
		return false
	}
}

func OneCase(div_cnt []int, a, b, c int) int {
	ab := Gcd(a, b)
	bc := Gcd(b, c)
	ac := Gcd(a, c)
	abc := Gcd(ab, c)

	//fmt.Println(ab)

	state_cnt := make([]int, 8)
	state_cnt[7] = div_cnt[abc]                                          //111
	state_cnt[6] = div_cnt[ab] - div_cnt[abc]                            //110
	state_cnt[5] = div_cnt[ac] - div_cnt[abc]                            //101
	state_cnt[3] = div_cnt[bc] - div_cnt[abc]                            //011
	state_cnt[4] = div_cnt[a] - div_cnt[ac] - div_cnt[ab] + div_cnt[abc] //100
	state_cnt[2] = div_cnt[b] - div_cnt[bc] - div_cnt[ab] + div_cnt[abc] //010
	state_cnt[1] = div_cnt[c] - div_cnt[ac] - div_cnt[bc] + div_cnt[abc] //001

	//fmt.Println(state_cnt)

	res := 0

	for ta := 1; ta <= 7; ta++ {
		for tb := ta; tb <= 7; tb++ {
			for tc := tb; tc <= 7; tc++ {
				if IsMatch(ta, tb, tc) { //match a b c
					var tmp int
					if ta == tb && tb == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) * (state_cnt[ta] + 2) / 6
					} else if ta == tb {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tc]
					} else if ta == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tb]
					} else if tb == tc {
						tmp = state_cnt[tb] * (state_cnt[tb] + 1) / 2 * state_cnt[ta]
					} else {
						tmp = state_cnt[ta] * state_cnt[tb] * state_cnt[tc]
					}

					if tmp != 0 {
						res += tmp
						//fmt.Println(ta, tb, tc, tmp)
					}
				}
			}
		}
	}

	return res
}

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

	div_cnt := CalDiv(100005)

	for {
		var n int
		_, err := fmt.Scanln(&n)
		if err != nil {
			break
		}

		for i := 0; i < n; i++ {
			var a, b, c int
			fmt.Fscanf(in, "%d%d%d\n", &a, &b, &c)

			fmt.Fprintln(out, OneCase(div_cnt, a, b, c))
		}

		out.Flush()
	}
}

package main

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

func CalDiv(n int) []int {
	res := make([]int, n+1)

	for i := 1; i <= n; i++ {
		for j := i; j <= n; j += i {
			res[j]++
		}
	}

	return res
}

func Gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func IsMatch(ta, tb, tc int) bool {
	if (ta&1) != 0 && (tb&2) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&1) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&1) != 0 && (tb&4) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&1) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&2) != 0 && (tc&1) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&4) != 0 && (tc&1) != 0 {
		return true
	} else {
		return false
	}
}

func OneCase(div_cnt []int, a, b, c int) int {
	ab := Gcd(a, b)
	bc := Gcd(b, c)
	ac := Gcd(a, c)
	abc := Gcd(ab, c)

	//fmt.Println(ab)

	state_cnt := make([]int, 8)
	state_cnt[7] = div_cnt[abc]                                          //111
	state_cnt[6] = div_cnt[ab] - div_cnt[abc]                            //110
	state_cnt[5] = div_cnt[ac] - div_cnt[abc]                            //101
	state_cnt[3] = div_cnt[bc] - div_cnt[abc]                            //011
	state_cnt[4] = div_cnt[a] - div_cnt[ac] - div_cnt[ab] + div_cnt[abc] //100
	state_cnt[2] = div_cnt[b] - div_cnt[bc] - div_cnt[ab] + div_cnt[abc] //010
	state_cnt[1] = div_cnt[c] - div_cnt[ac] - div_cnt[bc] + div_cnt[abc] //001

	//fmt.Println(state_cnt)

	res := 0

	for ta := 1; ta <= 7; ta++ {
		for tb := ta; tb <= 7; tb++ {
			for tc := tb; tc <= 7; tc++ {
				if IsMatch(ta, tb, tc) { //match a b c
					var tmp int
					if ta == tb && tb == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) * (state_cnt[ta] + 2) / 6
					} else if ta == tb {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tc]
					} else if ta == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tb]
					} else if tb == tc {
						tmp = state_cnt[tb] * (state_cnt[tb] + 1) / 2 * state_cnt[ta]
					} else {
						tmp = state_cnt[ta] * state_cnt[tb] * state_cnt[tc]
					}

					if tmp != 0 {
						res += tmp
						//fmt.Println(ta, tb, tc, tmp)
					}
				}
			}
		}
	}

	return res
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 1024)
	out := bufio.NewWriterSize(os.Stdout, 1024)

	div_cnt := CalDiv(100005)

	for {
		var n int
		_, err := fmt.Scanln(&n)
		if err != nil {
			break
		}

		for i := 0; i < n; i++ {
			var a, b, c int
			fmt.Fscanf(in, "%d%d%d\n", &a, &b, &c)

			fmt.Fprintln(out, OneCase(div_cnt, a, b, c))
		}

		out.Flush()
	}
}

package main

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

func CalDiv(n int) []int {
	res := make([]int, n+1)

	for i := 1; i <= n; i++ {
		for j := i; j <= n; j += i {
			res[j]++
		}
	}

	return res
}

func Gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func IsMatch(ta, tb, tc int) bool {
	if (ta&1) != 0 && (tb&2) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&1) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&1) != 0 && (tb&4) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&1) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&2) != 0 && (tc&1) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&4) != 0 && (tc&1) != 0 {
		return true
	} else {
		return false
	}
}

func OneCase(div_cnt []int, a, b, c int) int {
	ab := Gcd(a, b)
	bc := Gcd(b, c)
	ac := Gcd(a, c)
	abc := Gcd(ab, c)

	//fmt.Println(ab)

	state_cnt := make([]int, 8)
	state_cnt[7] = div_cnt[abc]                                          //111
	state_cnt[6] = div_cnt[ab] - div_cnt[abc]                            //110
	state_cnt[5] = div_cnt[ac] - div_cnt[abc]                            //101
	state_cnt[3] = div_cnt[bc] - div_cnt[abc]                            //011
	state_cnt[4] = div_cnt[a] - div_cnt[ac] - div_cnt[ab] + div_cnt[abc] //100
	state_cnt[2] = div_cnt[b] - div_cnt[bc] - div_cnt[ab] + div_cnt[abc] //010
	state_cnt[1] = div_cnt[c] - div_cnt[ac] - div_cnt[bc] + div_cnt[abc] //001

	//fmt.Println(state_cnt)

	res := 0

	for ta := 1; ta <= 7; ta++ {
		for tb := ta; tb <= 7; tb++ {
			for tc := tb; tc <= 7; tc++ {
				if IsMatch(ta, tb, tc) { //match a b c
					var tmp int
					if ta == tb && tb == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) * (state_cnt[ta] + 2) / 6
					} else if ta == tb {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tc]
					} else if ta == tc {
						tmp = state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tb]
					} else if tb == tc {
						tmp = state_cnt[tb] * (state_cnt[tb] + 1) / 2 * state_cnt[ta]
					} else {
						tmp = state_cnt[ta] * state_cnt[tb] * state_cnt[tc]
					}

					if tmp != 0 {
						res += tmp
						//fmt.Println(ta, tb, tc, tmp)
					}
				}
			}
		}
	}

	return res
}

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

	div_cnt := CalDiv(100005)

	for {
		var n int
		_, err := fmt.Scanln(&n)
		if err != nil {
			break
		}

		out := bufio.NewWriter(os.Stdout)

		for i := 0; i < n; i++ {
			var a, b, c int
			fmt.Fscanf(in, "%d%d%d\n", &a, &b, &c)

			fmt.Fprintln(out, OneCase(div_cnt, a, b, c))
		}

		out.Flush()
	}
}

package main

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

func CalDiv(n int) []int {
	res := make([]int, n+1)

	for i := 1; i <= n; i++ {
		for j := i; j <= n; j += i {
			res[j]++
		}
	}

	return res
}

func Gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func IsMatch(ta, tb, tc int) bool {
	if (ta&1) != 0 && (tb&2) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&1) != 0 && (tc&4) != 0 {
		return true
	} else if (ta&1) != 0 && (tb&4) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&1) != 0 && (tc&2) != 0 {
		return true
	} else if (ta&4) != 0 && (tb&2) != 0 && (tc&1) != 0 {
		return true
	} else if (ta&2) != 0 && (tb&4) != 0 && (tc&1) != 0 {
		return true
	} else {
		return false
	}
}

func OneCase(div_cnt []int, a, b, c int) int {
	ab := Gcd(a, b)
	bc := Gcd(b, c)
	ac := Gcd(a, c)
	abc := Gcd(ab, c)

	state_cnt := make([]int, 8)
	state_cnt[7] = div_cnt[abc]                                          //111
	state_cnt[6] = div_cnt[bc] - div_cnt[abc]                            //110
	state_cnt[5] = div_cnt[ac] - div_cnt[abc]                            //101
	state_cnt[3] = div_cnt[bc] - div_cnt[abc]                            //011
	state_cnt[4] = div_cnt[a] - div_cnt[ac] - div_cnt[ab] + div_cnt[abc] //100
	state_cnt[2] = div_cnt[b] - div_cnt[bc] - div_cnt[ab] + div_cnt[abc] //010
	state_cnt[1] = div_cnt[c] - div_cnt[ac] - div_cnt[bc] + div_cnt[abc] //001

	//fmt.Println(state_cnt)

	res := 0

	for ta := 1; ta <= 7; ta++ {
		for tb := ta; tb <= 7; tb++ {
			for tc := tb; tc <= 7; tc++ {
				if IsMatch(ta, tb, tc) { //match a b c
					if ta == tb && tb == tc {
						res += state_cnt[ta] * (state_cnt[ta] + 1) * (state_cnt[ta] + 2) / 6
					} else if ta == tb {
						res += state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tc]
					} else if ta == tc {
						res += state_cnt[ta] * (state_cnt[ta] + 1) / 2 * state_cnt[tb]
					} else if tb == tc {
						res += state_cnt[tb] * (state_cnt[tb] + 1) / 2 * state_cnt[ta]
					} else {
						res += state_cnt[ta] * state_cnt[tb] * state_cnt[tc]
					}
				}
			}
		}
	}

	return res
}

func main() {
	in := bufio.NewReader(os.Stdin)
	div_cnt := CalDiv(100005)

	for {
		var n int
		_, err := fmt.Scanln(&n)
		if err != nil {
			break
		}

		for i := 0; i < n; i++ {
			var a, b, c int
			fmt.Fscanf(in, "%d%d%d\n", &a, &b, &c)

			fmt.Println(OneCase(div_cnt, a, b, c))
		}

	}
}


You have a playlist consisting of $$$n$$$ songs. The $$$i$$$-th song is characterized by two numbers $$$t_i$$$ and $$$b_i$$$ — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of $$$3$$$ songs having lengths $$$[5, 7, 4]$$$ and beauty values $$$[11, 14, 6]$$$ is equal to $$$(5 + 7 + 4) \cdot 6 = 96$$$.You need to choose at most $$$k$$$ songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$) – the number of songs in the playlist and the maximum number of songs you can choose, respectively. Each of the next $$$n$$$ lines contains two integers $$$t_i$$$ and $$$b_i$$$ ($$$1 \le t_i, b_i \le 10^6$$$) — the length and beauty of $$$i$$$-th song.

Print one integer — the maximum pleasure you can get.

NoteIn the first test case we can choose songs $$${1, 3, 4}$$$, so the total pleasure is $$$(4 + 3 + 6) \cdot 6 = 78$$$.In the second test case we can choose song $$$3$$$. The total pleasure will be equal to $$$100 \cdot 100 = 10000$$$.

package main

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

type intHeap struct {
	sort.IntSlice
}

func (h *intHeap) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *intHeap) Pop() (v interface{}) {
	n := len(h.IntSlice)
	h.IntSlice, v = h.IntSlice[:n-1], h.IntSlice[n-1]
	return
}

// github.com/EndlessCheng/codeforces-go
func Sol1140C(reader io.Reader, writer io.Writer) {
	type pair struct {
		x, y int
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n, k int
	Fscan(in, &n, &k)
	arr := make([]pair, n)
	for i := range arr {
		Fscan(in, &arr[i].y, &arr[i].x)
	}
	sort.Slice(arr, func(i, j int) bool { return arr[i].x > arr[j].x || arr[i].x == arr[j].x && arr[i].y > arr[j].y })

	var ans, sum int64
	h := &intHeap{}
	for _, p := range arr {
		Push(h, p.y)
		sum += int64(p.y)
		for h.Len() > k {
			sum -= int64(Pop(h).(int))
		}
		if newAns := sum * int64(p.x); newAns > ans {
			ans = newAns
		}
	}
	Fprint(out, ans)
}

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

package main

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

type intHeap1140C struct {
	sort.IntSlice
}

func (h *intHeap1140C) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *intHeap1140C) Pop() (v interface{}) {
	n := len(h.IntSlice)
	h.IntSlice, v = h.IntSlice[:n-1], h.IntSlice[n-1]
	return
}

// github.com/EndlessCheng/codeforces-go
func Sol1140C(reader io.Reader, writer io.Writer) {
	type pair struct {
		x, y int
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n, k int
	Fscan(in, &n, &k)
	arr := make([]pair, n)
	for i := range arr {
		Fscan(in, &arr[i].y, &arr[i].x)
	}
	sort.Slice(arr, func(i, j int) bool { return arr[i].x > arr[j].x || arr[i].x == arr[j].x && arr[i].y > arr[j].y })

	var ans, sum int64
	h := &intHeap1140C{sort.IntSlice(make([]int, 0, n))}
	for _, p := range arr {
		Push(h, p.y)
		sum += int64(p.y)
		for h.Len() > k {
			sum -= int64(Pop(h).(int))
		}
		if newAns := sum * int64(p.x); newAns > ans {
			ans = newAns
		}
	}
	Fprint(out, ans)
}

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

package main

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

type Song struct {
	t int
	b int
}

// ByAge implements sort.Interface for []Person based on
// the Age field.
type List []Song

func (a List) Len() int           { return len(a) }
func (a List) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a List) Less(i, j int) bool { return a[i].b > a[j].b }

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, k := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &k)
	t := make([]int, n)
	b := make([]int, n)
	list := []Song{}
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %d\n", &t[i], &b[i])
		list = append(list, Song{t[i], b[i]})
	}
	sort.Sort(List(list))
	//fmt.Println(list)
	h := &IntHeap{}
	heap.Init(h)
	sum := int64(0)
	ans := int64(0)
	for i := 0; i < k; i++ {
		heap.Push(h, list[i].t)
		sum += int64(list[i].t)
		if sum*int64(list[i].b) > ans {
			ans = sum * int64(list[i].b)
		}
	}
	//small := list[k-1].b
	//ans = int64(small) * int64(sum)
	for i := k; i < n; i++ {
		curSmall := heap.Pop(h).(int)
		sum -= int64(curSmall)
		if curSmall < list[i].t {
			curSmall = list[i].t
		}
		sum += int64(curSmall)
		heap.Push(h, curSmall)
		tmpAns := int64(list[i].b) * sum
		if tmpAns > ans {
			ans = tmpAns
		}
	}
	fmt.Fprintf(out, "%d\n", ans)
	return
}

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

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

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

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

// Author: sighduck
// URL: https://codeforces.com/contest/1140/problem/C

package main

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

type Song struct {
	length int64
	beauty int64
}

type Item struct {
	priority int64
	i        int
}

type PriorityQueue []Item

func (pq PriorityQueue) Len() int           { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool { return pq[i].priority < pq[j].priority }
func (pq *PriorityQueue) Pop() interface{} {
	last := (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return last
}
func (pq *PriorityQueue) Push(item interface{}) {
	*pq = append(*pq, item.(Item))
}
func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

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

func Solve(n, k int, songs []Song) int64 {
	sort.Slice(songs, func(i, j int) bool { return songs[i].beauty < songs[j].beauty })
	result := int64(0)
	sum := int64(0)
	pq := PriorityQueue{}
	heap.Init(&pq)
	for i := n - 1; i >= 0; i-- {
		heap.Push(&pq, Item{songs[i].length, i})
		sum += songs[i].length
		for pq.Len() > k {
			sum -= heap.Pop(&pq).(Item).priority
		}
		result = max(result, sum*songs[i].beauty)
	}
	return result
}

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)
	songs := make([]Song, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &songs[i].length, &songs[i].beauty)
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, k, songs))
}

package main

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

type Song struct {
	t int
	b int
}

// ByAge implements sort.Interface for []Person based on
// the Age field.
type List []Song

func (a List) Len() int           { return len(a) }
func (a List) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a List) Less(i, j int) bool { return a[i].b > a[j].b }

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, k := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &k)
	t := make([]int, n)
	b := make([]int, n)
	list := []Song{}
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %d\n", &t[i], &b[i])
		list = append(list, Song{t[i], b[i]})
	}
	sort.Sort(List(list))
	//fmt.Println(list)
	h := IntHeap{}
	heap.Init(&h)
	sum := int64(0)
	ans := int64(0)
	for i := 0; i < k; i++ {
		h = append(h, list[i].t)
		sum += int64(list[i].t)
		if sum*int64(list[i].b) > ans {
			ans = sum * int64(list[i].b)
		}
	}
	//small := list[k-1].b
	//ans = int64(small) * int64(sum)
	for i := k; i < n; i++ {
		curSmall := heap.Pop(&h).(int)
		sum -= int64(curSmall)
		if curSmall < list[i].t {
			curSmall = list[i].t
		}
		sum += int64(curSmall)
		heap.Push(&h, curSmall)
		tmpAns := int64(list[i].b) * sum
		if tmpAns > ans {
			ans = tmpAns
		}
	}
	fmt.Fprintf(out, "%d\n", ans)
	return
}

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

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

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

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

package main

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

type Song struct {
	t int
	b int
}

// ByAge implements sort.Interface for []Person based on
// the Age field.
type List []Song

func (a List) Len() int           { return len(a) }
func (a List) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a List) Less(i, j int) bool { return a[i].b > a[j].b }

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, k := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &k)
	t := make([]int, n)
	b := make([]int, n)
	list := []Song{}
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %d\n", &t[i], &b[i])
		list = append(list, Song{t[i], b[i]})
	}
	sort.Sort(List(list))
	h := &IntHeap{}
	heap.Init(h)
	sum := int64(0)
	ans := int64(0)
	for i := 0; i < k; i++ {
		*h = append(*h, list[i].t)
		sum += int64(list[i].t)
		if sum*int64(list[i].b) > ans {
			ans = sum * int64(list[i].b)
		}
	}
	//small := list[k-1].b
	//ans = int64(small) * int64(sum)
	for i := k; i < n; i++ {
		curSmall := heap.Pop(h).(int)
		sum -= int64(curSmall)
		if curSmall < list[i].t {
			curSmall = list[i].t
		}
		sum += int64(curSmall)
		heap.Push(h, curSmall)
		tmpAns := int64(list[i].b) * sum
		if tmpAns > ans {
			ans = tmpAns
		}
	}
	fmt.Fprintf(out, "%d\n", ans)
	return
}

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

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

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

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

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

package main

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

type Song struct {
	Length int64
	Beauty int64
}

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

func Solve(n int, k int, songs []Song) int64 {
	sort.Slice(songs, func(i, j int) bool { return songs[i].Beauty < songs[j].Beauty })
	prefix := make([]int64, n+1)
	prefix[n-1] = songs[n-1].Length
	for i := n - 2; i >= 0; i-- {
		prefix[i] = prefix[i+1] + songs[i].Length
	}
	maxPleasure := int64(0)
	for i, song := range songs {
		if i < n-k {
			maxPleasure = max(maxPleasure, song.Beauty*(song.Length+prefix[n-k+1]))
		} else {
			maxPleasure = max(maxPleasure, song.Beauty*prefix[i])
		}
	}
	return maxPleasure
}

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)
	songs := make([]Song, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &songs[i].Length, &songs[i].Beauty)
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, k, songs))
}


You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears:  Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one;  Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows:  Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$;  then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$;  then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$;  then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$;  and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.

package main

import (
	"bufio"
	"os"
	"strconv"

	"fmt"
	"container/heap"
	"strings"
)

type Item struct {
	left, right int
	index int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	if (pq[i].right - pq[i].left) > (pq[j].right - pq[j].left) {
		return true
	} else if (pq[i].right - pq[i].left) == (pq[j].right - pq[j].left) {
		return pq[i].left < pq[j].left
	} else {
		return false
	}
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

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

	buff := make([]byte, 2 * 1024 * 1024)

	scanner.Buffer(buff, 1024 * 1024)

	scanner.Scan()

	t := scanner.Text()

	testCases, err := strconv.Atoi(t)

	if err != nil {
		panic(err)
	}

	for j := 0; j < int(testCases); j ++ {
		scanner.Scan()

		al := scanner.Text()

		a, err := strconv.Atoi(al)

		if err != nil {
			panic(err)
		}

		ans := solve4(a)

		fmt.Print(strings.Trim(fmt.Sprintf("%v", ans), "[]"))

		fmt.Println()
	}
}

func solve4(a int) []int {
	counter := 1
	arr := make([]int, a + 1)

	var pq PriorityQueue

	pq = append(pq, &Item{left: 1, right: a})

	heap.Init(&pq)

	for ;len(pq) > 0; {

		item := heap.Pop(&pq)

		process(item.(*Item), &counter, &arr, &pq)
	}

	var result []int

	for i := 1; i < len(arr); i++ {
		result = append(result, arr[i])
	}

	return result
}

func process(item *Item, counter *int, arr *[]int, queue *PriorityQueue)  {
	a := item.left
	b := item.right

	if a == b {
		(*arr)[a] = *counter

		*counter ++

		return
	} else if a > b {
		return
	}

	var mid int

	if (b - a + 1) % 2 == 1 {
		mid = (b + a)/2
	} else {
		mid = (b + a - 1)/2
	}

	(*arr)[mid] = *counter

	*counter ++

	heap.Push(queue, &Item{left: mid + 1, right: b})
	heap.Push(queue, &Item{left: a, right: mid - 1})
}

/*
URL:
https://codeforces.com/problemset/problem/1353/D
*/

package main

import (
	"bufio"
	"container/heap"
	"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 (
	t int
	n int
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n = ReadInt()

		solve()
	}
}

func solve() {
	A := make([]int, n)

	pq := NewSegmentPQ()
	pq.push(&Segment{
		left: 0, right: n - 1, length: n,
	})

	i := 1
	for pq.Len() > 0 {
		pop := pq.pop()

		mid := (pop.left + pop.right) / 2
		A[mid] = i
		i++

		if (mid-1)-pop.left+1 > 0 {
			pq.push(&Segment{left: pop.left, right: mid - 1, length: (mid - 1) - pop.left + 1})
		}
		if pop.right-(mid+1)+1 > 0 {
			pq.push(&Segment{left: mid + 1, right: pop.right, length: pop.right - (mid + 1) + 1})
		}
	}

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

type Segment struct {
	pri         int
	left, right int
	length      int
}
type SegmentPQ []*Segment

// Interfaces
func NewSegmentPQ() *SegmentPQ {
	temp := make(SegmentPQ, 0)
	pq := &temp
	heap.Init(pq)

	return pq
}
func (pq *SegmentPQ) push(target *Segment) {
	heap.Push(pq, target)
}
func (pq *SegmentPQ) pop() *Segment {
	return heap.Pop(pq).(*Segment)
}

func (pq SegmentPQ) Len() int { return len(pq) }
func (pq SegmentPQ) Less(i, j int) bool {
	if pq[i].length > pq[j].length {
		return true
	} else if pq[i].length < pq[j].length {
		return false
	} else {
		return pq[i].left < pq[j].left
	}
} // <: ASC, >: DESC
func (pq SegmentPQ) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}
func (pq *SegmentPQ) Push(x interface{}) {
	item := x.(*Segment)
	*pq = append(*pq, item)
}
func (pq *SegmentPQ) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

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

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

type pair struct{ l, i int }
type hp []pair

func (h hp) Len() int            { return len(h) }
func (h hp) Less(i, j int) bool  { a, b := h[i], h[j]; return a.l > b.l || a.l == b.l && a.i < b.i }
func (h hp) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() interface{}   { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
func (h *hp) push(v pair)        { heap.Push(h, v) }
func (h *hp) pop() pair          { return heap.Pop(h).(pair) }

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

	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		ans := make([]interface{}, n)
		h := hp{{n - 1, 0}}
		for v := 1; v <= n; v++ {
			p := h.pop()
			l, i := p.l>>1, p.i
			ans[i+l] = v
			if l > 0 {
				h.push(pair{l - 1, i})
			}
			if p.l > l {
				h.push(pair{p.l - l - 1, i + l + 1})
			}
		}
		Fprintln(out, ans...)
	}
}

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

package main

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

func main() {
	for t := ScanInt(); t > 0; t-- {
		n := ScanInt()
		a := make([]int, n+1)
		val := 1
		hp := NewMaxHeap([]node{{1, n, n}})
		for len(hp.a) > 0 {
			poll := hp.Poll()
			mdl := 0

			if (poll.r-poll.l+1)%2 == 0 {
				mdl = (poll.l + poll.r - 1) / 2
			} else {
				mdl = (poll.l + poll.r) / 2
			}
			a[mdl] = val
			val++

			// put back in heap
			if poll.l < mdl && poll.l > 0 {
				leftNode := node{
					l: poll.l,
					r: mdl - 1,
				}
				leftNode.size = leftNode.r - leftNode.l + 1
				hp.Offer(leftNode)
			}
			if poll.r > mdl && poll.r <= n {
				rightNode := node{
					l: mdl + 1,
					r: poll.r,
				}
				rightNode.size = rightNode.r - rightNode.l + 1
				hp.Offer(rightNode)
			}
		}

		P(SArr(a[1:]))
	}

	close(O)
	oWg.Wait()
}

type node struct {
	l, r, size int
}

func NewMaxHeap(arg []node) heap {
	heap := heap{}
	heap.a = arg
	heap.cmp = func(i, j int, a []node) bool {
		if !(i >= 0 && i < len(a) && j >= 0 && j < len(a)) {
			return false
		}
		if heap.a[i].size > heap.a[j].size {
			return true
		} else if heap.a[i].size < heap.a[j].size {
			return false
		} else {
			return i <= j
		}
	}
	if len(arg) > 0 {
		heap.BuildHeap()
	}
	return heap
}

type heap struct {
	a   []node
	cmp func(i, j int, a []node) bool
}

func (h *heap) heapify(i int) {
	largest := i
	l := i<<1 + 1
	r := i<<1 + 2

	if l >= 0 && l < len(h.a) &&
		(h.a[l].size > h.a[largest].size ||
		(h.a[l].size == h.a[largest].size && h.a[l].l < h.a[largest].l)) { //h.a[parent].size > h.a[i].size || (h.a[parent].size >= h.a[i].size && h.a[parent].l <= h.a[i].l)
		largest = l
	}
	if r >= 0 && r < len(h.a) &&
		(h.a[r].size > h.a[largest].size ||
			(h.a[r].size == h.a[largest].size && h.a[r].l < h.a[largest].l)) { //h.a[parent].size > h.a[i].size || (h.a[parent].size >= h.a[i].size && h.a[parent].l <= h.a[i].l)
		largest = r
	}
	if largest != i {
		h.a[largest], h.a[i] = h.a[i], h.a[largest]
		h.heapify(largest)
	}
}

// build max heap
func (h *heap) BuildHeap() {
	for i := (len(h.a) / 2) - 1; i >= 0; i-- {
		h.heapify(i)
	}
}

func (h *heap) Poll() node {
	if len(h.a) == 0 {
		return node{}
	}
	ele := h.a[0]
	h.a[0] = h.a[len(h.a)-1]
	h.a = h.a[:len(h.a)-1]
	h.heapify(0)
	return ele
}

func (h *heap) Offer(key node) {
	h.a = append(h.a, key)

	for i := len(h.a) - 1; i >= 0; {
		parent := (i - 1) / 2
		if h.a[parent].size > h.a[i].size || (h.a[parent].size >= h.a[i].size && h.a[parent].l <= h.a[i].l) {
			return
		}
		h.a[parent], h.a[i] = h.a[i], h.a[parent]
		i = parent
	}
}

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

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

func init() {
	P = fmt.Println

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

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

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

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

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

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

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

package main

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

type Interval struct {l, r, sz int }
type priority_queue []*Interval

func Segment(l, r int) *Interval {
	if r - l >= 0 {return &Interval{l, r, r - l + 1} }
	return nil
}

func (pq priority_queue) Len() int { return len(pq) }

func (pq priority_queue) Less(i, j int) bool {
	return pq[i].sz > pq[j].sz || (pq[i].sz == pq[j].sz && pq[i].l < pq[j].l)
}

func (pq priority_queue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priority_queue) Push(x interface{}){
	*pq = append(*pq, x.(*Interval))
}

func (pq *priority_queue) Pop() interface{}{
	old := *pq
	s := old[len(old) - 1]
	old[len(old) - 1] = nil
	*pq = old[: len(old)-1]
	return s
}

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

	var tc int
	fmt.Fscan(reader, &tc)
	for ;tc > 0; tc-- {
		var n int
		fmt.Fscan(reader, &n)
		var pq priority_queue
		heap.Init(&pq)
		heap.Push(&pq, Segment(1, n))
		ans := make([]int, n)
		cnt := 1
		for pq.Len() > 0 {
			tp := heap.Pop(&pq)
			seg := tp.(*Interval)
			len := (seg.r - seg.l + 1)
			var i int
			if len % 2 == 1 {
				i = (seg.l + seg.r) / 2
			} else {
				i = (seg.l + seg.r - 1) / 2
			}
			if l := Segment(seg.l, i - 1); l != nil { heap.Push(&pq, l) }
			if r := Segment(i + 1, seg.r); r != nil { heap.Push(&pq, r) }
			ans[i - 1] = cnt
			cnt++
		}
		fmt.Fprintln(writer, strings.Trim(fmt.Sprint(ans), "[]"))
	}
}

package main

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

type segment struct {
	l, r, len int
}

func newSegment(l, r int) *segment {
	len := r - l + 1
	if len > 0 {
		return &segment{l, r, len}
	}
	return nil
}

type PriorityQueue []*segment

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].len > pq[j].len || (pq[i].len == pq[j].len && pq[i].l < pq[j].l)
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriorityQueue) Push(x interface{}) {
	s := x.(*segment)
	*pq = append(*pq, s)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	s := old[n-1]
	old[n-1] = nil
	*pq = old[0 : n-1]
	return s
}

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

	var t int
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		var n int
		fmt.Fscan(reader, &n)
		var pq PriorityQueue
		heap.Init(&pq)
		heap.Push(&pq, newSegment(1, n))

		ans := make([]int, n)
		cnt := 1
		for pq.Len() > 0 {
			e := heap.Pop(&pq)
			seg := e.(*segment)
			var idx int
			if (seg.r-seg.l+1)%2 == 1 {
				idx = (seg.l + seg.r) / 2
			} else {
				idx = (seg.l + seg.r - 1) / 2
			}
			if l := newSegment(seg.l, idx-1); l != nil {
				heap.Push(&pq, l)
			}
			if r := newSegment(idx+1, seg.r); r != nil {
				heap.Push(&pq, r)
			}
			ans[idx-1] = cnt
			cnt++
		}
		fmt.Fprintln(writer, strings.Trim(fmt.Sprint(ans), "[]"))
	}
}

package main

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

type Indexes []int

type ByLen []Indexes

func (a ByLen) Len() int           { return len(a) }
func (a ByLen) Less(i, j int) bool {

	if (a[i][1] - a[i][0] + 1) > (a[j][1] - a[j][0] + 1) {
		return true
	} else if (a[i][1] - a[i][0] + 1) == (a[j][1] - a[j][0] + 1) {
		return a[i][0] < a[j][0]
	}
	return false
}
func (a ByLen) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

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

	buff := make([]byte, 2 * 1024 * 1024)

	scanner.Buffer(buff, 1024 * 1024)

	scanner.Scan()

	t := scanner.Text()

	scanner.Text()

	testCases, err := strconv.Atoi(t)

	if err != nil {
		panic(err)
	}

	for j := 0; j < int(testCases); j ++ {
		scanner.Scan()

		al := scanner.Text()

		a, err := strconv.Atoi(al)

		if err != nil {
			panic(err)
		}

		ans := solve4(a)

		fmt.Print(strings.Trim(fmt.Sprintf("%v", ans), "[]"))

		fmt.Println()
	}
}

func solve4(a int) []int {
	counter := 1

	result := make([]int, a)

	var indexes []Indexes
	indexes = append(indexes, []int{0, a - 1})

	for ;len(indexes) > 0; {
		sort.Sort(ByLen(indexes))

		l := len(indexes)

		for i:=0; i < l; i++ {
			left := indexes[0][0]
			right := indexes[0][1]

			indexes = indexes[1 :]

			if left > right {
				continue
			}

			var mid int

			if (right - left + 1) % 2 == 1 {
				mid = (right + left)/2
			} else {
				mid = (right + left - 1)/2
			}

			result[mid] = counter

			counter ++

			if left == right {
				continue
			}

			indexes = append(indexes, []int {mid + 1, right})
			indexes = append(indexes, []int {left, mid - 1})
		}
	}

	return result
}

package main

import (
	"bufio"
	"os"
	"strconv"

	"fmt"
)

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

	buff := make([]byte, 2 * 1024 * 1024)

	scanner.Buffer(buff, 1024 * 1024)

	scanner.Scan()

	t := scanner.Text()

	testCases, err := strconv.Atoi(t)

	if err != nil {
		panic(err)
	}

	for j := 0; j < int(testCases); j ++ {
		scanner.Scan()

		al := scanner.Text()

		a, err := strconv.Atoi(al)

		if err != nil {
			panic(err)
		}

		ans := solve4(a)

		for i := 0; i < len(ans); i++ {
			fmt.Print(ans[i])
			fmt.Print(" ")
		}

		fmt.Println()
	}
}

func solve4(a int) []int {
	counter := 1
	arr := make([]int, a + 1)

	var queue [][]int

	queue = append(queue, []int {1, a})

	for ;len(queue) > 0; {

		item := queue[0]

		queue = queue[1 : ]

		process(item, &counter, &arr, &queue)
	}

	var result []int

	for i := 1; i < len(arr); i++ {
		result = append(result, arr[i])
	}

	return result
}

func process(item []int, counter *int, arr *[]int, queue *[][]int)  {
	a := item[0]
	b := item[1]

	if a == b {
		(*arr)[a] = *counter

		*counter ++

		return
	} else if a > b {
		return
	}

	var mid int

	if (b - a + 1) % 2 == 1 {
		mid = (b + a)/2
	} else {
		mid = (b + a - 1)/2
	}

	(*arr)[mid] = *counter

	*counter ++

	if b - mid > mid - a {
		*queue = append(*queue, []int {mid + 1, b})
		*queue = append(*queue, []int {a, mid - 1})

	} else {
		*queue = append(*queue, []int {a, mid - 1})
		*queue = append(*queue, []int {mid + 1, b})
	}
}

package main

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

type segment struct {
	l, r, len int
}

func newSegment(l, r int) *segment {
	len := r - l + 1
	if len > 0 {
		return &segment{l, r, len}
	}
	return nil
}

type PriorityQueue []*segment

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].len > pq[j].len || (pq[i].len == pq[j].len && pq[i].l < pq[i].l)
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriorityQueue) Push(x interface{}) {
	s := x.(*segment)
	*pq = append(*pq, s)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	s := old[n-1]
	old[n-1] = nil
	*pq = old[0 : n-1]
	return s
}

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

	var t int
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		var n int
		fmt.Fscan(reader, &n)
		var pq PriorityQueue
		heap.Init(&pq)
		heap.Push(&pq, newSegment(1, n))

		ans := make([]int, n)
		cnt := 1
		for pq.Len() > 0 {
			e := heap.Pop(&pq)
			seg := e.(*segment)
			var idx int
			if (seg.r-seg.l+1)%2 == 1 {
				idx = (seg.l + seg.r) / 2
			} else {
				idx = (seg.l + seg.r - 1) / 2
			}
			if l := newSegment(seg.l, idx-1); l != nil {
				heap.Push(&pq, l)
			}
			if r := newSegment(idx+1, seg.r); r != nil {
				heap.Push(&pq, r)
			}
			ans[idx-1] = cnt
			cnt++
		}
		fmt.Fprintln(writer, strings.Trim(fmt.Sprint(ans), "[]"))
	}
}


Alice and Bob are playing a game. They have an array of positive integers $$$a$$$ of size $$$n$$$.Before starting the game, Alice chooses an integer $$$k \ge 0$$$. The game lasts for $$$k$$$ stages, the stages are numbered from $$$1$$$ to $$$k$$$. During the $$$i$$$-th stage, Alice must remove an element from the array that is less than or equal to $$$k - i + 1$$$. After that, if the array is not empty, Bob must add $$$k - i + 1$$$ to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the $$$k$$$-th stage ends and Alice hasn't lost yet, she wins.Your task is to determine the maximum value of $$$k$$$ such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible.

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 a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$).

For each test case, print one integer — the maximum value of $$$k$$$ such that Alice can win if both players play optimally.

package main

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

var (
	t, n int
	a, b []int
)

func check(k int) bool {
	step := 0
	copy(b, a)

	for i := 0; i < n; i++ {
		if b[i] <= k-step {
			for j := n - 1; j > i; j-- {
				b[j-step] += k - step
				break
			}
			step++
		}
	}

	if step < k {
		return false
	}
	return true
}

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n)
		a = make([]int, n)
		b = make([]int, n)
		for i := 0; i < n; i++ {
			scan(&a[i])
		}
		sort.Slice(a, func(i, j int) bool {
			return a[i] > a[j]
		})
		l, r := 0, n
		for l < r {
			mid := (l + r + 1) / 2
			if check(mid) {
				l = mid
			} else {
				r = mid - 1
			}
		}
		println(l)
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var bytes []byte
var l, max int

func fastScan() int {
	b := bytes[l]

	// Check if the bytes is not a number
	for b < 48 || b > 57 {
		l++
		b = bytes[l]
	}

	result := 0
	for 47 < b && b < 58 {
		result = (result << 3) + (result << 1) + int(b-48)

		l++
		if l > max {
			return result
		}
		b = bytes[l]
	}
	return result
}

func main() {
	// fmt.Println("hello")
	bytes, _ = ioutil.ReadAll(bufio.NewReader(os.Stdin))
	max = len(bytes) - 1

	// ws := bufio.NewWriter(os.Stdout)
	t := fastScan()

	for i := 0; i < t; i++ {
		lst := []int{}
		n := fastScan()
		var x int
		for ele := 0; ele < n; ele++ {
			x = fastScan()
			lst = append(lst, x)
		}
		sort.Ints(lst)
		s := 0
		e := n
		ans := 0
		for s <= e {
			mid := (s + e) / 2
			if possible(mid, lst) {
				ans = mid
				s = mid + 1
			} else {
				e = mid - 1
			}
		}

		fmt.Println(ans)

	}

	// ws.Flush()

}

func possible(k int, lst []int) bool {
	f := 0
	l := len(lst) - 1
	for s := 1; s < k+1; s++ {
		temp := (k - s + 1)
		for l >= f {
			if lst[l] <= temp {
				break
			}
			l--
		}
		if l < f {
			return false
		}
		l--
		if l >= f {
			f += 1
		}
	}
	return true
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n int
		fmt.Fscan(r, &n)
		a := make([]int, n+1)

		for i := 0; i < n; i++ {
			var temp int
			fmt.Fscan(r, &temp)
			a[temp]++
		}

		var k int
		for i := 1; i <= n; i++ {
			pos := true
			act := 0
			ref := 0

			for j := 1; j <= i; j++ {
				if j == 1 {
					ref += i + 1 - j
				} else {
					ref++
				}
				act += a[j]
				if act < ref { pos = false }
			}

			if !pos { break }
			k = i
		}

		fmt.Fprintln(w, k)
	}

}

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 debug(a ...interface{}) {
	for _, e := range a {
		printf("%v ", e)
	}
	printf("\n")
	writer.Flush()
}

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

	// debug("n", n)
	// debug("a", a)

	var res int = 0
	beg, fin := 1, n
	for beg <= fin {
		k := (beg + fin) / 2
		// debug("k", k)
		cnt := make([]int, 2*n+10)
		for i:=0; i<n; i++ {
			cnt[a[i]]++
		}
		aliceWins := true
		origK := k
		for k > 0 {
			num := k
			for num >= 1 {
				if cnt[num] > 0 {
					break
				}
				num--
			}
			if num == 0 {
				aliceWins = false
				break
			}
			cnt[num]--

			for incNum:=1; incNum<=k; incNum++ {
				if cnt[incNum] > 0 {
					cnt[incNum]--
					cnt[incNum + k]++
					break
				}
			}

			k--
		}

		if aliceWins {
			res = origK
			beg = origK + 1
			continue
		}
		fin = origK - 1
	}
	printf("%d\n", res)
}

func main() {
	defer writer.Flush()

	var T int
	scanf("%d\n", &T)
	for tt:=1; tt<=T; tt++ {
		solve()
	}
}

package main

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

var (
	t, n int
	a, b []int
)

func check(k int) bool {
	step := 0
	copy(b, a)

	for i := 0; i < n; i++ {
		if b[i] <= k-step {
			for j := i + 1; j < n; j++ {
				if b[j] <= k-step-1 {
					b[j] += k - step
					break
				}
			}
			step++
		}
	}
	if step < k {
		return false
	}
	return true
}

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n)
		a = make([]int, n)
		b = make([]int, n)
		for i := 0; i < n; i++ {
			scan(&a[i])
		}
		sort.Slice(a, func(i, j int) bool {
			return a[i] > a[j]
		})
		l, r := 0, n
		for l < r {
			mid := (l + r + 1) / 2
			if check(mid) {
				l = mid
			} else {
				r = mid - 1
			}
		}
		println(l)
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var (
	t, n int
	a, b []int
)

func check(k int) bool {
	step := 1
	flag := true
	copy(b, a)

	for i := 0; i < n; i++ {
		if b[i] <= k-step+1 {
			flag = false
			for j := i + 1; j < n; j++ {
				if b[j] < k-step {
					b[j] += k - step + 1
					break
				}
			}
			step++
		}
	}
	if flag || step < k {
		return false
	}
	return true
}

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n)
		a = make([]int, n)
		b = make([]int, n)
		for i := 0; i < n; i++ {
			scan(&a[i])
		}
		sort.Slice(a, func(i, j int) bool {
			return a[i] > a[j]
		})
		l, r := 0, n
		for l < r {
			mid := (l + r + 1) / 2
			if check(mid) {
				l = mid
			} else {
				r = mid - 1
			}
		}
		println(l)
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var (
	t, n int
	a, b []int
)

func check(k int) bool {
	step := 1
	flag := true
	copy(b, a)
	for i := 0; i < n; i++ {
		if b[i] <= k-step+1 {
			flag = false
			for j := i + 1; j < n; j++ {
				if b[j] < k-step {
					b[j] += k - step + 1
				}
			}
			step++
		}
	}
	if flag || step < k {
		return false
	}
	return true
}

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n)
		a = make([]int, n)
		b = make([]int, n)
		for i := 0; i < n; i++ {
			scan(&a[i])
		}
		sort.Slice(a, func(i, j int) bool {
			return a[i] > a[j]
		})
		l, r := 0, n
		for l < r {
			mid := (l + r + 1) / 2
			if check(mid) {
				l = mid
			} else {
				r = mid - 1
			}
		}
		println(l)
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var (
	t, n int
	a    []int
)

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n)
		a = make([]int, n+1)
		for i := 1; i <= n; i++ {
			scan(&a[i])
		}
		sort.Slice(a, func(i, j int) bool {
			return a[i] <= a[j]
		})
		cnt := 0
		for i := 1; i <= n; i++ {
			if a[i] != a[i-1] && cnt+1 >= a[i] {
				cnt++
			}
		}
		println(cnt)
	}
}

//

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	r = bufio.NewReader(os.Stdin)
	w = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(r, a...)
}

func println(a ...any) {
	fmt.Fprintln(w, a...)
}

func flush() {
	w.Flush()
}

package main

import "fmt"

func main() {
	fmt.Println("hello world")
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n int
		fmt.Fscan(r, &n)
		a := make([]int, n+1)

		for i := 0; i < n; i++ {
			var temp int
			fmt.Fscan(r, &temp)
			a[temp]++
		}

		var k int
		for i := 1; i <= n; i++ {
			pos := true
			act := 0

			for j := 1; j <= i; j++ {
				ref := i + 1 -j
				act += a[j]
				if act < ref { pos = false }
			}

			if !pos { break }
			k = i
		}

		fmt.Fprintln(w, k)
	}

}


Petya got an array $$$a$$$ of numbers from $$$1$$$ to $$$n$$$, where $$$a[i]=i$$$.He performed $$$n$$$ operations sequentially. In the end, he received a new state of the $$$a$$$ array.At the $$$i$$$-th operation, Petya chose the first $$$i$$$ elements of the array and cyclically shifted them to the right an arbitrary number of times (elements with indexes $$$i+1$$$ and more remain in their places). One cyclic shift to the right is such a transformation that the array $$$a=[a_1, a_2, \dots, a_n]$$$ becomes equal to the array $$$a = [a_i, a_1, a_2, \dots, a_{i-2}, a_{i-1}, a_{i+1}, a_{i+2}, \dots, a_n]$$$.For example, if $$$a = [5,4,2,1,3]$$$ and $$$i=3$$$ (that is, this is the third operation), then as a result of this operation, he could get any of these three arrays:  $$$a = [5,4,2,1,3]$$$ (makes $$$0$$$ cyclic shifts, or any number that is divisible by $$$3$$$);  $$$a = [2,5,4,1,3]$$$ (makes $$$1$$$ cyclic shift, or any number that has a remainder of $$$1$$$ when divided by $$$3$$$);  $$$a = [4,2,5,1,3]$$$ (makes $$$2$$$ cyclic shifts, or any number that has a remainder of $$$2$$$ when divided by $$$3$$$). Let's look at an example. Let $$$n=6$$$, i.e. initially $$$a=[1,2,3,4,5,6]$$$. A possible scenario is described below.  $$$i=1$$$: no matter how many cyclic shifts Petya makes, the array $$$a$$$ does not change.  $$$i=2$$$: let's say Petya decided to make a $$$1$$$ cyclic shift, then the array will look like $$$a = [\textbf{2}, \textbf{1}, 3, 4, 5, 6]$$$.  $$$i=3$$$: let's say Petya decided to make $$$1$$$ cyclic shift, then the array will look like $$$a = [\textbf{3}, \textbf{2}, \textbf{1}, 4, 5, 6]$$$.  $$$i=4$$$: let's say Petya decided to make $$$2$$$ cyclic shifts, the original array will look like $$$a = [\textbf{1}, \textbf{4}, \textbf{3}, \textbf{2}, 5, 6]$$$.  $$$i=5$$$: let's say Petya decided to make $$$0$$$ cyclic shifts, then the array won't change.  $$$i=6$$$: let's say Petya decided to make $$$4$$$ cyclic shifts, the array will look like $$$a = [\textbf{3}, \textbf{2}, \textbf{5}, \textbf{6}, \textbf{1}, \textbf{4}]$$$. You are given a final array state $$$a$$$ after all $$$n$$$ operations. Determine if there is a way to perform the operation that produces this result. In this case, if an answer exists, print the numbers of cyclical shifts that occurred during each of the $$$n$$$ operations.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of the description of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2\cdot10^3$$$) — the length of the array $$$a$$$. The next line contains the final state of the array $$$a$$$: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) are written. All $$$a_i$$$ are distinct. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2\cdot10^3$$$.

For each test case, print the answer on a separate line. Print -1 if the given final value $$$a$$$ cannot be obtained by performing an arbitrary number of cyclic shifts on each operation. Otherwise, print $$$n$$$ non-negative integers $$$d_1, d_2, \dots, d_n$$$ ($$$d_i \ge 0$$$), where $$$d_i$$$ means that during the $$$i$$$-th operation the first $$$i$$$ elements of the array were cyclic shifted to the right $$$d_i$$$ times. If there are several possible answers, print the one where the total number of shifts is minimal (that is, the sum of $$$d_i$$$ values is the smallest). If there are several such answers, print any of them.

NoteThe first test case matches the example from the statement.The second set of input data is simple. Note that the answer $$$[3, 2, 1]$$$ also gives the same permutation, but since the total number of shifts $$$3+2+1$$$ is greater than $$$0+0+1$$$, this answer is not correct.

package main

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

func check(b bool) {
	if !b {
		_, _, line, _ := runtime.Caller(1)
		fmt.Printf("check failed line %d\n", line)
		os.Exit(-1)
	}
}

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

const (
	INIT = -1
)

var (
	a []int
)

// [l,r)
func reverse(l, r int) {
	r--
	for l < r {
		a[l] = a[l] ^ a[r]
		a[r] = a[l] ^ a[r]
		a[l] = a[l] ^ a[r]

		l++
		r--
	}
}

// [l,r)
func rotate(r, n int) {
	reverse(0, r)
	reverse(r, n)
	reverse(0, n)
}

func solve(n int) []int {
	ans := []int{}
	for i := n - 1; i >= 0; i-- {
		// fmt.Printf("i %d a %v\n", i, a)

		want := i + 1
		if a[i] == want {
			ans = append(ans, 0)
			continue
		}
		pos := INIT
		for j := 0; j < i; j++ {
			if a[j] == want {
				pos = j
				break
			}
		}
		check(pos != INIT)
		rotate(pos+1, i+1)
		ans = append(ans, pos+1)
	}
	return ans
}

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

	var tc int
	fmt.Fscan(r, &tc)

	for ; tc > 0; tc-- {
		var n int
		fmt.Fscan(r, &n)
		a = make([]int, n)

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

		ans := solve(n)
		for i := n - 1; i >= 0; i-- {
			fmt.Fprintf(w, "%d ", ans[i])
		}
		fmt.Fprintln(w)

	}
}

package main

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

func check(b bool) {
	if !b {
		_, _, line, _ := runtime.Caller(1)
		fmt.Printf("check failed line %d\n", line)
		os.Exit(-1)
	}
}

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

const (
	INIT = -1
)

var (
	a []int
)

// [l,r)
func reverse(l, r int) {
	r--
	for l < r {
		a[l] = a[l] ^ a[r]
		a[r] = a[l] ^ a[r]
		a[l] = a[l] ^ a[r]

		l++
		r--
	}
}

// [l,r)
func rotate(r, n int) {
	reverse(0, r)
	reverse(r, n)
	reverse(0, n)
}

func solve(n int) {
	ans := []int{}
	for i := n - 1; i >= 0; i-- {
		// fmt.Printf("i %d a %v\n", i, a)

		want := i + 1
		if a[i] == want {
			ans = append(ans, 0)
			continue
		}
		pos := INIT
		for j := 0; j < i; j++ {
			if a[j] == want {
				pos = j
				break
			}
		}
		check(pos != INIT)
		rotate(pos+1, i+1)
		ans = append(ans, pos+1)
	}

	for i := n - 1; i >= 0; i-- {
		fmt.Printf("%d ", ans[i])
	}
	fmt.Println()
}

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

	var tc int
	fmt.Fscan(r, &tc)

	for ; tc > 0; tc-- {
		var n int
		fmt.Fscan(r, &n)
		a = make([]int, n)

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

		solve(n)

	}
}

package main

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

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

func main() {
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		var n int
		fmt.Fscan(in, &n)
		arr := make([]int, n+1)
		mmid := make(map[int]int)
		for i := 1; i <= n; i++ {
			fmt.Fscan(in, &arr[i])
			mmid[arr[i]] = i
		}
		ans := make([]int, n+1)
		for i := n; i >= 1; i-- {

			ans[i] = (mmid[i]) % i
			for j := 1; j <= n; j++ {
				mmid[j] -= (mmid[i]) % i
				if mmid[j] < 1 {
					mmid[j] += i
				}
			}
		}
		for i := 1; i <= n; i++ {
			fmt.Fprintf(out, "%d ", ans[i])
		}
		fmt.Fprintln(out)
	}
}

package main

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

func CF1650DFindTarget(a []int, t int) int {
	for i := 0; i < len(a); i++ {
		if a[i] == t {
			return i
		}
	}
	return -1
}

func solveCF1650DCase(in io.Reader, out io.Writer) {
	var n int
	fmt.Fscan(in, &n)

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

	countCache := make([]int, n)
	for i := 0; i < n; i++ {
		target := n - i
		idx := CF1650DFindTarget(a, target)
		numRotated := (idx + 1) % target
		countCache[n-1-i] = numRotated
		a = append(a[numRotated:(n-i)], a[:numRotated]...)
	}

	for i := 0; i < len(countCache); i++ {
		fmt.Fprintf(out, "%d ", countCache[i])
	}
	fmt.Fprintln(out)
}

func CF1650D(rawIn io.Reader, rawOut io.Writer) {
	in := bufio.NewReader(rawIn)
	out := bufio.NewWriter(rawOut)
	defer out.Flush()

	var cases int
	fmt.Fscan(in, &cases)
	for cc := 0; cc < cases; cc++ {
		solveCF1650DCase(in, out)
	}
}

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

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 0
	_, _ = fmt.Fscan(in, &t)
	for ii := 0; ii < t; ii++ {
		var n int
		_, _ = fmt.Fscan(in, &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &a[i])
		}
		ans := make([]int, n)
		for i := n; i > 0; i-- {
			for j, num := range a {
				if num == i {
					ans[i-1] = (j + 1) % i
					a = append(a[j+1:], a[:j]...)
					break
				}
			}
			//fmt.Println(a, ans)
		}
		//fmt.Fprintln(out, ans)
		for i := 0; i < n; i++ {
			fmt.Fprint(out, ans[i])
			if i < n-1 {
				fmt.Fprint(out, " ")
			} else {
				fmt.Fprintln(out)
			}
		}
	}
}

//  1 2 3 4 5 6
//0 1 1 2 0 4
//1 2 3 4 5 6

package main

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

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

	var t, n int
	_arr := make([]int, 2e3+10)
	ans := make([]int, 2e3+10)
	for Fscan(in, &t); t > 0; t-- {
		ans = ans[:0]
		Fscan(in, &n)
		for i := 0; i < n; i++ {
			Fscan(in, &_arr[i])
		}
		arr := _arr[:n]
		for next := n; next > 1; next-- {
			var idx int
			for idx = 0; idx < next; idx++ {
				if arr[idx] == next {
					break
				}
			}
			ans = append(ans, (idx+1)%next)
			ri := next - idx - 1
			if ri == 0 {
				continue
			}
			temp := make([]int, next)
			for i := 0; i < next; i++ {
				temp[(i+ri)%next] = arr[i]
			}
			arr = temp
		}
		Fprint(out, 0, " ")
		for i := len(ans) - 1; i > 0; i-- {
			Fprint(out, ans[i], " ")
		}
		Fprint(out, ans[0], "\n")
	}
}

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

package main
import ."fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	T,n:=0,0
	for Scan(&T); T > 0; T-- {
		Scan(&n)
		a := make([]int, n)
		for i := range a {Scan(&a[i])}
		d := make([]interface{}, n)
		for i := n; i > 0; i-- {
			for j, v := range a {
				if v == i {
					d[i-1] = (j + 1) % i
					a = append(a[j+1:], a[:j]...)
					break
				}
			}
		}
		Println(d...)
	}
}

package main

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

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

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

	c := 0
	fmt.Fscan(in, &c)
	for ; c > 0; c-- {
		n := 0
		fmt.Fscan(in, &n)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &arr[i])
		}
		res := make([]int, n)
		for i := n - 1; i >= 0; i-- {
			for arr[i] != i+1 {
				t := arr[0]
				last := arr[i]
				for j := i - 1; j >= 0; j-- {
					tmp := arr[j]
					arr[j] = last
					last = tmp
				}
				arr[i] = t
				res[i]++
			}
		}
		for _, v := range res {
			fmt.Fprint(out, v, " ")
		}
		out.Flush()
		fmt.Println()
	}
}

package main

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

/*

 */

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n int
	scanf("%d\n", &n)

	a := make([]int, n)

	for i := range a {
		scanf("%d", &a[i])
	}
	scanf("\n")

	shift := func(a []int, cnt int) {
		b := make([]int, len(a))

		for i, num := range a {
			j := i - cnt
			if j < 0 {
				j += len(a)
			}

			b[j] = num
		}

		for i, num := range b {
			a[i] = num
		}
	}

	ans := make([]int, 0)

	for i := n - 1; i >= 0; i-- {
		j := 0
		for ; j <= i; j++ {
			if a[j] == i+1 {
				break
			}
		}

		cnt := j + 1

		shift(a[:i+1], cnt)

		ans = append(ans, cnt%(i+1))
	}

	for i := len(ans) - 1; i >= 0; i-- {
		fmt.Fprintf(writer, "%d ", ans[i])
	}
	fmt.Fprintln(writer)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

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

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int) int {
	quot := num / div
	if num%div != 0 {
		quot++
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	minimum := nums[0]
	for _, num := range nums {
		if num < minimum {
			minimum = num
		}
	}
	return minimum
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	idx := 0
	for i, num := range nums {
		if num > nums[idx] {
			idx = i
		}
	}

	return nums[idx]
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

package main

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

func solve(cin *scanner, cout *writer, cerr *writer) {
	n := cin.NextInt()
	a := cin.NextInts(n)
	ans := make([]int, n)
	for i := n - 1; i >= 0; i-- {
		var xidx int
		for j := 0; j < i+1; j++ {
			if a[j] == i+1 {
				xidx = j
				break
			}
		}
		ans[i] = (xidx + 1) % (i + 1)
		a = append(a[xidx+1:i+1], a[:xidx+1]...)
	}
	for i := range ans {
		cout.Print(ans[i])
		if i < n-1 {
			cout.Print(" ")
		}
	}
	cout.Println()
}

func main() {
	cin := NewScanner(os.Stdin)
	cout, cerr := NewWriter(os.Stdout), NewWriter(os.Stderr)
	defer cout.Flush()
	defer cerr.Flush()
	t := cin.NextInt()
	// t := 1
	for ti := 0; ti < t; ti++ {
		solve(cin, cout, cerr)
	}
}

// Template Bolierplate {{{
type scanner struct {
	*bufio.Scanner
}

func NewScanner(r io.Reader) *scanner {
	s := bufio.NewScanner(r)
	s.Split(bufio.ScanWords)
	s.Buffer(nil, 1024*1024)
	return &scanner{s}
}

func (i *scanner) Next() string {
	i.Scan()
	return i.Text()
}

func (i *scanner) Nexts(n int) []string {
	res := make([]string, n)
	for j := range res {
		res[j] = i.Next()
	}
	return res
}

func (i *scanner) NextInt() int {
	v, _ := strconv.Atoi(i.Next())
	return v
}

func (i *scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(i.Next(), 10, 64)
	return v
}

func (i *scanner) NextInts(n int) []int {
	res := make([]int, n)
	for j := range res {
		res[j] = i.NextInt()
	}
	return res
}

func (i *scanner) NextInt64s(n int) []int64 {
	res := make([]int64, n)
	for j := range res {
		res[j] = i.NextInt64()
	}
	return res
}

type writer struct {
	w *bufio.Writer
}

func NewWriter(w io.Writer) *writer {
	return &writer{bufio.NewWriter(w)}
}

func (i *writer) Print(a ...interface{}) {
	fmt.Fprint(i.w, a...)
}

func (i *writer) Println(a ...interface{}) {
	fmt.Fprintln(i.w, a...)
}

func (i *writer) Printf(format string, a ...interface{}) {
	fmt.Fprintf(i.w, format, a...)
}

func (i *writer) Flush() {
	i.w.Flush()
}

// }}}

// vim: fdm=marker


Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.

The first line of the input contains a single integer l (1 ≤ l ≤ 1 000) — the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≤ p, q ≤ 500) — the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.

Print a single real number — the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4.  Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .

NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor.

package main

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

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

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

	l, p, q := nextFloat(), nextFloat(), nextFloat()

	println(l / (p + q) * p)
}

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

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

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

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

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

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

package main

import (
    "fmt"
    )

func main() {
    var l, p, q int
    fmt.Scan(&l, &p, &q)

    fmt.Println(float32(l * p) / float32(p+q))
}


You are given a string $$$s$$$ consisting of $$$n$$$ characters. Each character of $$$s$$$ is either 0 or 1.A substring of $$$s$$$ is a contiguous subsequence of its characters.You have to choose two substrings of $$$s$$$ (possibly intersecting, possibly the same, possibly non-intersecting — just any two substrings). After choosing them, you calculate the value of the chosen pair of substrings as follows:  let $$$s_1$$$ be the first substring, $$$s_2$$$ be the second chosen substring, and $$$f(s_i)$$$ be the integer such that $$$s_i$$$ is its binary representation (for example, if $$$s_i$$$ is 11010, $$$f(s_i) = 26$$$);  the value is the bitwise OR of $$$f(s_1)$$$ and $$$f(s_2)$$$. Calculate the maximum possible value you can get, and print it in binary representation without leading zeroes.

The first line contains one integer $$$n$$$ — the number of characters in $$$s$$$. The second line contains $$$s$$$ itself, consisting of exactly $$$n$$$ characters 0 and/or 1. All non-example tests in this problem are generated randomly: every character of $$$s$$$ is chosen independently of other characters; for each character, the probability of it being 1 is exactly $$$\frac{1}{2}$$$. This problem has exactly $$$40$$$ tests. Tests from $$$1$$$ to $$$3$$$ are the examples; tests from $$$4$$$ to $$$40$$$ are generated randomly. In tests from $$$4$$$ to $$$10$$$, $$$n = 5$$$; in tests from $$$11$$$ to $$$20$$$, $$$n = 1000$$$; in tests from $$$21$$$ to $$$40$$$, $$$n = 10^6$$$.  Hacks are forbidden in this problem.

Print the maximum possible value you can get in binary representation without leading zeroes.

NoteIn the first example, you can choose the substrings 11010 and 101. $$$f(s_1) = 26$$$, $$$f(s_2) = 5$$$, their bitwise OR is $$$31$$$, and the binary representation of $$$31$$$ is 11111.In the second example, you can choose the substrings 1110010 and 11100.

package main

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

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

func max(i, j string) string {
    for k := range i {
        if i[k] != j[k] {
            if i[k] == '1' {
                return i
            } else {
                return j
            }
        }
    }
    return i
}

func main() {
    var n int
    var s string
    Fscan(in, &n, &s)

    first_one := strings.Index(s, "1")

    if first_one == -1 {
        Fprintln(out, "0")
    } else {
        a := s[first_one : n]
        ans := a

        first_zero := strings.Index(a, "0")
        for i := 0; i < first_zero; i++ {
            res := []byte(a)
            for k, j := first_zero, i; k < len(a); k++ {
                if res[k] == '0' && a[j] == '1' {
                    res[k] = '1'
                }
                j++
            }

            ans = max(string(res), ans)
        }

        Fprintln(out, ans)
    }

    out.Flush()
}

package main

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

var r *bufio.Reader
var w *bufio.Writer
func init(){
	r = bufio.NewReader(os.Stdin)
	w = bufio.NewWriter(os.Stdout)
}
func main(){
	defer w.Flush()
	var n int
	var s []byte
	fmt.Fscan(r, &n,&s)
	sn :=make([]byte, len(s))
	copy(sn, s)
	var bits big.Int
	cur:=0
	for i:=len(s)-1;i>=0;i--{
		if s[i]==49{
			bits.SetBit(&bits, cur, 1)
		}
		cur++;
	}
	var old,ans big.Int
	old.Set(&bits)
	ans.Set(&bits)
	iter:=0
	for old.Sign()!=0 && iter<1000{
		iter++
		var temp big.Int
		temp.Set(&bits)
		temp.Or(&bits, &old)
		if ans.Cmp(&temp)==-1{
			ans.Set(&temp)
		}
		old.Div(&old, big.NewInt(2))
	}
	fmt.Println(ans.Text(2))
}

package main

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

func maxl(a, b []byte) []byte {
	for i := range a {
		if a[i] < b[i] { return b }
		if b[i] < a[i] { break }
	}
	return a
}

func or(a, b []byte) []byte {
	c := make([]byte, len(a))
	i := 0

	for i < len(a) {
		ai := len(a) - 1 - i
		if i < len(b) {
			bi := len(b) - 1 - i
			c[ai] = a[ai] | b[bi]
		} else {
			c[ai] = a[ai]
		}
		i++
	}

	return c
}

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

	var n int
	var a []byte

	fmt.Fscan(r, &n, &a)
	for i := range a { a[i] -= '0' }

	var i, j int
	for i < n && a[i] == 0 { i++ }
	for j = i; j < n && a[j] == 1; j++ {}

	l := n - j

	if l > 0 {
		res := a[i:]
		for k := 0; k + l < n; k++ {
			nres := or(a[i:], a[k:k+l])
			res = maxl(res, nres)
		}

		for _, v := range res { fmt.Fprintf(w, "%d", v) }
		fmt.Fprintln(w, "")
	} else {
		fmt.Fprintln(w, "0")
	}
}

package main

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

func maxl(a, b []byte) []byte {
	for i := range a {
		if a[i] < b[i] {
			return b
		}
		if b[i] < a[i] {
			return a
		}
	}
	return a
}

func or(a, b []byte) []byte {
	c := make([]byte, len(a))
	i := 0

	for i < len(a) {
		if i < len(b) {
			c[len(a) - 1 - i] = a[len(a) - 1 - i] | b[len(b) - 1 - i]
		} else {
			c[len(a) -1 - i] = a[len(a) - 1 - i]
		}
		i++
	}

	return c
}

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

	var n int
	var a []byte

	fmt.Fscan(r, &n, &a)
	for i := range a { a[i] -= '0' }

	var i, j int
	for i < n && a[i] == 0 { i++ }
	for j = i; j < n && a[j] == 1; j++ {}

	l := n - j

	if l > 0 {
		res := a[i:]
		// fmt.Fprintf(w, "1 &&& i:%d j:%d l:%d\n", i, j, l)
		// fmt.Fprintln(w, "1 &&& res: ", res)
		for k := 0; k + l < n; k++ {
			nres := or(a[i:], a[k:k+l])
			res = maxl(res, nres)
			// fmt.Fprintln(w, "2 &&& cmp: ", a[k:k+l])
			// fmt.Fprintln(w, "2 &&& nres: ", nres)
			// fmt.Fprintln(w, "2 &&& res: ", res)
		}

		for _, v := range res { fmt.Fprintf(w, "%d", v) }
		fmt.Fprintln(w, "")
	} else {
		fmt.Fprintln(w, "0")
	}
}

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

type BestAns struct {
	withLid    int64
	withoutLid int64
}

var MOD int64 = 1000*1000*1000 + 7

func reverse(a []bool) []bool {
	res := make([]bool, len(a), len(a))
	for i := 0; i < len(a); i++ {
		res[len(a)-i-1] = a[i]
	}
	return res
}

func or(a, b []bool) []bool {
	if len(a) < len(b) {
		a, b = b, a
	}

	a = reverse(a)
	b = reverse(b)

	ans := make([]bool, len(a), len(a))

	for i := 0; i < len(a); i++ {
		if i >= len(b) {
			ans[i] = a[i]
		} else {
			ans[i] = a[i] || b[i]
		}
	}
	return reverse(ans)
}

func sor(a, b string) string {

	na := make([]bool, len(a), len(a))
	nb := make([]bool, len(b), len(b))

	for i := 0; i < len(a); i++ {
		if a[i] == '1' {
			na[i] = true
		}
	}

	for i := 0; i < len(b); i++ {
		if b[i] == '1' {
			nb[i] = true
		}
	}

	orres := or(na, nb)

	ans := make([]rune, len(orres), len(orres))

	for i := 0; i < len(orres); i++ {
		if orres[i] {
			ans[i] = '1'
		} else {
			ans[i] = '0'
		}
	}

	return string(ans)
}

func main() {
	defer writer.Flush()

	var n int
	var s string

	scanf("%d\n", &n)
	scanf("%s\n", &s)

	firstOneIndex := n

	for i := 0; i < n; i++ {
		if s[i] == '1' {
			firstOneIndex = i
			break
		}
	}
	if firstOneIndex == n {
		printf("%s\n", "0")
		return
	}

	firstInterval := s[firstOneIndex:]

	cur := firstOneIndex
	for s[cur] == '1' {
		cur++
	}

	ans := firstInterval
	for i := firstOneIndex; i < cur; i++ {
		if s[i] == '0' {
			break
		}
		secondInterval := s[i : i+n-cur]
		candidate := sor(firstInterval, secondInterval)
		if candidate > ans {
			ans = candidate
		}
	}

	first := 0
	for ans[first] == '0' {
		first++
	}
	printf("%s\n", ans[first:])
}

package main

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

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 debug(a ...interface{}) {
	for _, e := range a {
		printf("%v ", e)
	}
	printf("\n")
	writer.Flush()
}

func solve() {
	var n int
	scanf("%d\n", &n)
	var s string
	scanf("%s", &s)

	var res, newS, first, second strings.Builder
	i := 0
	for i < n {
		if s[i] == '1' {
			break
		}
		i++
	}

	for i < n {
		newS.WriteRune(rune(s[i]))
		i++
	}

	if newS.Len() == 0 {
		printf("0")
		return
	}

	i = 0
	for i < newS.Len() {
		if newS.String()[i] == '0' {
			break
		}
		first.WriteRune(rune(newS.String()[i]))
		i++
	}

	j := i
	for j < newS.Len() {
		second.WriteRune(rune(newS.String()[j]))
		j++
	}

	if second.Len() == 0 {
		printf("%s", first.String())
		return
	}

	rem := second.Len()
	res = second
	for j:=0; j<i; j++ {
		var newSecond strings.Builder
		for k:=0; k<rem; k++ {
			if second.String()[k] == '1' {
				newSecond.WriteRune(rune('1'))
				continue
			}
			newSecond.WriteRune(rune(newS.String()[j+k]))
		}
		if strings.Compare(newSecond.String(), res.String()) == 1 {
			res = newSecond
		}
	}

	first.WriteString(res.String())
	printf("%s", first.String())
}

func main() {
	defer writer.Flush()

	solve()
}

package main

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

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

func max(i, j string) string {
    for k := range i {
        if i[k] != j[k] {
            if i[k] == '1' {
                return i
            } else {
                return j
            }
        }
    }
    return i
}

func main() {
    var n int
    var s string
    Fscan(in, &n, &s)

    first_one := strings.Index(s, "1")

    if first_one == -1 {
        Fprintln(out, "0")
    } else {
        a := s[first_one : n]
        ans := a

        first_zero := strings.Index(a, "0")
        for i := 0; i < first_zero; i++ {
            res := []byte(a)
            for k, j := first_zero, 0; k < len(a); k++ {
                if res[k] == '0' && a[j] == '1' {
                    res[k] = '1'
                }
                j++
            }

            ans = max(string(res), ans)
        }

        Fprintln(out, ans)
    }

    out.Flush()
}

package main

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

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

func max(i, j string) string {
    for k := range i {
        if i[k] != j[k] {
            if i[k] == '1' {
                return i
            } else {
                return j
            }
        }
    }
    return i
}

func main() {
    var n int
    var s string
    Fscan(in, &n, &s)

    first_one := strings.Index(s, "1")

    if first_one == -1 {
        Fprintln(out, "0")
    } else {
        a := s[first_one : n]
        ans := a

        first_zero := strings.Index(a, "0")
        for i := 0; i < first_zero; i++ {
            res := []byte(a)
            for k, j := i, 0; k < len(a); k++ {
                if res[k] == '0' && a[j] == '1' {
                    res[k] = '1'
                }
                j++
            }

            ans = max(string(res), ans)
        }

        Fprintln(out, ans)
    }

    out.Flush()
}

package main

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

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

type BestAns struct {
	withLid    int64
	withoutLid int64
}

var MOD int64 = 1000*1000*1000 + 7

func reverse(a []bool) []bool {
	res := make([]bool, len(a), len(a))
	for i := 0; i < len(a); i++ {
		res[len(a)-i-1] = a[i]
	}
	return res
}

func or(a, b []bool) []bool {
	if len(a) < len(b) {
		a, b = b, a
	}

	a = reverse(a)
	b = reverse(b)

	ans := make([]bool, len(a), len(a))

	for i := 0; i < len(a); i++ {
		if i >= len(b) {
			ans[i] = a[i]
		} else {
			ans[i] = a[i] || b[i]
		}
	}
	return reverse(ans)
}

func sor(a, b string) string {

	na := make([]bool, len(a), len(a))
	nb := make([]bool, len(b), len(b))

	for i := 0; i < len(a); i++ {
		if a[i] == '1' {
			na[i] = true
		}
	}

	for i := 0; i < len(b); i++ {
		if b[i] == '1' {
			nb[i] = true
		}
	}

	orres := or(na, nb)

	ans := make([]rune, len(orres), len(orres))

	for i := 0; i < len(orres); i++ {
		if orres[i] {
			ans[i] = '1'
		} else {
			ans[i] = '0'
		}
	}

	return string(ans)
}

func main() {
	defer writer.Flush()

	var n int
	var s string

	scanf("%d\n", &n)
	scanf("%s\n", &s)

	firstOneIndex := n

	for i := 0; i < n; i++ {
		if s[i] == '1' {
			firstOneIndex = i
			break
		}
	}
	if firstOneIndex == n {
		printf("%s\n", strings.Repeat("0", n))
		return
	}

	firstInterval := s[firstOneIndex:]

	cur := firstOneIndex
	for s[cur] == '1' {
		cur++
	}

	ans := firstInterval
	for i := firstOneIndex; i < cur; i++ {
		if s[i] == '0' {
			break
		}
		secondInterval := s[i : i+n-cur]
		candidate := sor(firstInterval, secondInterval)
		if candidate > ans {
			ans = candidate
		}
	}
	printf("%s\n", ans)
}