You are given a binary matrix $$$A$$$ of size $$$n \times n$$$. Rows are numbered from top to bottom from $$$1$$$ to $$$n$$$, columns are numbered from left to right from $$$1$$$ to $$$n$$$. The element located at the intersection of row $$$i$$$ and column $$$j$$$ is called $$$A_{ij}$$$. Consider a set of $$$4$$$ operations:  Cyclically shift all rows up. The row with index $$$i$$$ will be written in place of the row $$$i-1$$$ ($$$2 \le i \le n$$$), the row with index $$$1$$$ will be written in place of the row $$$n$$$.  Cyclically shift all rows down. The row with index $$$i$$$ will be written in place of the row $$$i+1$$$ ($$$1 \le i \le n - 1$$$), the row with index $$$n$$$ will be written in place of the row $$$1$$$.  Cyclically shift all columns to the left. The column with index $$$j$$$ will be written in place of the column $$$j-1$$$ ($$$2 \le j \le n$$$), the column with index $$$1$$$ will be written in place of the column $$$n$$$.  Cyclically shift all columns to the right. The column with index $$$j$$$ will be written in place of the column $$$j+1$$$ ($$$1 \le j \le n - 1$$$), the column with index $$$n$$$ will be written in place of the column $$$1$$$.     The $$$3 \times 3$$$ matrix is shown on the left before the $$$3$$$-rd operation is applied to it, on the right — after. You can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order.After that, you can perform an arbitrary (possibly zero) number of new xor-operations:  Select any element $$$A_{ij}$$$ and assign it with new value $$$A_{ij} \oplus 1$$$. In other words, the value of $$$(A_{ij} + 1) \bmod 2$$$ will have to be written into element $$$A_{ij}$$$. Each application of this xor-operation costs one burl. Note that the $$$4$$$ shift operations — are free. These $$$4$$$ operations can only be performed before xor-operations are performed.Output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, $$$A_{ij} = 1$$$ if $$$i = j$$$ and $$$A_{ij} = 0$$$ otherwise).

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. The descriptions of the test cases follow. Before each test case, an empty line is written in the input. The first line of each test case contains a single number $$$n$$$ ($$$1 \le n \le 2000$$$) This is followed by $$$n$$$ lines, each containing exactly $$$n$$$ characters and consisting only of zeros and ones. These lines describe the values in the elements of the matrix. It is guaranteed that the sum of $$$n^2$$$ values over all test cases does not exceed $$$4 \cdot 10^6$$$.

For each test case, output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. In other words, print the minimum number of xor-operations it will take after applying cyclic shifts to the matrix for the $$$A$$$ matrix to become unitary.

NoteIn the first test case, you can do the following: first, shift all the rows down cyclically, then the main diagonal of the matrix will contain only "1". Then it will be necessary to apply xor-operation to the only "1" that is not on the main diagonal.In the second test case, you can make a unitary matrix by applying the operation $$$2$$$ — cyclic shift of rows upward twice to the matrix.

package main

import "fmt"
import "bufio"
import "os"
// import "sort"

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

	var t int

	fmt.Fscan(rd, &t)

	for test := 0; test < t; test++ {
		var n int

		fmt.Fscan(rd, &n)

		a := make([][]int, n)

		cnt := make([]int, n)

		total := 0

		normalize := func (x int) int {
			if x < 0 {
				return x + n
			} else {
				return x
			}
		}

		for i := 0; i < n; i++ {
			var temp string
			fmt.Fscan(rd, &temp)
			a[i] = make([]int, n)
			for j := 0; j < n; j++ {
				if temp[j] == '0' {
					a[i][j] = 0
				} else {
					a[i][j] = 1
				}
				total += a[i][j]
				cnt[normalize(i - j)] += a[i][j]
			}
		}

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

		ans := n * n

		for i := 0; i < n; i++ {
			cur := 0
			cur = n - cnt[i]
			cur += (total - cnt[i])
			ans = min(ans, cur)
		}

		fmt.Printf("%v\n", ans)
	}
}

package main

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

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

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

	c, n := 0, 0
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		matrix := make([]string, n*3)
		presum := make([][]int, n*3)
		total_onecnt := 0
		for i := range presum {
			presum[i] = make([]int, n*3)
		}
		for i := 0; i < n; i++ {
			tmp_str := ""
			str := ""
			Fscan(in, &tmp_str)
			for _, ch := range tmp_str {
				if ch == '1' {
					total_onecnt++
				}
			}
			for j := 0; j < 3; j++ {
				str += tmp_str
			}
			matrix[i] = str
		}
		for i := n; i < n*3; i++ {
			matrix[i] = matrix[i%n]
		}

		//预处理 presum[i][j]表示该点 主要线上累计1的个数
		for x, str := range matrix {
			for y, ch := range str {
				if x == 0 || y == 0 {
					if matrix[x][y] == '1' {
						presum[x][y] = 1
					}
				} else if ch == '1' {
					presum[x][y] = presum[x-1][y-1] + 1
				} else if ch == '0' {
					presum[x][y] = presum[x-1][y-1]
				}
			}
		}
		max_onecnt := 0
		//使用前缀和方式求解
		for x := n - 1; x < n*3; x++ {
			for y := 0; y < n*3; y++ {
				k := 0
				if x >= n && y >= n {
					k = presum[x-n][y-n]
				}
				max_onecnt = max(max_onecnt, presum[x][y]-k)

			}
		}
		need := n - max_onecnt
		ans := need + (total_onecnt + need - n)
		Fprintf(out, "%d\n", ans)
	}
}

func max(i, j int) int {
	if i > j {
		return i
	}
	return j
}

package main

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

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	fmt.Fscan(in, &n)
	strs := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &strs[i])
	}
	cnt := make([]int, n)
	sum := 0
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if strs[i][j] == '1' {
				sum++
				cnt[(i-j+n)%n]++
			}
		}
	}
	ans := int(1e9)
	for _, v := range cnt {
		ans = min(ans, sum-v+n-v)
	}
	fmt.Fprintln(out, ans)
}

func abs(a int) int {
	if a > 0 {
		return a
	}
	return -a
}
func sum(a, b int64) int64 {
	return (b + a) * (b - a + 1) / 2
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	fmt.Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

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

	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		a := make([]string, n)
		for i := range a {
			Fscan(in, &a[i])
			a[i] += a[i]
		}
		a = append(a, a...)
		m := n * 2
		s := make([][]int, m+1)
		s[0] = make([]int, m+1)
		for i, r := range a {
			s[i+1] = make([]int, m+1)
			for j, v := range r {
				s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + int(v&1)
			}
		}

		ans := int(1e9)
		for k := n + 1; k < n*3; k++ {
			l, r := max(0, m-k), min(m-1, m*2-k-1)
			for i, j, c1 := k+l-m, l, 0; j <= r; j++ {
				c1 += int(a[i][j] & 1)
				if j >= l+n-1 {
					x, y := i-n, j-n
					if j >= l+n {
						c1 -= int(a[x][y] & 1)
					}
					ans = min(ans, s[i+1][j+1]-s[i+1][y+1]-s[x+1][j+1]+s[x+1][y+1]-2*c1+n)
				}
				i++
			}
		}
		Fprintln(out, ans)
	}
}

func main() { CF1660E(os.Stdin, os.Stdout) }
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func max(a, b int) int {
	if b > a {
		return b
	}
	return a
}

package main

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

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

	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		a := make([]string, n)
		for i := range a {
			Fscan(in, &a[i])
			a[i] += a[i]
		}
		a = append(a, a...)
		n *= 2
		sum := make([][]int, n+1)
		sum[0] = make([]int, n+1)
		for i, r := range a {
			sum[i+1] = make([]int, n+1)
			for j, v := range r {
				sum[i+1][j+1] = sum[i+1][j] + sum[i][j+1] - sum[i][j] + int(v&1)
			}
		}

		ans := int(1e9)
		for s := n/2 + 1; s < n/2*3; s++ {
			l := max(0, n-s)
			r := min(n-1, n*2-s-1)
			c1 := 0
			for i, j := s+l-n, l; j <= r; j++ {
				c1 += int(a[i][j] & 1)
				if j >= l+n/2-1 {
					x, y := i-n/2, j-n/2
					if j >= l+n/2 {
						c1 -= int(a[x][y] & 1)
					}
					x++
					y++
					s1 := sum[i+1][j+1] - sum[i+1][y] - sum[x][j+1] + sum[x][y]
					ans = min(ans, s1-2*c1+n/2)
				}
				i++
			}
		}
		Fprintln(out, ans)
	}
}

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

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

package main

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

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

func run(r io.Reader, w io.Writer) {
	in := bufio.NewReader(r)
	out := bufio.NewWriter(w)

	defer out.Flush()

	var T, n int
	for fmt.Fscan(in, &T); T > 0; T-- {
		fmt.Fscan(in, &n)
		arr := make([]string, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &arr[i])
		}
		fmt.Fprintln(out, process(arr))
	}
}

func process(arr []string) int {
	totalCount, maxCount := 0, 0
	n := len(arr)
	for i := 0; i < n; i++ {
		j := i
		tmpCount := 0
		for k := 0; k < n; k++ {
			if arr[k][j] == '1' {
				tmpCount++
				totalCount++
			}
			j = (j + 1) % n
		}
		maxCount = max(maxCount, tmpCount)
	}
	return totalCount + n - 2*maxCount
}

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

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 0
	fmt.Fscan(in, &t)
	for ii := 0; ii < t; ii++ {
		n:=0
		fmt.Fscan(in, &n)
		grids:= make([]string, n)
		ones:=0
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &grids[i])
			for j := 0; j < n; j++ {
				if grids[i][j]=='1'{
					ones++
				}
			}
		}
		max:=0
		for i := 0; i < n; i++ {
			temp:=i
			cnt:=0
			for j := 0; j < n; j++ {
				if grids[temp][j]=='1'{
					cnt++
				}
				temp = (temp+1)%n
			}
			if cnt > max{
				max = cnt
			}
		}
		fmt.Fprintln(out, ones-max + n-max)
	}
}

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

package main

import "fmt"
import "bufio"
import "os"
// import "sort"

func main() {
	rd := bufio.NewReader(os.Stdin)
	wr := bufio.NewWriter(os.Stdout)

	var t int

	fmt.Fscan(rd, &t)

	for test := 0; test < t; test++ {
		var n int

		fmt.Fscan(rd, &n)

		a := make([][]int, n)

		cnt := make([]int, n)

		total := 0

		normalize := func (x int) int {
			if x < 0 {
				return x + n
			} else {
				return x
			}
		}

		for i := 0; i < n; i++ {
			var temp string
			fmt.Fscan(rd, &temp)
			a[i] = make([]int, n)
			for j := 0; j < n; j++ {
				if temp[j] == '0' {
					a[i][j] = 0
				} else {
					a[i][j] = 1
				}
				total += a[i][j]
				cnt[normalize(i - j)] += a[i][j]
			}
		}

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

		ans := n * n

		for i := 0; i < n; i++ {
			cur := 0
			cur = n - cnt[i]
			cur += (total - cnt[i])
			ans = min(ans, cur)
		}

		fmt.Fprintf(wr, "%v\n", ans)
	}
}

package main

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

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

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

	c, n := 0, 0
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		matrix := make([]string, n*3)
		presum := make([][]int, n*3)
		total_onecnt := 0
		for i := range presum {
			presum[i] = make([]int, n*3)
		}
		for i := 0; i < n; i++ {
			tmp_str := ""
			str := ""
			Fscan(in, &tmp_str)
			for _, ch := range tmp_str {
				if ch == '1' {
					total_onecnt++
				}
			}
			for j := 0; j < 3; j++ {
				str += tmp_str
			}
			matrix[i] = str
		}
		for i := n; i < n*3; i++ {
			matrix[i] = matrix[i%3]
		}

		//预处理 presum[i][j]表示该点 主要线上累计1的个数
		for x, str := range matrix {
			for y, ch := range str {
				if x == 0 || y == 0 {
					if matrix[x][y] == '1' {
						presum[x][y] = 1
					}
				} else if ch == '1' {
					presum[x][y] = presum[x-1][y-1] + 1
				} else {
					presum[x][y] = presum[x-1][y-1]
				}
			}
		}
		max_onecnt := 0
		//使用前缀和方式求解
		for x := n - 1; x < n*3; x++ {
			for y := 0; y < n*3; y++ {
				k := 0
				if x >= n && y >= n {
					k = presum[x-n][y-n]
				}
				max_onecnt = max(max_onecnt, presum[x][y]-k)

			}
		}
		need := n - max_onecnt
		ans := need + (total_onecnt + need - n)
		Fprintf(out, "%d\n", ans)
	}
}

func max(i, j int) int {
	if i > j {
		return i
	}
	return j
}

package main

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

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

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

	c, n := 0, 0
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		a := make([]string, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		x, y := make([]bool, n), make([]bool, n)
		one := 0
		for i, str := range a {
			for j, ch := range str {
				if ch == '1' {
					x[i] = true
					y[j] = true
					one++
				}
			}
		}
		ans := 0
		for i := 0; i < n; i++ {
			if !(x[i] && y[i]) { //不具备4钟操作使得主要列上值为1，需要XOR运算
				ans++
				one++
			}
		}
		ans += one - n
		Fprintf(out, "%d\n", ans)
	}
}

package main

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

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	fmt.Fscan(in, &n)
	strs := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &strs[i])
	}
	cnt := make([]int, n)
	sum := 0
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if strs[i][j] == '1' {
				sum++
				cnt[(i-j+n)%n]++
			}
		}
	}
	ans := int(1e9)
	for _, v := range cnt {
		ans = min(ans, sum-v+n-v)
	}
	fmt.Fprintln(out, ans)
}

func abs(a int) int {
	if a > 0 {
		return a
	}
	return -a
}
func sum(a, b int64) int64 {
	return (b + a) * (b - a + 1) / 2
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func gcd(a, b int) int {
	if a%b == 0 {
		return b
	}
	return gcd(b, a%b)
}

func main() {
	stdin, _ := os.Open("/project/go/algo/input")
	//stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	fmt.Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}


Arkady's code contains $$$n$$$ variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code.He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names.A string $$$a$$$ is a prefix of a string $$$b$$$ if you can delete some (possibly none) characters from the end of $$$b$$$ and obtain $$$a$$$.Please find this minimum possible total length of new names.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of variables. The next $$$n$$$ lines contain variable names, one per line. Each name is non-empty and contains only lowercase English letters. The total length of these strings is not greater than $$$10^5$$$. The variable names are distinct.

Print a single integer — the minimum possible total length of new variable names.

NoteIn the first example one of the best options is to shorten the names in the given order as "cod", "co", "c".In the second example we can shorten the last name to "aac" and the first name to "a" without changing the other names.

package main

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

type maxHeap []int

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

func (m *maxHeap) Push(x interface{}) {
	*m = append(*m, x.(int))
}

func (m *maxHeap) Pop() interface{} {
	old := *m
	n := len(old)
	x := old[n-1]
	*m = old[:n-1]
	return x
}

type node struct {
	children map[byte]*node
	depth    int
	depths   maxHeap
	occupied bool
}

func newNode(depth int) *node {
	return &node{
		children: make(map[byte]*node),
		depth:    depth,
	}
}

func (n *node) consolidate() {
	n.depths = maxHeap{}
	for _, child := range n.children {
		child.consolidate()
		n.depths = append(n.depths, child.depths...)
		child.depths = nil
	}
	if n.occupied {
		n.depths = append(n.depths, n.depth)
		heap.Init(&n.depths)
	} else if n.depth > 0 && len(n.depths) > 0 {
		heap.Init(&n.depths)
		heap.Pop(&n.depths)
		heap.Push(&n.depths, n.depth)
	}
}

func (n *node) add(suffix string) {
	if len(suffix) == 0 {
		n.occupied = true
		n.depths = maxHeap{n.depth}
	} else {
		child, ok := n.children[suffix[0]]
		if !ok {
			child = newNode(n.depth + 1)
			n.children[suffix[0]] = child
		}
		child.add(suffix[1:])
	}
}

func main() {
	const maxCapacity = 1000000

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, maxCapacity), maxCapacity)

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

	trie := newNode(0)
	for i := 0; i < n; i++ {
		scanner.Scan()
		trie.add(scanner.Text())
	}
	trie.consolidate()

	total := 0
	for _, depth := range trie.depths {
		total += depth
	}
	fmt.Println(total)
}

package main

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

type maxHeap []int

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

func (m *maxHeap) Push(x interface{}) {
	*m = append(*m, x.(int))
}

func (m *maxHeap) Pop() interface{} {
	old := *m
	n := len(old)
	x := old[n-1]
	*m = old[:n-1]
	return x
}

type node struct {
	depth    int
	occupied bool
	children map[byte]*node
	depths   maxHeap
}

func newNode(depth int) *node {
	return &node{
		depth:    depth,
		children: make(map[byte]*node),
	}
}

func (n *node) consolidate() {
	if n == nil {
		return
	}
	n.depths = maxHeap{}
	for _, child := range n.children {
		child.consolidate()
		n.depths = append(n.depths, child.depths...)
		child.depths = nil
	}
	if n.occupied {
		n.depths = append(n.depths, n.depth)
		heap.Init(&n.depths)
	} else if n.depth > 0 && len(n.depths) > 0 {
		heap.Init(&n.depths)
		heap.Pop(&n.depths)
		heap.Push(&n.depths, n.depth)
	}
}

func (n *node) add(suffix string) {
	if len(suffix) == 0 {
		n.occupied = true
		n.depths = maxHeap{n.depth}
	} else {
		child, ok := n.children[suffix[0]]
		if !ok {
			child = newNode(n.depth + 1)
			n.children[suffix[0]] = child
		}
		child.add(suffix[1:])
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	const maxCapacity = 1000000
	buf := make([]byte, maxCapacity)
	scanner.Buffer(buf, maxCapacity)

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

	trie := newNode(0)
	for i := 0; i < n; i++ {
		scanner.Scan()
		trie.add(scanner.Text())
	}
	trie.consolidate()
	total := 0
	for _, depth := range trie.depths {
		total += depth
	}
	fmt.Println(total)
}

package main

import (
	"container/heap"
	"fmt"
)

type maxHeap []int

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

func (m *maxHeap) Push(x interface{}) {
	*m = append(*m, x.(int))
}

func (m *maxHeap) Pop() interface{} {
	old := *m
	n := len(old)
	x := old[n-1]
	*m = old[:n-1]
	return x
}

type node struct {
	children map[byte]*node
	depth    int
	depths   maxHeap
	occupied bool
}

func newNode(depth int) *node {
	return &node{
		children: make(map[byte]*node),
		depth:    depth,
	}
}

func (n *node) consolidate() {
	n.depths = maxHeap{}
	for _, child := range n.children {
		child.consolidate()
		n.depths = append(n.depths, child.depths...)
		child.depths = nil
	}
	if n.occupied {
		n.depths = append(n.depths, n.depth)
		heap.Init(&n.depths)
	} else if n.depth > 0 && len(n.depths) > 0 {
		heap.Init(&n.depths)
		heap.Pop(&n.depths)
		heap.Push(&n.depths, n.depth)
	}
}

func (n *node) add(suffix string) {
	if len(suffix) == 0 {
		n.occupied = true
		n.depths = maxHeap{n.depth}
	} else {
		child, ok := n.children[suffix[0]]
		if !ok {
			child = newNode(n.depth + 1)
			n.children[suffix[0]] = child
		}
		child.add(suffix[1:])
	}
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	trie := newNode(0)
	for i := 0; i < n; i++ {
		var s string
		fmt.Scanf("%s\n", &s)
		trie.add(s)
	}
	trie.consolidate()
	total := 0
	for _, depth := range trie.depths {
		total += depth
	}
	fmt.Println(total)
}

package main

import (
	"container/heap"
	"fmt"
)

type maxHeap []int

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

func (m *maxHeap) Push(x interface{}) {
	*m = append(*m, x.(int))
}

func (m *maxHeap) Pop() interface{} {
	old := *m
	n := len(old)
	x := old[n-1]
	*m = old[:n-1]
	return x
}

type node struct {
	children map[byte]*node
	depth    int
	depths   maxHeap
	occupied bool
}

func newNode(depth int) *node {
	return &node{
		children: make(map[byte]*node),
		depth:    depth,
	}
}

func (n *node) consolidate() {
	n.depths = maxHeap{}
	for _, child := range n.children {
		child.consolidate()
		n.depths = append(n.depths, child.depths...)
		child.depths = nil
	}
	if n.occupied {
		n.depths = append(n.depths, n.depth)
		heap.Init(&n.depths)
	} else if n.depth > 0 && len(n.depths) > 0 {
		heap.Init(&n.depths)
		heap.Pop(&n.depths)
		heap.Push(&n.depths, n.depth)
	}
}

func (n *node) add(suffix string) {
	if len(suffix) == 0 {
		n.occupied = true
		n.depths = maxHeap{n.depth}
	} else {
		child, ok := n.children[suffix[0]]
		if !ok {
			child = newNode(n.depth + 1)
			n.children[suffix[0]] = child
		}
		child.add(suffix[1:])
	}
}

func main() {
	var n int
	fmt.Scanf("%d", &n)
	trie := newNode(0)
	for i := 0; i < n; i++ {
		var s string
		fmt.Scanf("%s", &s)
		trie.add(s)
	}
	trie.consolidate()
	total := 0
	for _, depth := range trie.depths {
		total += depth
	}
	fmt.Println(total)
}

package main

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

type maxHeap []int

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

func (m *maxHeap) Push(x interface{}) {
	*m = append(*m, x.(int))
}

func (m *maxHeap) Pop() interface{} {
	old := *m
	n := len(old)
	x := old[n-1]
	*m = old[:n-1]
	return x
}

type node struct {
	depth    int
	occupied bool
	children map[byte]*node
	depths   maxHeap
}

func newNode(depth int) *node {
	return &node{
		depth:    depth,
		children: make(map[byte]*node),
	}
}

func (n *node) consolidate() {
	if n == nil {
		return
	}
	n.depths = maxHeap{}
	for _, child := range n.children {
		child.consolidate()
		n.depths = append(n.depths, child.depths...)
		child.depths = nil
	}
	if n.occupied {
		n.depths = append(n.depths, n.depth)
		heap.Init(&n.depths)
	} else if n.depth > 0 && len(n.depths) > 0 {
		heap.Init(&n.depths)
		heap.Pop(&n.depths)
		heap.Push(&n.depths, n.depth)
	}
}

func (n *node) add(suffix string) {
	if len(suffix) == 0 {
		n.occupied = true
		n.depths = maxHeap{n.depth}
	} else {
		child, ok := n.children[suffix[0]]
		if !ok {
			child = newNode(n.depth + 1)
			n.children[suffix[0]] = child
		}
		child.add(suffix[1:])
	}
}

func main() {
	trie := newNode(0)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < n; i++ {
		scanner.Scan()
		trie.add(scanner.Text())
	}
	trie.consolidate()
	total := 0
	for _, depth := range trie.depths {
		total += depth
	}
	fmt.Println(total)
}

package main

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

type maxHeap []int

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

func (m *maxHeap) Push(x interface{}) {
	*m = append(*m, x.(int))
}

func (m *maxHeap) Pop() interface{} {
	old := *m
	n := len(old)
	x := old[n-1]
	*m = old[:n-1]
	return x
}

type node struct {
	depth    int
	occupied bool
	children map[byte]*node
	depths   maxHeap
}

func newNode(depth int) *node {
	return &node{
		depth:    depth,
		children: make(map[byte]*node),
	}
}

func (n *node) consolidate() {
	if n == nil {
		return
	}
	n.depths = maxHeap{}
	for _, child := range n.children {
		child.consolidate()
		n.depths = append(n.depths, child.depths...)
		child.depths = nil
	}
	if n.occupied {
		n.depths = append(n.depths, n.depth)
		heap.Init(&n.depths)
	} else if n.depth > 0 && len(n.depths) > 0 {
		heap.Init(&n.depths)
		heap.Pop(&n.depths)
		heap.Push(&n.depths, n.depth)
	}
}

func (n *node) add(suffix string) {
	if len(suffix) == 0 {
		n.occupied = true
		n.depths = maxHeap{n.depth}
	} else {
		child, ok := n.children[suffix[0]]
		if !ok {
			child = newNode(n.depth + 1)
			n.children[suffix[0]] = child
		}
		child.add(suffix[1:])
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	const maxCapacity = 100001
	buf := make([]byte, maxCapacity)
	scanner.Buffer(buf, maxCapacity)

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

	trie := newNode(0)
	for i := 0; i < n; i++ {
		scanner.Scan()
		trie.add(scanner.Text())
	}
	trie.consolidate()
	total := 0
	for _, depth := range trie.depths {
		total += depth
	}
	fmt.Println(total)
}


Ringo found a string $$$s$$$ of length $$$n$$$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $$$s$$$ into a palindrome by applying two types of operations to the string. The first operation allows him to choose $$$i$$$ ($$$2 \le i \le n-1$$$) and to append the substring $$$s_2s_3 \ldots s_i$$$ ($$$i - 1$$$ characters) reversed to the front of $$$s$$$.The second operation allows him to choose $$$i$$$ ($$$2 \le i \le n-1$$$) and to append the substring $$$s_i s_{i + 1}\ldots s_{n - 1}$$$ ($$$n - i$$$ characters) reversed to the end of $$$s$$$.Note that characters in the string in this problem are indexed from $$$1$$$.For example suppose $$$s=$$$abcdef. If he performs the first operation with $$$i=3$$$ then he appends cb to the front of $$$s$$$ and the result will be cbabcdef. Performing the second operation on the resulted string with $$$i=5$$$ will yield cbabcdefedc.Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most $$$30$$$ times. The length of the resulting palindrome must not exceed $$$10^6$$$It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.

The only line contains the string $$$S$$$ ($$$3 \le |s| \le 10^5$$$) of lowercase letters from the English alphabet.

The first line should contain $$$k$$$ ($$$0\le k \le 30$$$)  — the number of operations performed. Each of the following $$$k$$$ lines should describe an operation in form L i or R i. $$$L$$$ represents the first operation, $$$R$$$ represents the second operation, $$$i$$$ represents the index chosen. The length of the resulting palindrome must not exceed $$$10^6$$$.

NoteFor the first example the following operations are performed:abac $$$\to$$$ abacab $$$\to$$$ abacabaThe second sample performs the following operations: acccc $$$\to$$$ cccacccc $$$\to$$$ ccccaccccThe third example is already a palindrome so no operations are required.

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	s, _ := reader.ReadString('\n')
	res := solve(s)
	fmt.Print(res)
}

func solve(s string) string {
	var n int
	for n < len(s) && (s[n] >= 'a' && s[n] <= 'z') {
		n++
	}

	var res bytes.Buffer
	res.WriteString("3\n")
	res.WriteString("L 2\n")
	m := n + 1
	res.WriteString("R 2\n")
	m += n - 1
	res.WriteString(fmt.Sprintf("R %d\n", m-1))
	return res.String()
}

package main

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

var _r = bufio.NewReader(os.Stdin)
var _w = bufio.NewWriter(os.Stdout)

var s string

func main() {
	_, _ = fmt.Scan(&s)
	n := len(s)
	fmt.Println(3)
	fmt.Println(string('R'), n-1)
	fmt.Println(string('L'), n)
	fmt.Println(string('L'), 2)
}

package main

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

func main() {
	defer _w.Flush()
	S := ReadString()
	n := len(S)
	println(3)
	println("R", n-1)
	println("L", n)
	println("L", 2)
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func print(a ...interface{})            { fmt.Fprint(_w, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	var s string
	Fscan(bufio.NewReader(os.Stdin), &s)
	n := len(s)
	Print("3\nR ", n-1, "\nL ", n, "\nL ", 2)
}

package main

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

func main() {
	var s string
	Fscan(bufio.NewReader(os.Stdin), &s)
	n := len(s)
	Print("3\nR ", n-1, "\nL ", n, "\nL 2")
}

package main

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

func main() {
	var s string
	Fscan(bufio.NewReader(os.Stdin), &s)
	n := len(s)
	Print("3\nR", n-1, "\nL", n, "\nL 2")
}


You are given two integers $$$l$$$ and $$$r$$$, $$$l\le r$$$. Find the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.As a reminder, $$$a \bmod b$$$ is a remainder we get when dividing $$$a$$$ by $$$b$$$. For example, $$$26 \bmod 8 = 2$$$.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ $$$(1\le t\le 10^4)$$$, denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers $$$l$$$, $$$r$$$ ($$$1\le l \le r \le 10^9$$$).

For every test case, output the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.

NoteIn the first test case, the only allowed pair is $$$(a, b) = (1, 1)$$$, for which $$$a \bmod b = 1 \bmod 1 = 0$$$.In the second test case, the optimal choice is pair $$$(a, b) = (1000000000, 999999999)$$$, for which $$$a \bmod b = 1$$$.

package main

import "fmt"

func main()  {
	var T int
	fmt.Scan(&T)
	for i:=0;i<T;i++{
		var a,b int
		fmt.Scan(&a,&b)
		k:=b/2+1
		var y int
		if k>=a{
			y=k
		}else {
			y=a
		}
		fmt.Println(b%y)
	}
}

package main

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

type CF1562A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1562A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1562A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1562A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1562A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1562A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1562A
Date: 22/11/21
User: epradere
URL: https://codeforces.com/problemset/problem/1562/A
Problem: CF1562A
**/
func (in *CF1562A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		l, r := in.NextInt64(), in.NextInt64()
		ans := int64(math.Ceil(float64(r)/2.0) - 1)
		if ans < l {
			ans = r % l
			if l+1 < r {
				ans = int64(math.Max(float64(ans), float64(r%(l+1))))
			}
		}
		fmt.Println(ans)
	}

}

func NewCF1562A(r *bufio.Reader) *CF1562A {
	return &CF1562A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1562A(bufio.NewReader(os.Stdin)).Run()
}

package main
import (
	"fmt"
	// "sort"
)
func puts(x string){
	fmt.Println(x)
}
func print(x int){
	fmt.Print(x);
	fmt.Print(" ");
}
func test_case(){
	var n,m int
	fmt.Scan(&n,&m)
	temp:=m/2
	if n>temp{
		print(m-n)
		puts("")
	}else if m%2!=0 {
		print(m/2)
		puts("")
	}else{
		print(m/2-1)
		puts("")
	}

}
func main(){
	var t int
	fmt.Scan(&t)
	for t>0{
		test_case()
		t-=1
	}
}

package main

import (
	"fmt"
	"os"
)

type pair struct {
	l, r int
}

func readInput() (int, []pair) {
	var numLines int
	//fmt.Println("hey")
	fmt.Fscan(os.Stdin, &numLines)
	var v []pair = make([]pair, 0, numLines)
	for i := 0; i < numLines; i++ {
		var l, r int
		fmt.Fscan(os.Stdin, &l, &r)
		v = append(v, pair{l, r})
	}
	return numLines, v
}

func findA(l, r int) int {
	if r/l == 1 {
		return r % l
	} else {
		med := r/2 + 1
		return r % med
	}
	/*var result, temp int
	for a := r; a >= l; a-- {
		for b := a; b >= l; b-- {
			temp = a % b
			if temp > result {
				result = temp
			}
		}
	}
	return result*/
}

func main() {
	numLines, v := readInput()
	//fmt.Println(numLines, v)
	for i := 0; i < numLines; i++ {
		fmt.Println(findA(v[i].l, v[i].r))
	}
}

package main

import (
	"fmt"
)

func main() {
	var t, l, r int
	for fmt.Scan(&t); t != 0; t-- {
		fmt.Scan(&l, &r)
		ans := r-l
		if ans > (r-1)/2 {
			ans = (r-1)/2
		}
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t, l, r int
	fmt.Scan(&t)
	for ; t != 0; t-- {
		fmt.Scan(&l, &r)
		ans := r-l
		if ans > (r-1)/2 {
			ans = (r-1)/2
		}
		fmt.Println(ans)
	}
}

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func brute(l, r int) int {
	res := 0
	for a := l; a <= r; a++ {
		for b := l; b <= a; b++ {
			if a%b > res {
				res = a%b
			}
		}
	}
	return res
}

func solve(l, r int) int {
	if l <= r/2+1 {
		return (r-1)/2
	}
	return r%l
}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		l, r := stdin.Int(), stdin.Int()
		fmt.Println(solve(l, r))
	}
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		var l, r int
		fmt.Scan(&l, &r)
		fmt.Println(min((r-1)/2, r-l))
	}
}

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

package main

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

func main() {
	rr := bufio.NewReaderSize(os.Stdin, 1024*1024)

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

	for t := 0; t < T; t++ {
		var l, r int
		fmt.Fscanf(rr, "%d %d\n", &l, &r)

		var x int

		for a := r; a >= l && a > r-10; a-- {
			for b := a/2 - 2; b <= a/2+2; b++ {
				bb := b
				if bb < l || bb > r {
					bb = l
				}
				if bb != 0 && bb < a && a%bb > x {
					x = a % bb
				}
			}
		}

		fmt.Println(x)
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var a,b int
		fmt.Fscan(in,&a,&b)
		if a > (b/2)+1 {
			fmt.Fprintln(out,b%a)
		} else {
			fmt.Fprintln(out,b%((b/2)+1))
		}
	}
}

package main

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

func ICeil(x float64) int64 {
	return int64(math.Ceil(x))
}

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N := 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		l, r := int64(0), int64(0)
		fmt.Fscan(f, &l, &r)
		if ICeil(float64(r)/2.0) >= l {
			fmt.Fprintln(w, ICeil(float64(r)/2.0)-1)
		} else {
			fmt.Fprintln(w, r%l)
		}
	}
	w.Flush()
}

func main() {
	solve()
}

package main

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

var (
	reader  = bufio.NewReader(os.Stdin)
	t, l, r int
)

func solve(l, r int) int {
	if r >= 2*l-1 {
		return (r+1)/2 - 1
	}
	return r - l
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &l, &r)
		fmt.Println(solve(l, r))
	}
}

package main

import "fmt"

func main(){
	var t int
	var l, r int

	fmt.Scanln(&t)
	for ; t>0; t-- {
		fmt.Scanln(&l, &r)
		b := 0
		if r % 2 == 0 {
			// 2b-1 = r - 1
			b = r / 2
		} else {
			// 2b-1 = r
			b = (r+1) / 2
		}

		if b >= l {
			fmt.Println(b-1)
		} else {
			fmt.Println(r-l)
		}
	}
	return
}

package main

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

func main() {

	read := bufio.NewReader(os.Stdin)

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

	for i := 0; i < t; i++ {
		var l, r int
		fmt.Fscan(read, &l, &r)

		fmt.Println(solve(l, r))
	}
}

func solve(l, r int) int {

	//15...26  = 12

	// a = b * k + R
	//26 = 14 * 1 + 12
	//
	//25 8

	if l == r {
		return 0
	}
	d := r/2 + 1

	m := max(d, l)

	return r % m

}

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

package main

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

var input io.Reader = bufio.NewReader(os.Stdin)

func max(a int,b int)(int){
	if a > b{
		return a
	}else{
		return b
	}
}
func solve() {
	var a, b int
	fmt.Fscan(input, &a, &b)
	c := b / 2
	if a == b{
		fmt.Println(0)
		return
	}else{
		for i:= max(a,c);i<b;i++{
			if i * 2 > b{
				fmt.Println(b%i)
				return
			}
		}
	}
	fmt.Println(0)
}
func main() {

	var T int
	fmt.Fscan(input, &T)
	for {
		solve()
		T--
		if T == 0 {
			break
		}
	}
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })

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

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

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

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

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

func MODULE(x, y int) int {
	if x > y {
		return x - y
	} else {
		return y - x
	}
}

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var l, r int
		fmt.Fscan(input, &l, &r)

		m := 2*l - 1
		if m <= r {
			q := (r - 1) / 2
			fmt.Println(q)
		} else {
			w := r - l
			fmt.Println(w)
		}

	}
}

package main

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

func TheMiracleAndSleeper() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	for tcs := ScanPosInt(sc); tcs > 0; tcs-- {
		l := ScanPosInt(sc)
		r := ScanPosInt(sc)
		if l > r/2 {
			fmt.Println(r - l)
		} else {
			fmt.Println((r - 1) / 2)
		}
	}
}

func main() {
	TheMiracleAndSleeper()
}

func ScanPosInt(scanner *bufio.Scanner) (n int) {
	scanner.Scan()
	buf := scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return
}

package main

import "fmt"

func main()  {
	var T int
	fmt.Scanf("%d",&T)
	for i:=0;i<T;i++{
		var a,b int
		fmt.Scanf("%d%d",&a,&b)
		k:=b/2+1
		var y int
		if k>=a{
			y=k
		}else {
			y=a
		}
		fmt.Println(b%y)
	}
}

package main

import "fmt"

func main()  {
	var T int
	fmt.Scanf("%d",&T)
	for i:=0;i<T;i++{
		var a,b int
		fmt.Scanf("%d%d",&a,&b)
		k:=b/2+1
		var y int
		if k>=a{
			y=k
		}else {
			y=a
		}
		fmt.Println(a,b)
		fmt.Println(b%y)
	}
}

package main

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

type CF1562A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1562A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1562A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1562A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1562A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1562A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1562A
Date: 22/11/21
User: epradere
URL: https://codeforces.com/problemset/problem/1562/A
Problem: CF1562A
**/
func (in *CF1562A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		l, r := in.NextInt(), in.NextInt()
		ans :=  int(math.Ceil(float64(r)/2))-1
		if ans < l {
			ans = r%l
		}
		fmt.Println(ans)
	}

}

func NewCF1562A(r *bufio.Reader) *CF1562A {
	return &CF1562A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1562A(bufio.NewReader(os.Stdin)).Run()
}

package main
import (
	"fmt"
	// "sort"
)
func puts(x string){
	fmt.Println(x)
}
func print(x int){
	fmt.Print(x);
	fmt.Print(" ");
}
func test_case(){
	var n,m int
	fmt.Scanf("%d %d\n",&n,&m)
	temp:=m/2
	if n>temp{
		print(m-n)
		puts("")
	}else if m%2!=0 {
		print(m/2)
		puts("")
	}else{
		print(m/2-1)
		puts("")
	}

}
func main(){
	var t int
	fmt.Scanf("%d",&t)
	for t>0{
		test_case()
		t-=1
	}
}

package main

import (
	"fmt"
	"os"
)

type pair struct {
	l, r int
}

func readInput() (int, []pair) {
	var numLines int
	//fmt.Println("hey")
	fmt.Fscan(os.Stdin, &numLines)
	var v []pair = make([]pair, 0, numLines)
	for i := 0; i < numLines; i++ {
		var l, r int
		fmt.Fscan(os.Stdin, &l, &r)
		v = append(v, pair{l, r})
	}
	return numLines, v
}

func findA(l, r int) int {
	if r/l == 1 {
		return r % l
	} else {
		med := r/2 + 1
		return r % med
	}
	/*var result, temp int
	for a := r; a >= l; a-- {
		for b := a; b >= l; b-- {
			temp = a % b
			if temp > result {
				result = temp
			}
		}
	}
	return result*/
}

func main() {
	numLines, v := readInput()
	fmt.Println(numLines, v)
	for i := 0; i < numLines; i++ {
		fmt.Println(findA(v[i].l, v[i].r))
	}
}

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func valid(n int, l, r int) bool {
	return l <= n && n <= r
}

func update(a, b, halfspan int, l, r int, res *int) {
	for ia := -halfspan; ia <= halfspan; ia++ {
		for ib := -halfspan; ib <= halfspan; ib++ {
			na := a + ia
			nb := b + ib
			if valid(na, l, r) && valid(nb, l, r) && na >= nb && na % nb > *res {
				*res = na % nb
			}
		}
	}
}

func solve(l, r int) int {
	res := 0
	update(r, r-1, 5, l, r, &res)
	update(l+1, l, 5, l, r, &res)
	update(r, r/2, 5, l, r, &res)
	update(r-5, r/2, 5, l, r, &res)
	update(l+5, l, 5, l, r, &res)
	update(r/2, l, 5, l, r, &res)
	return res
}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		l, r := stdin.Int(), stdin.Int()
		fmt.Println(solve(l, r))
	}
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		var l, r int
		fmt.Scan(&l, &r)
		fmt.Println(min((r-l)/2, r-l))
	}
}

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


This is the hard version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$2n$$$ operations. It can be proved that it is always possible.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output an integer $$$k$$$ ($$$0\le k\le 2n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.

NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

var (
	writer  *bufio.Writer
	scanner *bufio.Scanner
)

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.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 suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		_ = sint64()
		a := sstring()
		b := sstring()
		res := sol(a, b)
		printf("%d ", len(res))
		for _, i := range res {
			printf("%d ", i)
		}
		printf("\n")
	}
}

func sol(a, b string) []int64 {
    if a == b {
        return nil
    }
    ca := convert0(a)
    cb := convert0(b)
	for i := len(cb)-1; i >= 0; i-- {
        ca = append(ca, cb[i])
    }
    return ca
}

func convert0(a string) []int64 {
	ret := []int64{}
    curr := int64(0)
    for curr != int64(len(a)-1) {
        next := curr+1
		if a[curr] != a[next] {
			ret = append(ret, curr+1)
		}
		curr++
    }
	if a[len(a)-1] == '1' {
		ret = append(ret, int64(len(a)))
	}
	return ret
}

package main

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

/*
6
OEYCDK
EYOKCD
KDCEOY
CKHOYE
YOEDKC
DCKYEO
3
IWL
GIW
WLI
*/

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

type priorityQueue [][2]int

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

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

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

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func next() (n string) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func Fill(a []int, v int) {
	for i := range a {
		a[i] = v
	}
}

func FillB(a []bool, v bool) {
	for i := range a {
		a[i] = v
	}
}

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

var (
	names map[string]int
	words []string
	withs [][]string
	res   []string
	has   []bool
)

func dfs(ind int) {
	if has[ind] {
		return
	}
	has[ind] = true
	for i := len(withs[ind]) - 1; i >= 0; i-- {
		dfs(names[withs[ind][i]])
	}
	res = append(res, words[ind])
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		name := "in"
		file1, err := os.Open(name + ".in")
		if err != nil {
			log.Fatal(err)
		}
		// file2, err := os.Create(name + ".out")
		// if err != nil {
		// 	log.Fatal(err)
		// }
		in = bufio.NewReaderSize(file1, 8192)
		// out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()

	for cases := nextInt(); cases > 0; cases-- {
		n := nextInt()
		a, b := next(), next()
		ord := make([]int, n)
		for i := 0; i <= (n-1)/2; i++ {
			ord[2*i] = i
		}
		for i, curr := n-1, 1; curr < n; i, curr = i-1, curr+2 {
			ord[curr] = i
		}
		res := []int{}
		for i := 0; i < n; i++ {
			x, v := n-1-i, byte(0)
			if i%2 == 1 {
				v = a[ord[i]] ^ 1
			} else {
				v = a[ord[i]]
			}
			if v == b[x] {
				res = append(res, 1)
			}
			res = append(res, x+1)
		}
		printf("%d", len(res))
		for _, v := range res {
			printf(" %d", v)
		}
		printf("\n")
	}
}

package main

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

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.nextInt(); t > 0; t-- {
		n := io.nextInt()
		a, b := []byte(io.next()), []byte(io.next())

		i, j, inv, dir := 0, n-1, byte(0), 1
		ops := []int{}
		for k := n - 1; k >= 0; k-- {
			if a[j]^inv != b[k] {
				if a[i]^inv == b[k] {
					ops = append(ops, 1)
					a[i] ^= 1
				}
				ops = append(ops, k+1)
				i, j = j, i+dir
				dir = -dir
				inv ^= 1
			} else {
				j -= dir
			}
		}
		io.print(len(ops), " ")
		io.printlnInts(ops...)
	}
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) nextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.nextInt()
	}
	return a
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}

package main

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

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

	var T, n int
	var a, b []byte
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &a, &b)
		ans := []interface{}{}
		for i, c := range a {
			if i > 0 && c != a[i-1] {
				ans = append(ans, i)
			}
		}
		if a[n-1] != b[n-1] {
			ans = append(ans, n)
		}
		for i := len(b) - 2; i >= 0; i-- {
			if b[i] != b[i+1] {
				ans = append(ans, i+1)
			}
		}
		Fprint(out, len(ans), " ")
		Fprintln(out, ans...)
	}
}

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


You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai.

The first line contains the only integer n (1 ≤ n ≤ 105) — the length of the permutation. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation. All the integers are distinct.

Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.

NoteIn the first example the only element can be removed.

package main

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

func main() {
	s := bufio.NewScanner(os.Stdin)
	s.Split(bufio.ScanWords)
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	xs := make([]int, n)
	for i := 0; i < n; i++ {
		s.Scan()
		xs[i], _ = strconv.Atoi(s.Text())
	}

	fmt.Println(do(n, xs))
}

func do(n int, xs []int) int {
	//fmt.Println(records(xs))
	//max := -1
	//maxIx := -1
	//var maxRecords []int
	//for i := 4; i <= 4; i++ {
	//	c, records := count(xs, i)
	//	if c > max || (c == max && xs[i] < xs[maxIx]) {
	//		max = c
	//		maxIx = i
	//		maxRecords = records
	//	}
	//}

	//fmt.Println(maxRecords)
	//fmt.Println(xs[maxIx])

	rs := records(xs)
	tr := NewSegmentTree(xs)
	ds := make([]int, n)
	for i := 2; i < len(xs); i++ {
		// if item exists before i that is greater than xs[i], but but all other
		// elements are less than xs[i].
		pr := tr.Range(0, i)
		fstMax := pr.a
		sndMax := pr.b
		if fstMax.val > xs[i] && sndMax.val < xs[i] {
			ds[fstMax.ix]++
		}
	}

	for i := 0; i < n; i++ {
		if i == 0 && n > 1 && rs[1] == 1 {
			ds[i]--
		}

		if rs[i] == 1 {
			ds[i]--
		}
	}

	maxIx := int(math.MinInt32)
	max := int(math.MinInt32)
	for i := 0; i < n; i++ {
		if ds[i] > max || (ds[i] == max && xs[i] < xs[maxIx]) {
			max = ds[i]
			maxIx = i
		}
	}

	//fmt.Println(ds)
	return xs[maxIx]
}

func count(xs []int, toRemove int) (c int, records []int) {
	max := -1
	records = make([]int, len(xs))
	for i := 0; i < len(xs); i++ {
		if i == toRemove {
			continue
		}

		if max != -1 && max < xs[i] {
			c++
			records[i]++
		}

		if xs[i] > max {
			max = xs[i]
		}
	}

	return
}

func records(xs []int) (records []int) {
	max := -1
	records = make([]int, len(xs))
	for i := 0; i < len(xs); i++ {
		if max != -1 && max < xs[i] {
			records[i]++
		}

		if xs[i] > max {
			max = xs[i]
		}
	}

	return
}

type Pair struct {
	a, b Element
}

func NewPair(a, ai, b, bi int) Pair {
	return Pair{Element{a, ai}, Element{b, bi}}
}

func DefaultPair() Pair {
	return Pair{DefaultElement(), DefaultElement()}
}

type Element struct {
	val, ix int
}

func DefaultElement() Element {
	return Element{-1, -1}
}

type SegmentTree struct {
	nds []Pair
	n   int
}

func NewSegmentTree(xs []int) *SegmentTree {
	n := len(xs)
	sq := 1 << (uint(math.Log2(float64(n))) + 1)
	sz := 2*sq - 1
	nds := make([]Pair, sz)
	for i := 0; i < sz; i++ {
		nds[i] = DefaultPair()
	}
	t := &SegmentTree{nds, n}
	for i := 0; i < n; i++ {
		t.Insert(i, xs[i])
	}
	return t
}

func (t *SegmentTree) Insert(k, x int) {
	t.insertRecur(0, k, 0, t.n, x)
}

func (t *SegmentTree) insertRecur(n, k, i, j, x int) {
	if i >= j-1 {
		t.nds[n] = NewPair(x, k, -1, -1)
		return
	}

	m := int((float64(i+j) / 2.0) + 0.5)
	lc := n*2 + 1
	rc := n*2 + 2

	if k < m {
		t.insertRecur(lc, k, i, m, x)
	} else {
		t.insertRecur(rc, k, m, j, x)
	}

	t.nds[n] = t.merge(t.nds[lc], t.nds[rc])
}

func (t *SegmentTree) merge(lv, rv Pair) Pair {
	a, b := maximum(lv.a, lv.b, rv.a, rv.b)
	return Pair{a, b}
}

func maximum(xs ...Element) (Element, Element) {
	//fmt.Println(xs)
	fstMaxElm := DefaultElement()
	sndMaxElm := DefaultElement()

	for i := 0; i < len(xs); i++ {
		if xs[i].val > fstMaxElm.val {
			sndMaxElm = fstMaxElm
			fstMaxElm = xs[i]
			continue
		}
		if xs[i].val > sndMaxElm.val {
			sndMaxElm = xs[i]
		}
	}
	//fmt.Printf("fstMax: %v: sndMax: %v\n", fstMaxElm, sndMaxElm)
	return fstMaxElm, sndMaxElm
}

func (t *SegmentTree) Range(k, l int) Pair {
	return t.rangeRecur(0, k, l, 0, t.n)
}

func (t *SegmentTree) rangeRecur(n, k, l, i, j int) Pair {
	//if i >= j-1 {
	//	return t.nds[n]
	//}

	m := int((float64(i+j) / 2.0) + 0.5)
	lc := 2*n + 1
	rc := 2*n + 2

	if i >= k && j <= l {
		return t.nds[n]
	} else if k >= j || l <= i {
		return DefaultPair()
	}

	//if k == i && l == j {
	//	return t.nds[n]
	//} else if l <= m {
	//	return t.rangeRecur(lc, k, l, i, m)
	//} else if k >= m {
	//	return t.rangeRecur(rc, k, l, m, j)
	//}

	lv := t.rangeRecur(lc, k, l, i, m)
	rv := t.rangeRecur(rc, k, l, m, j)
	return t.merge(lv, rv)
}

package main

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

func main() {
	s := bufio.NewScanner(os.Stdin)
	s.Split(bufio.ScanWords)
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	xs := make([]int, n)
	for i := 0; i < n; i++ {
		s.Scan()
		xs[i], _ = strconv.Atoi(s.Text())
	}

	//fmt.Println(records(xs))
	//max := -1
	//maxIx := -1
	//var maxRecords []int
	//for i := 2; i < n; i++ {
	//	c, records := count(xs, i)
	//	if c > max || (c == max && xs[i] < xs[maxIx]) {
	//		max = c
	//		maxIx = i
	//		maxRecords = records
	//	}
	//}

	//fmt.Println(maxRecords)
	//fmt.Println(xs[maxIx])

	rs := records(xs)
	tr := NewSegmentTree(xs)
	ds := make([]int, n)
	for i := 2; i < len(xs); i++ {
		// if item exists before i that is greater than xs[i], but but all other
		// elements are less than xs[i].
		pr := tr.Range(0, i)
		fstMax := pr.a
		sndMax := pr.b
		if fstMax.val > xs[i] && sndMax.val < xs[i] {
			ds[fstMax.ix]++
		}
	}

	for i := 0; i < n; i++ {
		if rs[i] == 1 && ds[i] > 0 {
			ds[i]--
		}
	}

	maxIx := -1
	max := -1
	for i := 0; i < n; i++ {
		if ds[i] > max || (ds[i] == max && xs[i] < xs[maxIx]) {
			max = ds[i]
			maxIx = i
		}
	}

	fmt.Println(xs[maxIx])
}

func count(xs []int, toRemove int) (c int, records []int) {
	max := -1
	records = make([]int, len(xs))
	for i := 0; i < len(xs); i++ {
		if i == toRemove {
			continue
		}

		if max != -1 && max < xs[i] {
			c++
			records[i]++
		}

		if xs[i] > max {
			max = xs[i]
		}
	}

	return
}

func records(xs []int) (records []int) {
	max := -1
	records = make([]int, len(xs))
	for i := 0; i < len(xs); i++ {
		if max != -1 && max < xs[i] {
			records[i]++
		}

		if xs[i] > max {
			max = xs[i]
		}
	}

	return
}

type Pair struct {
	a, b Element
}

func NewPair(a, ai, b, bi int) Pair {
	return Pair{Element{a, ai}, Element{b, bi}}
}

type Element struct {
	val, ix int
}

func DefaultElement() Element {
	return Element{-1, -1}
}

type SegmentTree struct {
	nds []Pair
	n   int
}

func NewSegmentTree(xs []int) *SegmentTree {
	n := len(xs)
	sq := 1 << (uint(math.Log2(float64(n))) + 1)
	sz := 2*sq - 1
	nds := make([]Pair, sz)
	for i := 0; i < sz; i++ {
		nds[i] = NewPair(-1, -1, -1, -1)
	}
	t := &SegmentTree{nds, n}
	for i := 0; i < n; i++ {
		t.Insert(i, xs[i])
	}
	return t
}

func (t *SegmentTree) Insert(k, x int) {
	t.insertRecur(0, k, 0, t.n, x)
}

func (t *SegmentTree) insertRecur(n, k, i, j, x int) {
	if i >= j-1 {
		t.nds[n] = NewPair(x, k, -1, -1)
		return
	}

	m := int((float64(i+j) / 2.0) + 0.5)
	lc := n*2 + 1
	rc := n*2 + 2

	if k < m {
		t.insertRecur(lc, k, i, m, x)
	} else {
		t.insertRecur(rc, k, m, j, x)
	}

	t.nds[n] = t.merge(t.nds[lc], t.nds[rc])
}

func (t *SegmentTree) merge(lv, rv Pair) Pair {
	a, b := maximum(lv.a, lv.b, rv.a, rv.b)
	return Pair{a, b}
}

func maximum(xs ...Element) (Element, Element) {
	//fmt.Println(xs)
	fstMaxElm := DefaultElement()
	sndMaxElm := DefaultElement()

	for i := 0; i < len(xs); i++ {
		if xs[i].val > fstMaxElm.val {
			sndMaxElm = fstMaxElm
			fstMaxElm = xs[i]
			continue
		}
		if xs[i].val > sndMaxElm.val {
			sndMaxElm = xs[i]
		}
	}
	//fmt.Printf("fstMax: %v: sndMax: %v\n", fstMaxElm, sndMaxElm)
	return fstMaxElm, sndMaxElm
}

func (t *SegmentTree) Range(k, l int) Pair {
	return t.rangeRecur(0, k, l, 0, t.n)
}

func (t *SegmentTree) rangeRecur(n, k, l, i, j int) Pair {
	if i >= j-1 {
		return t.nds[n]
	}

	m := int((float64(i+j) / 2.0) + 0.5)
	lc := 2*n + 1
	rc := 2*n + 2

	if k == i && l == j {
		return t.nds[n]
	} else if l <= m {
		return t.rangeRecur(lc, k, l, i, m)
	} else if k >= m {
		return t.rangeRecur(rc, k, l, m, j)
	}

	lv := t.rangeRecur(lc, k, l, i, m)
	rv := t.rangeRecur(rc, k, l, m, j)
	return t.merge(lv, rv)
}

package main

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

func main() {
	s := bufio.NewScanner(os.Stdin)
	s.Split(bufio.ScanWords)
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	xs := make([]int, n)
	for i := 0; i < n; i++ {
		s.Scan()
		xs[i], _ = strconv.Atoi(s.Text())
	}

	max := -1
	maxIx := -1
	for i := 0; i < n; i++ {
		c := count(xs, i)
		if c > max {
			max = c
			maxIx = i
		}
	}

	fmt.Println(xs[maxIx])
}

func count(xs []int, toRemove int) (c int) {
	max := -1
	for i := 0; i < len(xs); i++ {
		if i == toRemove {
			continue
		}

		if max != -1 && max < xs[i] {
			c++
		}

		if xs[i] > max {
			max = xs[i]
		}
	}

	return
}