An array $$$a_1, a_2, \ldots, a_n$$$ is good if and only if for every subsegment $$$1 \leq l \leq r \leq n$$$, the following holds: $$$a_l + a_{l + 1} + \ldots + a_r = \frac{1}{2}(a_l + a_r) \cdot (r - l + 1)$$$. You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. Each of the next $$$t$$$ lines contains the description of a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 70$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$): the initial array.

For each test case, print one integer: the minimum number of elements that you need to replace to make the given array good.

NoteIn the first test case, the array is good already.In the second test case, one of the possible good arrays is $$$[1, 1, \underline{1}, \underline{1}]$$$ (replaced elements are underlined).In the third test case, the array is good already.In the fourth test case, one of the possible good arrays is $$$[\underline{-2.5}, -2, \underline{-1.5}, -1, \underline{-0.5}, 0]$$$.

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(reader, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
// 	redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	var a = make([]int, n)
	for i := range a {
		scan(&a[i])
	}
	if n <= 2 {
		printf("0\n")
		return
	}
	var (
		kx, kdx, k int
		res, ans   = 0, n
		check      = func() {
			res = 0
			for i := range a {
				if k*a[i] != kx+i*kdx {
					res++
				}
			}
			if ans > res {
				ans = res
			}
		}
	)
	for i1 := 0; i1 < len(a); i1++ {
		for i2 := i1 + 1; i2 < len(a); i2++ {
			k = i2 - i1
			kdx = a[i2] - a[i1]
			kx = k*a[i1] - i1*kdx
			check()
		}
	}
	printf("%v\n", ans)
}

package main

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

var arr [75]float64

const float64EqualityThreshold = 1e-9

func almostEqual(a, b float64) bool {
	return math.Abs(a-b) <= float64EqualityThreshold
}

func main() {
	//file, _ := os.Open("input.txt")
	//in := bufio.NewReader(file)
	in := bufio.NewReader(os.Stdin)

	input1 := readArrInt(in)
	t := input1[0]
	for ; t != 0; t-- {
		input := readArrInt(in)
		n := input[0]
		readArrFloat(in)
		if n <= 2 {
			fmt.Println(0)
			continue
		}
		ans := n + 2
		for i := 0; i < n; i++ {
			for j := i + 1; j < n; j++ {
				step := (arr[j] - arr[i]) / float64(j-i)
				cur := arr[i] - step*float64(i)
				curAns := 0
				for z := 0; z < n; z++ {
					if !almostEqual(arr[z], cur) {
						curAns++
					}
					cur += step
					if curAns >= ans {
						break
					}
				}
				/* if curAns < ans {
					fmt.Println(i, " ", j)
					fmt.Println(step)
				} */
				ans = min(ans, curAns)
			}
		}
		fmt.Println(ans)
	}
}

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

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

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

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

func readFloat(in *bufio.Reader) float64 {
	nStr := readStr(in)
	n, _ := strconv.ParseFloat(nStr, 64)
	return n
}

func readInt(in *bufio.Reader) int {
	nStr := readStr(in)
	n, _ := strconv.Atoi(nStr)
	return n
}

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

func readLineNumbs(in *bufio.Reader) []string {
	line := readStr(in)
	numbs := strings.Split(line, " ")
	return numbs
}

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

func readArrFloat(in *bufio.Reader) {
	numbs := readLineNumbs(in)
	for i, n := range numbs {
		val, _ := strconv.ParseFloat(n, 64)
		arr[i] = val
	}
}

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

package main

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

var in = bufio.NewReader(os.Stdin)

const tolerance float64 = 0.000001

func isClose(a, b float64) bool {
	if a > b {
		b, a = a, b
	}
	return b-a < tolerance
}

func solve() {
	var n int
	fmt.Fscan(in, &n)

	a := make([]float64, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}

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

	result := n
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			diff := (a[j] - a[i]) / float64(j-i)

			v := a[i] - diff*float64(i)
			curCnt := 0
			for k := 0; k < n; k++ {
				if !isClose(a[k], v) {
					curCnt++
				}
				v += diff
			}
			if curCnt < result {
				result = curCnt
			}
		}
	}
	fmt.Println(result)
}

func main() {
	var t int
	fmt.Fscan(in, &t)

	for i := 0; i < t; i++ {
		solve()
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var test int
	fmt.Fscan(in, &test)
	for ; test > 0; test-- {
		var n int
		fmt.Fscan(in, &n)

		ar := make([]int, n)
		for i := range ar {
			fmt.Fscan(in, &ar[i])
		}

		if n <= 2 {
			fmt.Fprintln(out, 0)
			continue
		}

		res := n
		for i := 0; i < n; i++ {
			for j := i + 1; j < n; j++ {
				count := 0
				for k := 0; k < n; k++ {
					if (ar[k]-ar[i])*(k-j) != (ar[k]-ar[j])*(k-i) {
						count++
					}
				}

				if count < res {
					res = count
				}
			}
		}

		fmt.Fprintln(out, res)
	}
}

package main

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

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

func solve(){
	var n int
	fmt.Fscan(in, &n)
	a := make([]int, n)
	for i:=0; i < n ; i++{
		fmt.Fscan(in, &a[i])
	}
	var ans int = 1
	for i:=0; i <n;i++{
		for j:= i+1; j < n ;j++{
			cur := 0
			for k:= 0 ; k < n ;k++{
				if (a[k] - a[i]) * (k-j) == (a[k] - a[j]) *(k-i){
					cur++
				}
			}
			if cur > ans {
				ans = cur
			}
		}
	}
	fmt.Println(n - ans);
}

func main() {
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		solve();
	}
}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    scn := bufio.NewScanner(reader)
    scn.Scan()
	t, _ := strconv.Atoi(scn.Text())
	for t>0 {
		t--
		scn.Scan()
		N, _ := strconv.Atoi(scn.Text())
		scn.Scan()
		strA := Split(scn.Text()," ")
		A := make([]int, 70)
		for i, a := range strA {
			A[i], _  = strconv.Atoi(a)
		}
		maxlen := 1
		for i,x := range A[:N] {
			for j:=0; j<i; j++ {
				length := 2
				nom, denom := x-A[j], i-j
				for k:=j+1; k<i; k++ {
					if (A[k] - A[j])*denom == nom*(k-j) {
						length++
					}
				}
				if length>maxlen {
					maxlen = length
				}
			}
		}
		fmt.Println(N-maxlen)
	}
}

// """
// a+b+c = (a+c)(3)/2
// b = (a+c)/2
// любые три подряд идущих образуют прогрессию
// вопрос сколько минимум надо изменить
// """

package main

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

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

func main() {
	defer out.Flush()
	//redirectInputToFile(in, "input.txt")

	T := readInt()
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	n := readInt()
	arr := readArrInt()
	if n == 1 || n == 2 {
		println(0)
		return
	}
	ans := 0
	for i := 0; i < n; i++ {
		m := make(map[float64]int, 0)
		for j := i + 1; j < n; j++ {
			gap := float64(arr[j]-arr[i]) / float64(j-i)
			m[gap]++
			ans = max(ans, m[gap])
		}
	}
	println(n-ans-1)

}

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

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

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

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

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

func readFloat(in *bufio.Reader) float64 {
	nStr := readStr()
	n, _ := strconv.ParseFloat(nStr, 64)
	return n
}

func readInt() int {
	nStr := readStr()
	n, _ := strconv.Atoi(nStr)
	return n
}

func readStr() string {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	return nStr
}

func readLineNumbs() []string {
	line := readStr()
	numbs := strings.Split(line, " ")
	return numbs
}

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

func readArrFloat() {
	numbs := readLineNumbs()
	arr := make([]float64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseFloat(n, 64)
		arr[i] = val
	}
}

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

// PRINT
func print(args ...interface{}) {
	fmt.Fprint(out, args...)
	out.Flush()
}

func println(args ...interface{}) {
	fmt.Fprintln(out, args...)
	out.Flush()
}

func printErr(args ...interface{}) {
	fmt.Fprint(err, args...)
	err.Flush()
}

func printlnErr(args ...interface{}) {
	fmt.Fprintln(err, args...)
	err.Flush()
}

package main

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

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

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

	var ans = n
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			var cnt = 0
			for k := 0; k < n; k++ {
				// if (a[i]-a[k]) / (i-k) == (a[j]-a[k]) / (j-k)
				if (a[i]-a[k])*(j-k) != (a[j]-a[k])*(i-k) {
					cnt++
				}
			}
			if cnt < ans {
				ans = cnt
			}
		}
	}
	return ans
}

func main() {
	var ntc int
	fmt.Fscan(in, &ntc)
	for t := 0; t < ntc; t++ {
		fmt.Fprintf(out, "%d\n", solveCase())
	}
	out.Flush()
}

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(reader, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
// 	redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	var a = make([]float64, n)
	for i := range a {
		scan(&a[i])
	}
	if n <= 2 {
		printf("0\n")
		return
	}
	var (
		x, dx    float64
		res, ans = 0, n
		check    = func() {
			res = 0
			for i := range a {
				if a[i] != x+float64(i)*dx {
					res++
				}
			}
			if ans > res {
				ans = res
			}
		}
	)
	for i1 := 0; i1 < len(a); i1++ {
		for i2 := i1 + 1; i2 < len(a); i2++ {
			dx = (a[i2] - a[i1]) / float64(i2-i1)
			x = a[i1] - float64(i1)*dx
			check()
		}
	}
	printf("%v\n", ans)
}

package main

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

var arr [75]float64

func main() {
	//file, _ := os.Open("input.txt")
	//in := bufio.NewReader(file)
	in := bufio.NewReader(os.Stdin)

	input1 := readArrInt(in)
	t := input1[0]
	for ; t != 0; t-- {
		input := readArrInt(in)
		n := input[0]
		readArrFloat(in)
		if n <= 2 {
			fmt.Println(0)
			continue
		}
		ans := n - 2
		for i := 0; i < n; i++ {
			for j := i + 1; j < n; j++ {
				step := (arr[j] - arr[i]) / float64(j-i)
				cur := arr[i] - step*float64(i)
				curAns := 0
				for z := 0; z < n; z++ {
					if arr[z] != cur {
						curAns++
					}
					cur += step
					if curAns >= ans {
						break
					}
				}
				ans = min(ans, curAns)
			}
		}
		fmt.Println(ans)
	}
}

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

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

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

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

func readFloat(in *bufio.Reader) float64 {
	nStr := readStr(in)
	n, _ := strconv.ParseFloat(nStr, 64)
	return n
}

func readInt(in *bufio.Reader) int {
	nStr := readStr(in)
	n, _ := strconv.Atoi(nStr)
	return n
}

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

func readLineNumbs(in *bufio.Reader) []string {
	line := readStr(in)
	numbs := strings.Split(line, " ")
	return numbs
}

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

func readArrFloat(in *bufio.Reader) {
	numbs := readLineNumbs(in)
	for i, n := range numbs {
		val, _ := strconv.ParseFloat(n, 64)
		arr[i] = val
	}
}

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


Let's denote the function $$$f(s)$$$ that takes a string $$$s$$$ consisting of lowercase Latin letters and dots, and returns a string consisting of lowercase Latin letters as follows:  let $$$r$$$ be an empty string;  process the characters of $$$s$$$ from left to right. For each character $$$c$$$, do the following: if $$$c$$$ is a lowercase Latin letter, append $$$c$$$ at the end of the string $$$r$$$; otherwise, delete the last character from $$$r$$$ (if $$$r$$$ is empty before deleting the last character — the function crashes);  return $$$r$$$ as the result of the function. You are given two strings $$$s$$$ and $$$t$$$. You have to delete the minimum possible number of characters from $$$s$$$ so that $$$f(s) = t$$$ (and the function does not crash). Note that you aren't allowed to insert new characters into $$$s$$$ or reorder the existing ones.

The input consists of two lines: the first one contains $$$s$$$ — a string consisting of lowercase Latin letters and dots, the second one contains $$$t$$$ — a string consisting of lowercase Latin letters ($$$1 \le |t| \le |s| \le 10000$$$). Additional constraint on the input: it is possible to remove some number of characters from $$$s$$$ so that $$$f(s) = t$$$.

Print one integer — the minimum possible number of characters you have to delete from $$$s$$$ so $$$f(s)$$$ does not crash and returns $$$t$$$ as the result of the function.

package main

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

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

	s, _ := reader.ReadString('\n')
	t, _ := reader.ReadString('\n')

	fmt.Println(solve(s[:len(s)-1], t[:len(t)-1]))
}

func solve(s, t string) int {
	n := len(s)
	m := len(t)
	dp := make([][]int, n+1)
	for i := 0; i <= n; i++ {
		dp[i] = make([]int, m+1)
		for j := 0; j <= m; j++ {
			dp[i][j] = n + 1
		}
	}

	nxt := make([]int, n)

	for i := 0; i < n; i++ {
		if s[i] != '.' {
			nxt[i] = -1
			var bal int
			for j := i; j < n; j++ {
				if s[j] == '.' {
					bal--
				} else {
					bal++
				}
				if bal == 0 {
					nxt[i] = j
					break
				}
			}
		}
	}

	dp[0][0] = 0

	for i := 0; i < n; i++ {
		for j := 0; j <= m; j++ {
			dp[i+1][j] = min(dp[i+1][j], dp[i][j]+1)
			if j < m && s[i] == t[j] {
				dp[i+1][j+1] = min(dp[i+1][j+1], dp[i][j])
			}
			if s[i] != '.' && nxt[i] != -1 {
				dp[nxt[i]+1][j] = min(dp[nxt[i]+1][j], dp[i][j])
			}
		}
	}

	return dp[n][m]
}

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


You are given a permutation $$$p=[p_1, p_2, \ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$. Let's call the number $$$m$$$ ($$$1 \le m \le n$$$) beautiful, if there exists two indices $$$l, r$$$ ($$$1 \le l \le r \le n$$$), such that the numbers $$$[p_l, p_{l+1}, \ldots, p_r]$$$ is a permutation of numbers $$$1, 2, \ldots, m$$$.For example, let $$$p = [4, 5, 1, 3, 2, 6]$$$. In this case, the numbers $$$1, 3, 5, 6$$$ are beautiful and $$$2, 4$$$ are not. It is because:  if $$$l = 3$$$ and $$$r = 3$$$ we will have a permutation $$$[1]$$$ for $$$m = 1$$$;  if $$$l = 3$$$ and $$$r = 5$$$ we will have a permutation $$$[1, 3, 2]$$$ for $$$m = 3$$$;  if $$$l = 1$$$ and $$$r = 5$$$ we will have a permutation $$$[4, 5, 1, 3, 2]$$$ for $$$m = 5$$$;  if $$$l = 1$$$ and $$$r = 6$$$ we will have a permutation $$$[4, 5, 1, 3, 2, 6]$$$ for $$$m = 6$$$;  it is impossible to take some $$$l$$$ and $$$r$$$, such that $$$[p_l, p_{l+1}, \ldots, p_r]$$$ is a permutation of numbers $$$1, 2, \ldots, m$$$ for $$$m = 2$$$ and for $$$m = 4$$$. You are given a permutation $$$p=[p_1, p_2, \ldots, p_n]$$$. For all $$$m$$$ ($$$1 \le m \le n$$$) determine if it is a beautiful number or not.

The first line contains the only integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the given permutation $$$p$$$. The next line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are different) — the given permutation $$$p$$$. It is guaranteed, that the sum of $$$n$$$ from all test cases in the input doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines — the answers to test cases in the order they are given in the input.  The answer to a test case is the string of length $$$n$$$, there the $$$i$$$-th character is equal to $$$1$$$ if $$$i$$$ is a beautiful number and is equal to $$$0$$$ if $$$i$$$ is not a beautiful number.

NoteThe first test case is described in the problem statement.In the second test case all numbers from $$$1$$$ to $$$5$$$ are beautiful:  if $$$l = 3$$$ and $$$r = 3$$$ we will have a permutation $$$[1]$$$ for $$$m = 1$$$;  if $$$l = 3$$$ and $$$r = 4$$$ we will have a permutation $$$[1, 2]$$$ for $$$m = 2$$$;  if $$$l = 2$$$ and $$$r = 4$$$ we will have a permutation $$$[3, 1, 2]$$$ for $$$m = 3$$$;  if $$$l = 2$$$ and $$$r = 5$$$ we will have a permutation $$$[3, 1, 2, 4]$$$ for $$$m = 4$$$;  if $$$l = 1$$$ and $$$r = 5$$$ we will have a permutation $$$[5, 3, 1, 2, 4]$$$ for $$$m = 5$$$.

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 main() {
	defer writer.Flush()
	var n int
	scanf("%d\n", &n)
	for i := 0; i < n; i++ {
		var m, index int
		scanf("%d\n", &m)
		a := make([]int, m)
		for j := 0; j < m; j++ {
			if j<m-1 {
				scanf("%d", &a[j])
			}else{
				scanf("%d\n", &a[j])
			}
			if a[j] == 1 {
				index = j
			}
		}
		cnt := 1
		sum := a[index]
		l := index - 1
		r := index + 1
		if cnt == sum {
			printf("1")
		} else {
			printf("0")
		}
		for j := 0; j < m-1; j++ {
			if l < 0 || (r < m && a[l] > a[r]) {
				sum += a[r]
				r++
			} else {
				sum += a[l]
				l--
			}
			cnt += j + 2
			if sum == cnt {
				printf("1")
			} else {
				printf("0")
			}
		}
		printf("\n")
	}
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

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

type vector_i []int
func (v *vector_i) pb(x int) {
	*v=append(*v,x)
}
func (v *vector_i) size() int {
	return len(*v)
}
func (v *vector_i) pop() {
	if !(*v).empty() {
		*v=(*v)[:len(*v)-1]
	}
}
func (v *vector_i) reverse() {
	n:=(*v).size()
	for i:=0;i*2<n;i++ {
		(*v)[i],(*v)[n-i-1]=(*v)[n-i-1],(*v)[i]
	}
}
func (v *vector_i) clear() {
	*v=(*v)[:0]
}
func (v *vector_i) empty() bool {
	return (*v).size()==0
}
func (v *vector_i) sort() {
	sort.Slice(*v, func (i, j int) bool {
		return (*v)[i]<(*v)[j]
	})
}
type fun_ii_b func (i, j int) bool
func (v *vector_i) sort_fun(f fun_ii_b) {
	sort.Slice(*v,f)
}
func (v *vector_i) lb(x int) int {
	var l,r int = 0,(*v).size()
	for l<r {
		mid:=(l+r)/2
		if (*v)[mid]<x {
			l=mid+1
		} else {
			r=mid
		}
	}
	return l
}
func (v *vector_i) ub(x int) int {
	var l,r int = 0,(*v).size()
	for l<r {
		mid:=(l+r)/2
		if (*v)[mid]<=x {
			l=mid+1
		} else {
			r=mid
		}
	}
	return l
}
func (v *vector_i) del(pos int) {
	if pos>=0 && pos<len(*v) {
		for i:=pos;i<len(*v)-1;i++ {
			(*v)[i]=(*v)[i+1]
		}
		(*v).pop()
	}
}
func (v *vector_i) ins(pos, val int) {
	(*v).pb(0)
	for i:=len(*v)-1;i>pos;i-- {
		(*v)[i]=(*v)[i-1]
	}
	(*v)[pos]=val
}
func (v *vector_i) substr(l, r int) vector_i {
	var ans vector_i=make(vector_i,r-l+1)
	for i:=l;i<=r;i++ {
		ans.pb((*v)[i])
	}
	return ans
}
func (v *vector_i) resize(n int) {
	for len(*v)>n {
		(*v).pop()
	}
	for len(*v)<n {
		(*v).pb(0)
	}
}

func main() {

	defer writer.Flush()

	var t int
	scanf("%d\n",&t)
	for ;t>0;t-- {
		var p,id vector_i
		var n int
		scanf("%d\n",&n)
		for i:=1;i<=n;i++ {
			var x int
			scanf("%d ",&x)
			p.pb(x)
			id.pb(i)
		}
		scanf("\n")
		id.sort_fun(func(i,j int) bool {
			return p[id[i]-1]<p[id[j]-1]
		})
		var mn,mx int=1e9,-1e9
		for j,i:=range id {
			mn=min(mn,i)
			mx=max(mx,i)
			if mx-mn==j {
				printf("1")
			} else {
				printf("0")
			}
		}
		printf("\n")
	}
}

package main

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

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main(){
	defer writer.Flush()
	T := reader.NextInt64()
	for t:=int64(0);t<T;t++{
		n:=(reader.NextInt())
		arr:=make([]int,n)
		for i:= range arr {
			arr[i]=reader.NextInt()
		}
		solve(arr,n)
	}
}

func solve(arr []int, n int){
	hm:=make(map[int]int,n+1)
	for i,val:=range arr {
		hm[val-1]=i
	}
	l:=n
	r:=0
	var b strings.Builder;
	b.Grow(n+1)
	for i:=0;i<n;i++ {
		l=Mn(l,hm[i])
		r=Mx(r,hm[i])
		if r-l == i {
			b.WriteString("1")
			// ans+="1"
		}else{
			b.WriteString("0")
			// ans+="0"
		}
	}
	writer.Printf("%s \n", b.String())
	return
}

func Mn (a,b int)int {
	if a<b{
		return a
	}
	return b
}
func Mx (a,b int)int {
	if a<b{
		return b
	}
	return a
}
func abs(a int64)int64{
	if(a>=0){
		return a
	}
	return -a
}

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var t int
var n int
var P []int

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n = ReadInt()
		P = ReadIntSlice(n)

		solve()
	}
}

func solve() {
	pos := make([]int, n+1)
	for i := 0; i < n; i++ {
		p := P[i]
		pos[p] = i
	}

	answers := make([]rune, n)

	l, r := pos[1], pos[1]
	answers[0] = '1'
	for i := 2; i <= n; i++ {
		ChMin(&l, pos[i])
		ChMax(&r, pos[i])

		dist := r - l + 1
		if dist == i {
			answers[i-1] = '1'
		} else {
			answers[i-1] = '0'
		}
	}

	fmt.Println(string(answers))
}

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

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

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

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

package main

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

func main() {
	defer Flush()

	t := readi()
	for i := 0; i < t; i++ {
		n, a := readInts(0)
		ans := solve(n, a)
		for _, v := range ans {
			printf("%d", v)
		}
		println()
	}

}

func solve(n int, a []int) []int {
	w := make([]int, n+1)
	var b [2][]int
	for i := 0; i < n && a[i] != 1; i++ {
		b[0] = append(b[0], a[i])
		w[a[i]] = 0
	}
	for i := n - 1; 0 <= i && a[i] != 1; i-- {
		b[1] = append(b[1], a[i])
		w[a[i]] = 1
	}
	reverse(b[0])
	reverse(b[1])

	res := make([]int, n+1)
	res[n] = 1
	res[1] = 1
	c := 1
	m := make(map[int]bool)
	for i := 2; i < n; i++ {
		d := w[i]
		if !m[i] {
			var j int
			for j = 0; j < len(b[d]); j++ {
				c++
				v := b[d][j]
				m[v] = true
				if v == i {
					j++
					break
				}
			}
			b[d] = b[d][j:]
		}
		if c == i {
			res[i] = 1
		}
	}
	return res[1:]
}

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

// IO helper functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// IO functions

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

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

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

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

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

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

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

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

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

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

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

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

// Utilities

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

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

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

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

// reverse slice in place
func reverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}

// areverse: allocating reverse
func areverse(a []int) []int {
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[len(a)-i-1]
	}
	return b
}

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

// Simple math functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

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

func main() {
	defer Flush()

	t := readi()
	for i := 0; i < t; i++ {
		n, a := readInts(0)
		ans := solve(n, a)
		for _, v := range ans {
			printf("%d", v)
		}
		println()
	}

}

func solve(n int, a []int) []int {
	p := make([]int, n+1)
	for i, v := range a {
		p[v] = i
	}
	res := make([]int, n+1)
	l, r := n, -1
	for i := 1; i <= n; i++ {
		r = max(r, p[i])
		l = min(l, p[i])
		if r-l+1 == i {
			res[i] = 1
		}
	}
	return res[1:]
}

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

// IO helper functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// IO functions

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

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

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

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

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

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

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

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

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

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

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

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

// Utilities

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

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

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

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

// reverse slice in place
func reverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}

// areverse: allocating reverse
func areverse(a []int) []int {
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[len(a)-i-1]
	}
	return b
}

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

// Simple math functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

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

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

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

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

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

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

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return 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
}

const MOD = 1000000000 + 7

var t int
var n int
var P []int

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n = ReadInt()
		P = ReadIntSlice(n)

		solve()
	}
}

func solve() {
	idx := make([]int, n+1)
	for i, ele := range P {
		idx[ele] = i
	}

	min, max := idx[1], idx[1]
	answers := make([]rune, n+1)

	for i := 1; i <= n; i++ {
		if idx[i] > max {
			max = idx[i]
		}
		if idx[i] < min {
			min = idx[i]
		}

		if max-min == i-1 {
			answers[i] = '1'
		} else {
			answers[i] = '0'

		}
	}
	fmt.Println(string(answers[1:]))
}

package main

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

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

	testCount := 0
	fmt.Fscanf(in, "%d\n", &testCount)

	for i := 0; i < testCount; i++ {
		// input
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		arr := make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscanf(in, "%d", &arr[j])
		}
		fmt.Fscanf(in, "\n")

		beautifulNumbers(arr)
	}
}

func beautifulNumbers(arr []int) {
	idx := make([]int, len(arr)+1)
	for i, ele := range arr {
		idx[ele] = i
	}

	min, max := idx[1], idx[1]
	answers := make([]rune, len(arr)+1)

	for i := 1; i <= len(arr); i++ {
		if idx[i] > max {
			max = idx[i]
		}
		if idx[i] < min {
			min = idx[i]
		}

		if max-min == i-1 {
			answers[i] = '1'
		} else {
			answers[i] = '0'

		}
	}
	fmt.Println(string(answers[1:]))
}

package main

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

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

	testCount := 0
	fmt.Fscanf(in, "%d\n", &testCount)

	for i := 0; i < testCount; i++ {
		// input
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		arr := make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscanf(in, "%d", &arr[j])
		}
		fmt.Fscanf(in, "\n")

		beautifulNumbers(arr)
	}
}

func beautifulNumbers(arr []int) {
	idx := make([]int, len(arr)+1)
	for i, ele := range arr {
		idx[ele] = i
	}
	//fmt.Println("[", idx, "]")

	min, max := idx[1], idx[1]
	for i := 1; i <= len(arr); i++ {
		if idx[i] > max {
			max = idx[i]
		}
		if idx[i] < min {
			min = idx[i]
		}

		if max-min == i-1 {
			fmt.Print(1)
		} else {
			fmt.Print(0)

		}
	}
	fmt.Print("\n")
}

package main

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

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

	testCount := 0
	fmt.Fscanf(in, "%d\n", &testCount)

	for i := 0; i < testCount; i++ {
		// input
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		arr := make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscanf(in, "%d", &arr[j])
		}
		fmt.Fscanf(in, "\n")

		beautifulNumbers(arr)

	}
}

func beautifulNumbers(arr []int) {
	idx := make([]int, 200001)
	for i, ele := range arr {
		idx[ele] = i
	}

	// debug
	//for i := 1; i <= len(arr); i++ {
	//	fmt.Print(idx[i])
	//}
	//fmt.Print("\n")

	min, max := idx[1], idx[1]
	for i := 1; i <= len(arr); i++ {
		if idx[i] > max {
			max = idx[i]
		}
		if idx[i] < min {
			min = idx[i]
		}

		if max-min == i-1 {
			//fmt.Println("[min, max, i", min, max, i, "]")
			fmt.Print(1)
		} else {
			fmt.Print(0)

		}
	}
	fmt.Print("\n")
}

package main

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

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

	testCount := 0
	fmt.Fscanf(in, "%d\n", &testCount)

	for i := 0; i < testCount; i++ {
		// input
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		arr := make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscanf(in, "%d", &arr[j])
		}
		fmt.Fscanf(in, "\n")

		beautifulNumbers(arr)
	}
}

func beautifulNumbers(arr []int) {
	idx := make([]int, len(arr)+1)
	for i, ele := range arr {
		idx[ele] = i
	}
	//fmt.Println(idx[1:])

	min, max := len(arr)+1, -1
	for i := 1; i <= len(arr); i++ {
		ChMax(&max, idx[i])
		ChMin(&min, idx[i])

		if max-min+1 == i {
			fmt.Print(1)
		} else {
			fmt.Print(0)

		}
	}
	fmt.Print("\n")
}

func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

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

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

var ind,a [200010]int

func main(){
	defer writer.Flush()
	var T int
	scanf("%d\n",&T)
	for cas:=1;cas<=T;cas++{
		var n int
		scanf("%d\n",&n)
		for i:=0;i<n;i++{
			if i<n-1{
				scanf("%d",&a[i])
				ind[a[i]]=i
			}else{
				scanf("%d\n",&a[i])
				ind[a[i]]=i
			}
		}
		l,r:=ind[1],ind[1]
		for i:=1;i<=n;i++{
			if ind[i]<l{
				l=ind[i]
			}
			if ind[i]>r{
				r=ind[i]
			}
			if r-l+1==i {
				printf("1")
			}else{
				printf("0")
			}
		}
		printf("\n")
	}
}

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(a ...interface{})            { fmt.Fscan(reader, a...) }
func main() {
	var n int
	scanf(&n)
	for i := 0; i < n; i++ {
		var m, index int
		scanf(&m)
		a := make([]int, m)
		for j := 0; j < m; j++ {
			scanf(&a[j])
			if a[j] == 1 {
				index = j
			}
		}
		cnt := 1
		sum := a[index]
		l := index - 1
		r := index + 1
		if cnt == sum {
			printf("1")
		} else {
			printf("0")
		}
		for j := 0; j < m-1; j++ {
			if l < 0 || (r < m && a[l] > a[r]) {
				sum += a[r]
				r++
			} else {
				sum += a[l]
				l--
			}
			cnt += j + 2
			if sum == cnt {
				printf("1")
			} else {
				printf("0")
			}
		}
		printf("\n")
	}
}


Polycarp's workday lasts exactly $$$n$$$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $$$k$$$ bars at the beginning of the workday.In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $$$k$$$ is strictly greater than $$$1$$$.Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.Consider that Polycarp eats a bar in the minute $$$x$$$ and the next bar in the minute $$$y$$$ ($$$x < y$$$). Then the break time is equal to $$$y - x - 1$$$ minutes. It is not necessary for Polycarp to eat all bars he has.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200\,000$$$, $$$2 \le k \le n$$$) — the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday. The second line contains the string with length $$$n$$$ consisting of zeros and ones. If the $$$i$$$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $$$i$$$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $$$i$$$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.

Print the minimum possible break in minutes between eating chocolate bars.

NoteIn the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.In the second example Polycarp will eat bars in the minutes $$$1$$$ and $$$8$$$ anyway, also he needs to eat the chocolate bar in the minute $$$5$$$, so that the time of the maximum break will be equal to $$$3$$$ minutes.

package main

import "fmt"

func main() {
	var n int
	var k int
	fmt.Scan(&n, &k)
	var s string
	fmt.Scan(&s)

	l := 0
	r := n - 1
	minOk := r

	for r - l > 1 {
	    m := (l + r) / 2

	    tk := k - 1
	    pos := 0

	    ok := true

	    for pos < n - 1 && tk > 0 && ok {
	        prevpos := pos
	        pos += m;
	        if pos >= n {
	            pos = n - 1;
	        }

	        for s[pos] == '1' && pos > prevpos {
	            pos--;
	            if pos == prevpos {
	                ok = false;
	                break;
	            }
	        }
	        if !ok {
	            break;
	        }

	        tk--;
	    }

	    ok = ok && (pos == (n - 1))

	    if ok && m < minOk {
	        minOk = m;
	    }

	   // printf("%d %d\n", m, ok);
	    if (ok) {
	        r = m;
	    } else {
	        l = m;
	    }
	}

	fmt.Printf("%d", minOk - 1);
}


This problem is same as the previous one, but has larger constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \ldots, u_n$$$ ($$$1 \leq u_i \leq 10^5$$$) — the colors of the ribbons the cats wear.

Print a single integer $$$x$$$ — the largest possible streak of days.

NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once.

package main

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

func toInt(b []byte) int {
    var ret = 0
    for _, d := range b {
        ret = ret * 10 + int(d - '0')
    }
    return ret
}

func readInt(scanner *bufio.Scanner) int {
    scanner.Scan()
    return toInt(scanner.Bytes())
}

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

    var arr [100005]int;

    var n = readInt(scanner)

    for i := 0; i < n; i++ {
        arr[i] = readInt(scanner)
    }

    var hasCount [100005]int
    var count [100005]int

    dist := 0;

    ans := 0
    prevCount := 0
    for i := 0; i < n; i++ {
        val := arr[i]
        oldCount := count[val];
        newCount := oldCount + 1;
        if oldCount == 0 {
            dist++
        }
        count[val] = newCount

        hasCount[oldCount]--

        hasCount[newCount]++

        if newCount == 1 && (hasCount[1] == dist || hasCount[prevCount] == dist - 1) {
            ans = i
        }

        if newCount == prevCount + 1 && hasCount[prevCount] == dist - 1 {
            ans = i
        }

        if (hasCount[1] == 1 || hasCount[newCount + 1] == 1) &&
            hasCount[newCount] == dist - 1 {
            ans = i;
        }

        prevCount = newCount

    }

    fmt.Println(ans + 1)
}

package main

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

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

func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func getLine() string {
	s, _ := reader.ReadString('\n')
	if strings.HasSuffix(s, "\r\n") {
		s = s[:len(s)-2]
	} else if strings.HasSuffix(s, "\n") {
		s = s[:len(s)-1]
	}
	return s
}
func getLine2Int() (n int) {
	scanf("%d\n", &n)
	return
}
func getLine2Int2() (a, b int) {
	scanf("%d %d\n", &a, &b)
	return
}
func getLine2Ints(n int) []int {
	ans := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &ans[i])
	}
	scanf("%d\n", &ans[n-1])
	return ans
}

var debug = false

func see(a interface{}) {
	if debug {
		printf("DEBUG:%v\n", a)
	}
}

func main() {
	defer writer.Flush()

	n := getLine2Int()
	inputs := getLine2Ints(n)
	var mans int                            // 最大的结果
	var colorCount = make(map[int]int)      // 每个颜色出现的次数
	var colorCountTimes = make(map[int]int) // 每个出现的次数有几个颜色
	var mcctc int                           // 最大出现次数的是哪个颜色
	var ncctc int                           // 第二大出现次数的是哪个颜色
	for i := 0; i < n; i++ {
		tc := inputs[i]         // 当前颜色
		if colorCount[tc] > 0 { // 如果出现过，数量减1
			colorCountTimes[colorCount[tc]]--
		}
		colorCount[tc]++
		colorCountTimes[colorCount[tc]]++
		if colorCount[tc] > colorCount[mcctc] {
			ncctc = mcctc
			mcctc = tc
		} else if colorCount[tc] < colorCount[mcctc] && colorCount[tc] > colorCount[ncctc] {
			ncctc = tc
		}
		if colorCount[mcctc] == 1 ||
			colorCount[ncctc] == 0 ||
			colorCount[mcctc]*colorCountTimes[colorCount[mcctc]] == i ||
			(colorCountTimes[colorCount[mcctc]] == 1 && colorCount[ncctc]*(colorCountTimes[colorCount[ncctc]]+1) == i) {
			mans = i + 1
		}
	}
	printf("%d\n", mans)
}

package main

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

func keys(m map[int]map[int]bool) []int {
    k := make([]int, 0, len(m))
    for ky := range m {
        k = append(k, ky)
    }
    return k
}

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

    input.Scan()
    n, _ := strconv.Atoi(input.Text())

    u := make([]int, n, n)
    for i := range u {
        input.Scan()
        u[i], _ = strconv.Atoi(input.Text())
    }

    cnt := make(map[int]int)
    cntnum := make(map[int]map[int]bool)

    ans := 1
    for i, x := range u {
        cnt[x]++
        c := cnt[x]

        delete(cntnum[c - 1], x)
        if len(cntnum[c - 1]) == 0 {
            delete(cntnum, c - 1)
        }

        if _, ok := cntnum[c]; !ok {
            cntnum[c] = make(map[int]bool)
        }

        cntnum[c][x] = true

        if len(cntnum) > 2 {
            continue
        }
        if len(cntnum) == 2 {
            numcnts := keys(cntnum)
            if numcnts[0] > numcnts[1] {
                numcnts[0], numcnts[1] = numcnts[1], numcnts[0]
            }

            if numcnts[0] == 1 {
                if len(cntnum[1]) == 1 {
                    ans = i + 1
                    continue
                }
            }

            if numcnts[0] == numcnts[1] - 1 {
                if len(cntnum[numcnts[1]]) == 1 {
                    ans = i + 1
                    continue
                }
            }
        } else {
            // len(cntnum) == 1
            numcnts := keys(cntnum)
            if numcnts[0] == 1 || len(cnt) == 1 {
                ans = i + 1
            }
        }
    }

    fmt.Println(ans)
}

package main

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

type Comparable interface {
	Less(interface{}) bool
}

type SplayNode struct {
	Key Comparable
	parent, left, right *SplayNode
}

func (n *SplayNode) Next() *SplayNode {
	if n.right != nil {
		next := n.right
		for next.left != nil {
			next = next.left
		}
		return next
	}
	next := n
	for next.parent != nil && next.parent.right == next {
		next = next.parent
	}
	return next.parent
}

func (n *SplayNode) Prev() *SplayNode {
	if n.left != nil {
		next := n.left
		for next.right != nil {
			next = next.right
		}
		return next
	}
	next := n
	for next.parent != nil && next.parent.left == next {
		next = next.parent
	}
	return next.parent
}

func (n *SplayNode) rotate() {
	p := n.parent
	if p.left == n {
		p.left = n.right
		if p.left != nil {
			p.left.parent = p
		}
		n.right = p
	} else {
		p.right = n.left
		if p.right != nil {
			p.right.parent = p
		}
		n.left = p
	}
	g := p.parent
	if g != nil {
		if g.left == p {
			g.left = n
		} else {
			g.right = n
		}
	}
	p.parent = n
	n.parent = g
}

func (n *SplayNode) splay() {
	for n.parent != nil {
		p := n.parent
		g := p.parent
		if g != nil {
			if (g.left == p) == (p.left == n) {
				p.rotate()
			} else {
				n.rotate()
			}
		}
		n.rotate()
	}
}

type SplayTree struct {
	root *SplayNode
}

func (t *SplayTree) LowerBound(k Comparable) (n *SplayNode) {
	for it := t.root; it != nil; {
		if it.Key.Less(k) {
			it = it.right
		} else {
			n = it
			it = it.left
		}
	}
	if n != nil {
		n.splay()
		t.root = n
	}
	return
}

func (t *SplayTree) Split(k Comparable, r *SplayTree) {
	n := t.LowerBound(k)
	if n == nil {
		r.root = nil
		return
	}
	t.root, r.root = n.left, n
	if n.left != nil {
		n.left.parent = nil
		n.left = nil
	}
}

func (t *SplayTree) Merge(r *SplayTree) {
	n := r.root
	if n == nil {
		return
	}
	for n.left != nil {
		n = n.left
	}
	n.splay()
	n.left = t.root
	if n.left != nil {
		n.left.parent = n
	}
	t.root, r.root = n, nil
}

func (t *SplayTree) Insert(k Comparable) *SplayNode {
	n := &SplayNode{Key: k}
	r := SplayTree{}
	t.Split(k, &r)
	n.left, n.right = t.root, r.root
	if n.left != nil {
		n.left.parent = n
	}
	if n.right != nil {
		n.right.parent = n
	}
	t.root = n
	return n
}

func (t *SplayTree) Erase(n *SplayNode) {
	n.splay()
	t.root = n.left
	if t.root != nil {
		t.root.parent = nil
	}
	r := SplayTree{root: n.right}
	if r.root != nil {
		r.root.parent = nil
	}
	t.Merge(&r)
}

type Node struct {
	Key int
	Value int
}

func (n *Node) Less(other interface{}) bool {
	return n.Key < other.(*Node).Key
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	a := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		a[i], _ = strconv.Atoi(scanner.Text())
	}
	// k := make(map[int]int)
	k := make(map[int]int)
	t := SplayTree{}
	ans := 1
	var l, r *SplayNode
	for i := 0; i < n; i++ {
		if k[a[i]] > 0 {
			n := t.LowerBound(&Node{Key: k[a[i]]})
			n.Key.(*Node).Value--
			if n.Key.(*Node).Value == 0 {
				if l == n {
					l = nil
				}
				if r == n {
					r = nil
				}
				t.Erase(n)
			}
		}
		k[a[i]]++
		n := t.LowerBound(&Node{Key: k[a[i]]})
		if n == nil || n.Key.(*Node).Key > k[a[i]] {
			n = t.Insert(&Node{Key: k[a[i]]})
		}
		n.Key.(*Node).Value++
		if l == nil || n.Key.Less(l.Key) {
			l = n
		}
		if r == nil || r.Key.Less(n.Key) {
			r = n
		}
		first, last := l.Key.(*Node), r.Key.(*Node)
		// fmt.Println(first, last)
		if last.Key == 1 {
			ans = i + 1
		}  else if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		} else if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Println(ans)
}

// Author: sighduck
// URL: https://codeforces.com/contest/1163/problem/B1, https://codeforces.com/contest/1163/problem/B2

package main

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

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

func isValidStreak(countOfCount map[int]int, maxCount int, total int) bool {
	if countOfCount[1] == total {
		return true
	} else if countOfCount[total] == 1 {
		return true
	} else if countOfCount[1] == 1 && countOfCount[maxCount]*maxCount+1 == total {
		return true
	}
	return countOfCount[maxCount-1] > 0 && countOfCount[maxCount] == 1 &&
		countOfCount[maxCount]*maxCount+countOfCount[maxCount-1]*(maxCount-1) == total
}

func Solve(n int, u []int) int {
	maxCount := 0
	longestStreak := 1
	count := make(map[int]int)
	countOfCount := make(map[int]int)
	count[u[0]] = 1
	countOfCount[1] = 1
	for i := 1; i < n; i++ {
		elem := u[i]
		countOfCount[count[elem]] -= 1
		count[elem] += 1
		countOfCount[count[elem]] += 1
		maxCount = max(maxCount, count[elem])
		total := i + 1
		if isValidStreak(countOfCount, maxCount, total) {
			longestStreak = total
		}
	}
	return longestStreak
}

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

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

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

package main

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

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

    input.Scan()
    n, _ := strconv.Atoi(input.Text())

    u := make([]int, n, n)
    for i := range u {
        input.Scan()
        u[i], _ = strconv.Atoi(input.Text())
    }

    cnt := make(map[int]int)
    cntnum := make(map[int]map[int]bool)

    ans := 1
    for i, x := range u {
        cnt[x]++
        c := cnt[x]

        delete(cntnum[c - 1], x)
        if len(cntnum[c - 1]) == 0 {
            delete(cntnum, c - 1)
        }

        if _, ok := cntnum[c]; !ok {
            cntnum[c] = make(map[int]bool)
        }

        cntnum[c][x] = true

        if i == 0 {
            continue
        }

        if len(cntnum) > 2 {
            continue
        }
        if len(cntnum) == 2 {
            numcnts := make([]int, 0, 2)
            for nc := range cntnum {
                numcnts = append(numcnts, nc)
            }
            if numcnts[0] > numcnts[1] {
                numcnts[0], numcnts[1] = numcnts[1], numcnts[0]
            }

            if numcnts[0] == 1 {
                if len(cntnum[1]) == 1 {
                    ans = i + 1
                    continue
                }
            }

            if numcnts[0] == numcnts[1] - 1 {
                if len(cntnum[numcnts[1]]) == 1 {
                    ans = i + 1
                    continue
                }
            }
        } else {
            // len(cntnum) == 1
            if _, ok := cntnum[1]; ok {
                ans = i + 1
            }
        }
    }

    fmt.Println(ans)
}

package main

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

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

    input.Scan()
    n, _ := strconv.Atoi(input.Text())

    u := make([]int, n, n)
    for i := range u {
        input.Scan()
        u[i], _ = strconv.Atoi(input.Text())
    }

    cnt := make(map[int]int)
    cntnum := make(map[int]map[int]bool)

    ans := 1
    for i, x := range u {
        cnt[x]++
        c := cnt[x]

        delete(cntnum[c - 1], x)
        if len(cntnum[c - 1]) == 0 {
            delete(cntnum, c - 1)
        }

        if _, ok := cntnum[c]; !ok {
            cntnum[c] = make(map[int]bool)
        }

        cntnum[c][x] = true

        if i == 0 {
            continue
        }

        if len(cntnum) > 2 {
            continue
        }
        if len(cntnum) == 2 {
            if single, ok := cntnum[1]; ok {
                if len(single) == 1 {
                    ans = i + 1
                }
            }
        } else {
            // len(cntnum) == 1
            if _, ok := cntnum[1]; ok {
                ans = i + 1
            }
        }
    }

    fmt.Println(ans)
}

package main

import "fmt"

func main() {
  var n int
  fmt.Scanf("%d\n", &n)
  a := make([]int, n)
  for i := 0; i < n; i++ {
    fmt.Scanf("%d", &a[i])
  }
  ans := 0
  k := make(map[int]int)
  c := make(map[int]int)
  mn, mx := 0, 0
  for i := 0; i < n - 1; i++ {
    if k[a[i]] > 0 {
      c[k[a[i]]]--
    }
    k[a[i]]++
    c[k[a[i]]]++
    if k[a[i]] < mn {
      mn = k[a[i]]
    }
    for c[mn] == 0 {
      mn++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    if mn == mx {
      ans = i + 2
    }
  }
  fmt.Printf("%d", ans)
}

package main

import "fmt"

var n int
var a []int

func good(p int) bool {
  counts := map[int]int{}
  for i := 0; i < p; i++ {
    counts[a[i]]++
  }
  kind1, kind2 := 0, 0
  for _, value := range counts {
    if kind1 == 0 {
      kind1 = value
    } else if kind2 == 0 {
      kind2 = value
    } else if value != kind1 && value != kind2 {
      return false
    }
  }
  return kind1 + 1 == kind2 || kind2 + 1 == kind1 || kind1 <= 1 || kind2 <= 1
}

func main() {
  fmt.Scanf("%d", &n)
  a = make([]int, n)
  for i := 0; i < n; i++ {
    fmt.Scanf("%d", &a[i])
  }
  l, r := 0, n + 1
  for l < r {
    m := (l + r) / 2
    if good(m) {
      l = m + 1
    } else {
      r = m
    }
  }
  fmt.Printf("%d", l - 1)
}

package main

import "fmt"

func main() {
  var n int
  fmt.Scanf("%d\n", &n)
  a := make([]int, n)
  for i := 0; i < n; i++ {
    fmt.Scanf("%d", &a[i])
  }
  ans := 1
  k := make(map[int]int)
  c := make(map[int]int)
  mn, mx := 0, 0
  for i := 0; i < n; i++ {
    if k[a[i]] > 0 {
      c[k[a[i]]]--
    }
    k[a[i]]++
    c[k[a[i]]]++
    if k[a[i]] < mn {
      mn = k[a[i]]
    }
    for c[mn] == 0 {
      mn++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    if mn + 1 == mx {
      if c[mx] == 1 && mn + 1 >= mx {
          ans = i + 1
      }
    }
  }
  fmt.Printf("%d", ans)
}

package main

import "fmt"

func main() {
  var n int
  fmt.Scanf("%d", &n)
  a := make([]int, n)
  for i := 0; i < n; i++ {
    fmt.Scanf("%d", &a[i])
  }
  ans := 0
  k := make(map[int]int)
  c := make(map[int]int)
  mn, mx := 0, 0
  for i := 0; i < n - 1; i++ {
    if k[a[i]] > 0 {
      c[k[a[i]]]--
    }
    k[a[i]]++
    c[k[a[i]]]++
    if k[a[i]] < mn {
      mn = k[a[i]]
    }
    for c[mn] == 0 {
      mn++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    if mn == mx {
      ans = i
    }
  }
  fmt.Printf("%d", ans + 2)
}

package main

import "fmt"

func main() {
  var n int
  fmt.Scanf("%d\n", &n)
  a := make([]int, n)
  for i := 0; i < n; i++ {
    fmt.Scanf("%d", &a[i])
  }
  ans := 1
  k := make(map[int]int)
  c := make(map[int]int)
  mn, mx := 0, 0
  for i := 0; i < n - 1; i++ {
    if k[a[i]] > 0 {
      c[k[a[i]]]--
    }
    k[a[i]]++
    c[k[a[i]]]++
    if k[a[i]] < mn {
      mn = k[a[i]]
    }
    for c[mn] == 0 {
      mn++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    if mn == mx {
      ans = i + 2
    }
  }
  fmt.Printf("%d", ans)
}


You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".A palindrome is a string that reads the same forward or backward.The length of string B should be at most 104. It is guaranteed that there always exists such string.You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.

First line contains a string A (1 ≤ |A| ≤ 103) consisting of lowercase Latin letters, where |A| is a length of A.

Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.

NoteIn the first example, "aba" is a subsequence of "aba" which is a palindrome.In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.

package main

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

func main() {
	z := bufio.NewScanner(os.Stdin)
	z.Split(bufio.ScanLines)
	z.Scan()
	s :=  strings.TrimSpace(z.Text())
	sb := strings.Builder {}
	sb.Grow(len(s)*2)
	for i := 0; i < len(s); i++  {
		sb.WriteByte(s[i])
	}
	for i := len(s)-1; i >= 0; i--  {
		sb.WriteByte(s[i])
	}
	fmt.Println(sb.String())

}


There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.

The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right.

Print the number of steps, so that the line remains the same afterward.

NoteIn the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1]  →  [10 8 4]  →  [10]. So, there are two steps.

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol320D(reader io.Reader, writer io.Writer) {
	max := func(vals ...int) int {
		ans := vals[0]
		for _, val := range vals[1:] {
			if val > ans {
				ans = val
			}
		}
		return ans
	}

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

	var n int
	Fscan(in, &n)
	arr := make([]int, n)
	for i := range arr {
		Fscan(in, &arr[i])
	}

	ans := make([]int, n)
	stack := []int{}
	for i := n - 1; i >= 0; i-- {
		cnt := 0
		for len(stack) > 0 && arr[stack[len(stack)-1]] < arr[i] {
			var pos int
			stack, pos = stack[:len(stack)-1], stack[len(stack)-1]
			cnt = max(cnt+1, ans[pos])
			ans[i] = cnt
		}
		stack = append(stack, i)
	}
	Fprint(out, max(ans...))
}

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

package main

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

var sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
var w *bufio.Writer = bufio.NewWriter(os.Stdout)

func ni() int {
  sc.Scan()
  ans, _ := strconv.Atoi(sc.Text())
  return ans
}

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

func pri(n int)    { w.WriteString(strconv.Itoa(n)) }
func prll(n int64) { w.WriteString(strconv.FormatInt(n, 10)) }
func sp()          { w.WriteByte(' ') }
func endl()        { w.WriteByte('\n') }

func main() {
  sc.Split(bufio.ScanWords)
  n := ni()
  a := make([]int, n)
  max := make([]int, n)
  for i := 0; i < n; i++ {
    a[i] = ni()
    max[i] = -1
  }
  stack := make([]int, n)
  cur := 0
  for i := n - 1; i >= 0; i-- {
    if cur != 0 {
      for cur > 0 && a[stack[cur-1]] < a[i] {
        max[stack[cur-1]] = i
        cur--
      }
    }
    stack[cur] = i
    cur++
  }
  t := make([]int, n*4)
  var getmax func(v, tl, tr, l, r int) int
  var update func(v, tl, tr, pos, new_val int)
  var mi, ma func(i, j int) int

  mi = func(i, j int) int {
    if i < j {
      return i
    }
    return j
  }
  ma = func(i, j int) int {
    if i >= j {
      return i
    }
    return j
  }

  getmax = func(v, tl, tr, l, r int) int {
    if l > r {
      return 0
    } else if l == tl && r == tr {
      return t[v]
    }
    tm := (tl + tr) / 2
    return ma(getmax(v*2, tl, tm, l, mi(r, tm)), getmax(v*2+1, tm+1, tr, ma(l, tm+1), r))
  }

  update = func(v, tl, tr, pos, new_val int) {
    if tl == tr {
      t[v] = new_val
    } else {
      tm := (tl + tr) / 2
      if pos <= tm {
        update(v*2, tl, tm, pos, new_val)
      } else {
        update(v*2+1, tm+1, tr, pos, new_val)
      }
      t[v] = ma(t[v*2], t[v*2+1])
    }
  }

  for i := 0; i < n; i++ {
    switch {
    case max[i] == -1:
    case max[i] == i-1:
      update(1, 0, n-1, i, 1)
    default:
      update(1, 0, n-1, i, getmax(1, 0, n-1, max[i]+1, i-1)+1)
    }
  }
  pri(getmax(1, 0, n-1, 0, n-1))
  endl()
  w.Flush()
}

package main

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

var sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
var w *bufio.Writer = bufio.NewWriter(os.Stdout)

func ni() int {
  sc.Scan()
  ans, _ := strconv.Atoi(sc.Text())
  return ans
}

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

func pri(n int)    { w.WriteString(strconv.Itoa(n)) }
func prll(n int64) { w.WriteString(strconv.FormatInt(n, 10)) }
func sp()          { w.WriteByte(' ') }
func endl()        { w.WriteByte('\n') }

func GetNeutralValue() int { return -2147483648 }
func GetNeutralDelta() int { return 0 }

func CombineValues(value1, value2 int) int {
  v1, v2 := value1, value2
  if v1 >= v2 {
    return v1
  }
  return v2
}

func CombineDeltas(delta1, delta2 int) int {
  return delta1 + delta2
}

func CombineValueAndDelta(value, delta int, length int) int {
  return value + delta
}

type SegmentTree struct {
  value  []int
  delta  []int
  length []int
}

func NewSegmentTree(data []int) *SegmentTree {
  tree := new(SegmentTree)
  n := len(data)
  tree.value = make([]int, n*2)
  tree.delta = make([]int, n*2)
  tree.length = make([]int, n*2)
  for i := 0; i < n; i++ {
    tree.value[i+n] = data[i]
  }
  for i := 0; i < n*2; i++ {
    tree.delta[i] = GetNeutralDelta()
    tree.length[i] = 1
  }
  for i := n*2 - 1; i > 1; i -= 2 {
    tree.value[i>>1] = CombineValues(tree.value[i], tree.value[i^1])
    tree.length[i>>1] = tree.length[i] + tree.length[i^1]
  }
  return tree
}

func (tree *SegmentTree) applyDelta(i int, delta int) {
  tree.value[i] = CombineValueAndDelta(tree.value[i], delta, tree.length[i])
  tree.delta[i] = CombineDeltas(tree.delta[i], delta)
}

func (tree *SegmentTree) pushDelta(i int) {
  d := 0
  for ; i>>uint(d) > 0; d++ {
  }
  for d -= 2; d >= 0; d-- {
    x := i >> uint(d)
    tree.applyDelta(x, tree.delta[x>>1])
    tree.applyDelta(x^1, tree.delta[x>>1])
    tree.delta[x>>1] = GetNeutralDelta()
  }
}

func (tree *SegmentTree) Modify(a, b int, delta int) {
  a += len(tree.value) >> 1
  b += len(tree.value) >> 1
  tree.pushDelta(a)
  tree.pushDelta(b)
  ta, tb := -1, -1
  for ; a <= b; a, b = (a+1)>>1, (b-1)>>1 {
    if a&1 != 0 {
      tree.applyDelta(a, delta)
      if ta == -1 {
        ta = a
      }
    }
    if b&1 == 0 {
      tree.applyDelta(b, delta)
      if tb == -1 {
        tb = b
      }
    }
  }
  for i := ta; i > 1; i >>= 1 {
    tree.value[i>>1] = CombineValues(tree.value[i], tree.value[i^1])
  }
  for i := tb; i > 1; i >>= 1 {
    tree.value[i>>1] = CombineValues(tree.value[i], tree.value[i^1])
  }
}

func (tree *SegmentTree) Query(a, b int) int {
  a += len(tree.value) >> 1
  b += len(tree.value) >> 1
  tree.pushDelta(a)
  tree.pushDelta(b)
  res := GetNeutralValue()
  for ; a <= b; a, b = (a+1)>>1, (b-1)>>1 {
    if a&1 != 0 {
      res = CombineValues(res, tree.value[a])
    }
    if b&1 == 0 {
      res = CombineValues(res, tree.value[b])
    }
  }
  return res
}

func main() {
  sc.Split(bufio.ScanWords)
  n := ni()
  a := make([]int, n)
  max := make([]int, n)
  for i := 0; i < n; i++ {
    a[i] = ni()
    max[i] = -1
  }
  stack := make([]int, n)
  cur := 0
  for i := n - 1; i >= 0; i-- {
    if cur != 0 {
      for cur > 0 && a[stack[cur-1]] < a[i] {
        max[stack[cur-1]] = i
        cur--
      }
    }
    stack[cur] = i
    cur++
  }
  tree := NewSegmentTree(make([]int, n))

  for i := 0; i < n; i++ {
    switch {
    case max[i] == -1:
    case max[i] == i-1:
      tree.Modify(i, i, 1)
    default:
      tree.Modify(i, i, tree.Query(max[i]+1, i-1)+1)
    }
  }
  pri(tree.Query(0, n-1))
  endl()
  w.Flush()
}

package main

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

var sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
var w *bufio.Writer = bufio.NewWriter(os.Stdout)

func ni() int {
  sc.Scan()
  ans, _ := strconv.Atoi(sc.Text())
  return ans
}

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

func pri(n int)    { w.WriteString(strconv.Itoa(n)) }
func prll(n int64) { w.WriteString(strconv.FormatInt(n, 10)) }
func sp()          { w.WriteByte(' ') }
func endl()        { w.WriteByte('\n') }

func main() {
  sc.Split(bufio.ScanWords)
  n := ni()
  a := make([]int, n)
  max := make([]int, n)
  for i := 0; i < n; i++ {
    a[i] = ni()
    max[i] = -1
  }
  stack := make([]int, n)
  cur := 0
  for i := n - 1; i >= 0; i-- {
    if cur == 0 {
      stack[cur] = i
      cur++
    } else {
      for cur > 0 && a[stack[cur-1]] < a[i] {
        max[stack[cur-1]] = i
        cur--
      }
      stack[cur] = i
      cur++
    }
  }
  t := make([]int, n*4)
  var build func(a []int, v, tl, tr int)
  var getmax func(v, tl, tr, l, r int) int
  var update func(v, tl, tr, pos, new_val int)
  var mi, ma func(i, j int) int

  mi = func(i, j int) int {
    if i < j {
      return i
    }
    return j
  }
  ma = func(i, j int) int {
    if i >= j {
      return i
    }
    return j
  }

  build = func(aa []int, v, tl, tr int) {
    if tl == tr {
      t[v] = aa[tl]
    } else {
      tm := (tl + tr) / 2
      build(aa, v*2, tl, tm)
      build(aa, v*2+1, tm+1, tr)
      if t[v*2] >= t[v*2+1] {
        t[v] = t[v*2]
      } else {
        t[v] = t[v*2+1]
      }
    }
  }

  getmax = func(v, tl, tr, l, r int) int {
    if l > r {
      return 0
    } else if l == tl && r == tr {
      return t[v]
    }
    tm := (tl + tr) / 2
    return ma(getmax(v*2, tl, tm, l, mi(r, tm)), getmax(v*2+1, tm+1, tr, ma(l, tm+1), r))
  }

  update = func(v, tl, tr, pos, new_val int) {
    if tl == tr {
      t[v] = new_val
    } else {
      tm := (tl + tr) / 2
      if pos <= tm {
        update(v*2, tl, tm, pos, new_val)
      } else {
        update(v*2+1, tm+1, tr, pos, new_val)
      }
      t[v] = ma(t[v*2], t[v*2+1])
    }
  }

  maxs := make([]int, n)
  build(maxs, 1, 0, n-1)
  for i := 0; i < n; i++ {
    if max[i] == -1 {
      update(1, 0, n-1, i, 0)
    } else if max[i] == i-1 {
      update(1, 0, n-1, i, 1)
    } else {
      update(1, 0, n-1, i, getmax(1, 0, n-1, max[i]+1, i-1)+1)
    }
  }
  pri(getmax(1, 0, n-1, 0, n-1))
  endl()
  // for i := 0; i < n; i++ {
  //   pri(getmax(1, 0, n-1, i, i))
  //   sp()
  // }
  // endl()
  w.Flush()
}

package main

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

var sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
var w *bufio.Writer = bufio.NewWriter(os.Stdout)

func ni() int {
  sc.Scan()
  ans, _ := strconv.Atoi(sc.Text())
  return ans
}

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

func pri(n int)    { w.WriteString(strconv.Itoa(n)) }
func prll(n int64) { w.WriteString(strconv.FormatInt(n, 10)) }
func sp()          { w.WriteByte(' ') }
func endl()        { w.WriteByte('\n') }

type Interface interface {
  Len() int
  GetInitValue(i int) int
  GetNeutralValue() int
  GetNeutralDelta() int
  CombineValues(value1, value2 int) int
  CombineDeltas(delta1, delta2 int) int
  CombineValueAndDelta(value, delta int, length int) int
}

type MaxWithRangeAdd []int

func (tr MaxWithRangeAdd) Len() int               { return len(tr) }
func (tr MaxWithRangeAdd) GetInitValue(i int) int { return tr[i] }
func (tr MaxWithRangeAdd) GetNeutralValue() int   { return -2147483648 }
func (tr MaxWithRangeAdd) GetNeutralDelta() int   { return 0 }

func (tr MaxWithRangeAdd) CombineValues(value1, value2 int) int {
  v1, v2 := value1, value2
  if v1 >= v2 {
    return v1
  }
  return v2
}

func (tr MaxWithRangeAdd) CombineDeltas(delta1, delta2 int) int {
  return delta1 + delta2
}

func (tr MaxWithRangeAdd) CombineValueAndDelta(value, delta int, length int) int {
  return value + delta
}

type SegmentTree struct {
  funcs  Interface
  value  []int
  delta  []int
  length []int
}

func NewSegmentTree(funcs Interface) *SegmentTree {
  tree := new(SegmentTree)
  tree.funcs = funcs
  n := funcs.Len()
  tree.value = make([]int, n*2)
  tree.delta = make([]int, n*2)
  tree.length = make([]int, n*2)
  for i := 0; i < n; i++ {
    tree.value[i+n] = funcs.GetInitValue(i)
  }
  for i := 0; i < n*2; i++ {
    tree.delta[i] = funcs.GetNeutralDelta()
    tree.length[i] = 1
  }
  for i := n*2 - 1; i > 1; i -= 2 {
    tree.value[i>>1] = funcs.CombineValues(tree.value[i], tree.value[i^1])
    tree.length[i>>1] = tree.length[i] + tree.length[i^1]
  }
  return tree
}

func (tree *SegmentTree) applyDelta(i int, delta int) {
  tree.value[i] = tree.funcs.CombineValueAndDelta(tree.value[i], delta, tree.length[i])
  tree.delta[i] = tree.funcs.CombineDeltas(tree.delta[i], delta)
}

func (tree *SegmentTree) pushDelta(i int) {
  d := 0
  for ; i>>uint(d) > 0; d++ {
  }
  for d -= 2; d >= 0; d-- {
    x := i >> uint(d)
    tree.applyDelta(x, tree.delta[x>>1])
    tree.applyDelta(x^1, tree.delta[x>>1])
    tree.delta[x>>1] = tree.funcs.GetNeutralDelta()
  }
}

func (tree *SegmentTree) Modify(a, b int, delta int) {
  a += len(tree.value) >> 1
  b += len(tree.value) >> 1
  tree.pushDelta(a)
  tree.pushDelta(b)
  ta, tb := -1, -1
  for ; a <= b; a, b = (a+1)>>1, (b-1)>>1 {
    if a&1 != 0 {
      tree.applyDelta(a, delta)
      if ta == -1 {
        ta = a
      }
    }
    if b&1 == 0 {
      tree.applyDelta(b, delta)
      if tb == -1 {
        tb = b
      }
    }
  }
  for i := ta; i > 1; i >>= 1 {
    tree.value[i>>1] = tree.funcs.CombineValues(tree.value[i], tree.value[i^1])
  }
  for i := tb; i > 1; i >>= 1 {
    tree.value[i>>1] = tree.funcs.CombineValues(tree.value[i], tree.value[i^1])
  }
}

func (tree *SegmentTree) Query(a, b int) int {
  a += len(tree.value) >> 1
  b += len(tree.value) >> 1
  tree.pushDelta(a)
  tree.pushDelta(b)
  res := tree.funcs.GetNeutralValue()
  for ; a <= b; a, b = (a+1)>>1, (b-1)>>1 {
    if a&1 != 0 {
      res = tree.funcs.CombineValues(res, tree.value[a])
    }
    if b&1 == 0 {
      res = tree.funcs.CombineValues(res, tree.value[b])
    }
  }
  return res
}

func main() {
  sc.Split(bufio.ScanWords)
  n := ni()
  a := make([]int, n)
  max := make([]int, n)
  for i := 0; i < n; i++ {
    a[i] = ni()
    max[i] = -1
  }
  stack := make([]int, n)
  cur := 0
  for i := n - 1; i >= 0; i-- {
    if cur != 0 {
      for cur > 0 && a[stack[cur-1]] < a[i] {
        max[stack[cur-1]] = i
        cur--
      }
    }
    stack[cur] = i
    cur++
  }
  tree := NewSegmentTree(MaxWithRangeAdd(make([]int, n)))

  for i := 0; i < n; i++ {
    switch {
    case max[i] == -1:
    case max[i] == i-1:
      tree.Modify(i, i, 1)
    default:
      tree.Modify(i, i, tree.Query(max[i]+1, i-1)+1)
    }
  }
  pri(tree.Query(0, n-1))
  endl()
  w.Flush()
}

package main

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

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

	var n int
	Fscan(in, &n)
	arr := make([]int, n)
	for i := range arr {
		Fscan(in, &arr[i])
	}

	ans := make([]int, n)
	posStack := []int{}
	for i := n - 1; i >= 0; i-- {
		cnt := 0
		for len(posStack) > 0 && arr[posStack[len(posStack)-1]] < arr[i] {
			var pos int
			posStack, pos = posStack[:len(posStack)-1], posStack[len(posStack)-1]
			cnt++
			if ans[pos] > cnt {
				cnt = ans[pos]
			}
			ans[i] = cnt
		}
		posStack = append(posStack, i)
	}
	Fprint(out, ans[0])
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol320D(reader io.Reader, writer io.Writer) {
	max := func(vals ...int) int {
		ans := vals[0]
		for _, val := range vals[1:] {
			if val > ans {
				ans = val
			}
		}
		return ans
	}

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

	var n int
	Fscan(in, &n)
	arr := make([]int, n)
	for i := range arr {
		Fscan(in, &arr[i])
	}

	ans := make([]int, n)
	stack := []int{}
	for i := n - 1; i >= 0; i-- {
		cnt := 0
		for len(stack) > 0 && arr[stack[len(stack)-1]] < arr[i] {
			var pos int
			stack, pos = stack[:len(stack)-1], stack[len(stack)-1]
			cnt++
			ans[i] = max(cnt, ans[pos])
		}
		stack = append(stack, i)
	}
	Fprint(out, max(ans...))
}

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


Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?

The first line contains the only integer n (0 ≤ n ≤ 10100000). It is guaranteed that n doesn't contain any leading zeroes.

Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.

NoteIn the first sample the number already is one-digit — Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.

package main

import (
	"fmt"
)

var ps = fmt.Printf

func main() {
	var s string
	fmt.Scanf("%s\n", &s)
	if len(s) == 1 {
		ps("%d\n", 0)
		return
	}
	sum := ss(s)
	count := 1
	for lens(sum) > 1 {
		sum = lenss(sum)
		count++
	}
	ps("%d", count)
}
func ss(s string) int {
	sum := 0
	for i := 0; i < len(s); i++ {
		sum = sum + (int(s[i]) - 48)
	}
	return sum
}

func lens(n int) int {
	dcount := 0
	for n > 0 {
		dcount++
		n = n / 10
	}
	return dcount
}

func lenss(n int) int {
	sum := 0
	for n > 0 {
		sum += n % 10
		n = n / 10
	}
	return sum
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var val string
	fmt.Scanf("%s", &val)
	// fmt.Println(val)
	count := 0
	for len(val) > 1 {
		sum := 0
		// fmt.Println("hi")
		for j := 0; j < len(val); j++ {
			sum += int(val[j] - '0')

		}
		count++
		val = strconv.Itoa(sum)
	}
	fmt.Printf("%v\n", count)

}

package main
import (
	"fmt"
)
func main() {
	var i,a,k,s,d int
	var z string
	fmt.Scan(&z)
	a=len(z)
	flag1:=false
	flag2:=false
	if a<2 {
		fmt.Println("0")
		flag1=true
	}
	for i=0;i<a;i++ {
		s+=(int(z[i])-48)
	}
	k++
	if s<10 && flag1==false{
		fmt.Println("1")
		flag2=true
	}
	for ;s>=10; {
		d=s
		k++
		s=0
		for ;d>=10; {
			s+=(d%10)
			d/=10
		}
		s+=d
	}
	if flag1==false && flag2==false {
		fmt.Println(k)
	}
}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    var s string
    fmt.Fscan(reader,&s)
    ans := 0
    if len(s) > 1 {
        n := 0
        for _, v := range s {
            n += int(v-'0')
        }
        ans++
        for n/10 != 0 {
            u := n
            n = 0
            for u != 0 {
                n += u%10
                u /= 10
            }
            ans++
        }
    }
    fmt.Println(ans)
}

package main

import "fmt"

func main() {
	var n string
	fmt.Scanln(&n)
	var c = 0
	for {
		if len(n) <= 1 {
			break
		}
		var s = 0
		for i := 0; i < len(n); i++ {
			s += int(n[i] - '0')
		}
		c++
		n = fmt.Sprint(s)
	}
	fmt.Println(c)
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var val string
	fmt.Scanf("%s", &val)
	// fmt.Println(val)
	count := 0
	for len(val) > 1 {
		sum := 0
		// fmt.Println("hi")
		for j := 0; j < len(val); j++ {
			sum += int(val[j] - '0')

		}
		count++
		val = strconv.Itoa(sum)
	}
	println(count)

}

package main
import (
	"fmt"
)
func main() {
	var i,a,k,s,d int
	var z string
	fmt.Scan(&z)
	a=len(z)
	flag:=false
	if a<2 {
		fmt.Println("0")
		flag=true
	}
	for i=0;i<a;i++ {
		s+=(int(z[i])-48)
	}
	k++
	if s<10 {
		fmt.Println("1")
		flag=true
	}
	for ;s>=10; {
		d=s
		k++
		s=0
		for ;d>=10; {
			s+=(d%10)
			d/=10
		}
		s+=d
	}
	if flag==false {
		fmt.Println(k)
	}
}


You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.

For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.

NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.

package main

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

const N  = 100010
var nt, n int
var dp[N] int64
var L, R int64

func searchValue(pos int64) int {
	if pos == int64(n) * int64(n - 1) + 1 {
		return 1
	}
	var l = 1
	var r = n
	var ret = 0

	for l <= r {
		var mid = (l + r) >> 1
		if dp[mid] >= pos {
			ret = mid
			r = mid - 1
		} else{
			l = mid + 1
		}
	}

	pos -= dp[ret - 1]

	if pos % 2 == 1 {
		return ret
	}
	return ret + int(pos / 2)
}

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	fmt.Fscanf(reader, "%d\n", &nt)
	for kk := 1; kk <= nt; kk++ {
		fmt.Fscanf(reader, "%d %d %d\n", &n, &L, &R)
		dp[0] = 0
		for i := 1; i < n; i++ {
			dp[i] = dp[i - 1] + 2 * int64(n - i)
		}
		dp[n] = dp[n - 1] + 1

		for L <= R {
			var z = searchValue(L)
			fmt.Fprintf(writer, "%d ", z)
			L++
		}

		fmt.Fprintf(writer, "\n")
	}

}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n, l, r := reader.NextInt64(), reader.NextInt64(), reader.NextInt64()
		sol(n, l, r)
	}
}

func sol(n, l, r int64) {
    currSub := int64(1)
    currRangeLower := int64(0)
    currRangeUpper := (n-currSub)*2
    for i := l; i <= r; i++ {
        if i == n*(n-1)+1 {
            // should be the last value
            writer.Printf("%d ", 1)
            continue
        }
        for i > currRangeUpper {
            currSub++
            currRangeLower = currRangeUpper
            currRangeUpper += (n-currSub)*2
        }
        if i&1 == 1 {
            writer.Printf("%d ", currSub)
        } else {
            diff := i-currRangeLower
            writer.Printf("%d ", currSub + diff/2)
        }
    }
    writer.Printf("\n")
}