This problem is same as the next one, but has smaller 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$$$) — 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 (
	"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 [11]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 (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// k := make(map[int]int)
	k := make(map[int]int)
	t := SplayTree{}
	ans := 1
	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 {
				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++
		l, r := t.root, t.root
		for l.left != nil {
			l = l.left
		}
		for r.right != nil {
			r = r.right
		}
		first, last := l.Key.(*Node), r.Key.(*Node)
		if last.Key == 1 {
			ans = i + 1
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Print(ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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)
}

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, mm := 0, 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 {
      mm = mn
      mn = k[a[i]]
      if c[mm] == 0 {
        mm = mn + 1
      }
    }
    for c[mn] == 0 {
      mn++
    }
    if mm <= mn {
      mm = mn + 1
    }
    for mm < mx && c[mm] == 0 {
      mm++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    if mx == 1 || c[mx] == 1 && mn + 1 >= mx || c[mn] == 1 && mn == 1 && mm == mx {
      ans = i + 1
    }
  }
  fmt.Printf("%d", ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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]]})
			if n.Key.(Node).Value == 1 {
				if l == n {
					l = nil
				}
				if r == n {
					r = nil
				}
				t.Erase(n)
			} else {
				n.Key = Node{
					Key: n.Key.(Node).Key,
					Value: n.Key.(Node).Value - 1,
				}
			}
		}
		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{
			Key: n.Key.(Node).Key,
			Value: n.Key.(Node).Value + 1,
		}
		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
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			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"
	"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 [11]int                  // 每个颜色出现的次数
	var colorCountTimes = make(map[int]int) // 每个出现的次数有几个颜色
	var mcctc int                           // 最大出现次数的是哪个颜色
	var ncctc int                           // 第二大出现次数的是哪个颜色
	for i := 0; i < n; i++ {
		tc := inputs[i] // 当前颜色
		see(tc)
		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[mcctc]*colorCountTimes[colorCount[mcctc]] == i ||
			colorCount[ncctc]*(colorCountTimes[colorCount[ncctc]]+colorCountTimes[colorCount[mcctc]]) == i {
			mans = i + 1
		}
	}
	printf("%d\n", mans)
}

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 := 1; i < n; i++ {
		scanf("%d ", &ans[i])
	}
	scanf("%d\n", &ans[n-1])
	return ans
}

var debug = true

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 [11]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[mcctc]*colorCountTimes[colorCount[mcctc]] == i ||
			colorCount[ncctc]*(colorCountTimes[colorCount[ncctc]]+1) == i {
			mans = i + 1
		}
	}
	printf("%d\n", mans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// k := make(map[int]int)
	k := make(map[int]int)
	t := SplayTree{}
	ans := 1
	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 {
				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++
		l, r := t.root, t.root
		for l.left != nil {
			l = l.left
		}
		for r.right != nil {
			r = r.right
		}
		first, last := l.Key.(*Node), r.Key.(*Node)
		if last.Key == 1 {
			ans = i + 1
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Print(ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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 = n
		}
		first, last := l.Key.(*Node), r.Key.(*Node)
		if last.Key == 1 {
			ans = i + 1
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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 {
			l = n
		}
		if r == nil {
			r = n
		}
		first, last := l.Key.(*Node), r.Key.(*Node)
		if last.Key == 1 {
			ans = i + 1
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Print(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 := 1
  k := make(map[int]int)
  c := make(map[int]int)
  mn, mx, mm := 0, 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++
    }
    mm = mn + 1
    for mm < mx && c[mm] == 0 {
      mm++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    fmt.Printf("%d %d %d %d\n", c[mn], mn, mm, mx)
    if mx == 1 || c[mx] == 1 && mn + 1 == mx || c[mn] == 1 && mn == 1 && mm == mx {
      ans = i + 1
    }
  }
  fmt.Printf("%d", 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 := 1
  k := make(map[int]int)
  c := make(map[int]int)
  mn, mx, mm := 0, 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++
    }
    mm = mn + 1
    for mm < mx && c[mm] == 0 {
      mm++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    if c[mx] == 1 && mn + 1 == mx {
      ans = i + 1
    }
    if mn == 1 && c[mn] == 1 && mm == mx {
      ans = i + 1
    }
  }
  fmt.Printf("%d", 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 := 1
  k := make(map[int]int)
  c := make(map[int]int)
  mn, mx, mm := 0, 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 {
      mm = mn
      mn = k[a[i]]
      if c[mm] == 0 {
        mm = mn + 1
      }
    }
    for c[mn] == 0 {
      mn++
    }
    if mm < mn {
      mm = mn + 1
    }
    for mm < mx && c[mm] == 0 {
      mm++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    if mx == 1 || c[mx] == 1 && mn + 1 == mx || c[mn] == 1 && mn == 1 && mm == mx {
      ans = i + 1
    }
  }
  fmt.Printf("%d", 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 := 1
  k := make(map[int]int)
  c := make(map[int]int)
  mn, mx, mm := 0, 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++
    }
    mm = mn + 1
    for mm < mx && c[mm] == 0 {
      mm++
    }
    for c[mx + 1] > 0 {
      mx++
    }
    if mx == 1 || c[mx] == 1 && mn + 1 == mx || c[mn] == 1 && mn == 1 && mm == mx {
      ans = i + 1
    }
  }
  fmt.Printf("%d", ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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 || l.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
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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 = n
		}
		first, last := l.Key.(*Node), r.Key.(*Node)
		fmt.Println(first, last)
		if last.Key == 1 {
			ans = i + 1
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

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() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// 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 = l.Next()
				}
				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 {
			l = t.root
		}
		if r == nil {
			r = t.root
		}
		first, last := l.Key.(*Node), r.Key.(*Node)
		if last.Key == 1 {
			ans = i + 1
		}
		if last.Value == 1 && first.Key + 1 >= last.Key {
			ans = i + 1
		}
		if first.Key == 1 && first.Value == 1 && l.Next() == r {
			ans = i + 1
		}
	}
	fmt.Print(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]*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))
}

// 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 {
	fmt.Println(countOfCount)
	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))
}


Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has $$$n$$$ warriors, he places them on a straight line in front of the main gate, in a way that the $$$i$$$-th warrior stands right after $$$(i-1)$$$-th warrior. The first warrior leads the attack.Each attacker can take up to $$$a_i$$$ arrows before he falls to the ground, where $$$a_i$$$ is the $$$i$$$-th warrior's strength.Lagertha orders her warriors to shoot $$$k_i$$$ arrows during the $$$i$$$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $$$t$$$, they will all be standing to fight at the end of minute $$$t$$$.The battle will last for $$$q$$$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \leq 200\,000$$$) — the number of warriors and the number of minutes in the battle. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) that represent the warriors' strengths. The third line contains $$$q$$$ integers $$$k_1, k_2, \ldots, k_q$$$ ($$$1 \leq k_i \leq 10^{14}$$$), the $$$i$$$-th of them represents Lagertha's order at the $$$i$$$-th minute: $$$k_i$$$ arrows will attack the warriors.

Output $$$q$$$ lines, the $$$i$$$-th of them is the number of standing warriors after the $$$i$$$-th minute.

NoteIn the first example:   after the 1-st minute, the 1-st and 2-nd warriors die.  after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive.  after the 3-rd minute, the 1-st warrior dies.  after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1.  after the 5-th minute, the 2-nd warrior dies.

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 main() {
	defer writer.Flush()

	var n, q int
	scanf("%d %d\n", &n, &q)
	a, k := make([]int64, n), make([]int64, q)
	for i := range a {
		scanf("%d", &a[i])
	}
	scanf("\n")
	for i := range k {
		scanf("%d", &k[i])
	}
	ta := make([]int64, n)
	ta[0] = a[0]
	for i := 1; i < n; i++ {
		ta[i] = a[i] + ta[i-1]
	}
	d := int64(0)
	for i := range k {
		d += k[i]
		if d >= ta[n-1] {
			printf("%d\n", n)
			d = 0
		} else {
			printf("%d\n", n-sort.Search(n, func(i int) bool { return ta[i] > d }))
		}
	}
}


Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n    input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF        //here INF is a number big enoughtot=0for i from 1 to n    for j from (i+1) to n        ++tot        if (p[j].x-p[i].x>=d) then break    //notice that "break" is only to be                                            //out of the loop "for j"        d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?

A single line which contains two space-separated integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ 109).

If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≤ 109) representing the coordinates of the i-th point. The conditions below must be held:   All the points must be distinct.  |xi|, |yi| ≤ 109.  After running the given code, the value of tot should be larger than k.

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var n, k int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	r.Scan()
	k, _ = strconv.Atoi(r.Text())
	x := (n-1)*n/2
	if k >= x {
		w.WriteString("no solution\n")
		w.Flush()
		return
	}
	for j:=0; j<n; j++ {
		w.WriteString("0 ")
		w.WriteString(strconv.Itoa(j)+"\n")
	}
	w.Flush()
}

package main

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

func main() {
    var n,i,k int
    out := bufio.NewWriter(os.Stdout)
    fmt.Scan(&n,&k)
    if ((n*(n-1))/2)<=k {
    	fmt.Println("no solution")
    } else {
    	for i=0;i<n;i++ {
    		out.WriteString("0 "+strconv.Itoa(i)+"\n")
    	}
    }
    out.Flush()
}

package main

import "fmt"

func main() {
    var n,k int
    fmt.Scan(&n,&k)
    if (n*(n-1))/2 <= k {
        fmt.Println("no solution")
    } else {
        for i := 0; i < n; i++ {
            fmt.Println(0,i)
        }
    }
}

// 311A
package main

import (
	"fmt"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	if k >= n*(n-1)/2 {
		fmt.Print("no solution")
	} else {
		for i := 1; i <= n; i++ {
			fmt.Printf("0 %d\n", i)
		}
	}
}

// 311A-mic
package main

import (
	"fmt"
)

func main() {
	var a, b [1000006]int
	var n, k, i, j, x int
	fmt.Scan(&n, &k)
	for i = 0; i < (n+1)/2; i++ {
		a[i] = 0
		b[i] = 2 * i
	}
	for i = (n + 1) / 2; i < n; i++ {
		a[i] = 1
		b[i] = 2 * i
	}
	x = 0
	for i = 0; i < n; i++ {
		for j = i + 1; j < n; j++ {
			x++
		}
	}
	if x <= k {
		fmt.Println("no solution")
	} else {
		for i = 0; i < n; i++ {
			fmt.Println(a[i], b[i])
		}
	}
}

package main

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

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

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

func main() {
	scanner.Split(bufio.ScanWords)
	n, k := NextInt(), NextInt()
	if k >= n*(n-1)/2 {
		w.WriteString("no solution\n")
	} else {
		for i := 0; i < n; i++ {
			w.WriteString("0 " + strconv.Itoa(i))
			w.WriteByte('\n')
		}
	}
	w.Flush()
}

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var n, k int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdin)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	r.Scan()
	k, _ = strconv.Atoi(r.Text())
	x := (n-1)*n/2
	if k > x {
		w.WriteString("no solution\n")
		w.Flush()
		return
	}
	for j:=0; j<n; j++ {
		w.WriteString("0 ")
		w.WriteString(strconv.Itoa(j)+"\n")
	}
	w.Flush()
}

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var n, k int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	r.Scan()
	k, _ = strconv.Atoi(r.Text())
	x := (n-1)*n/2
	if k > x {
		w.WriteString("no solution\n")
		w.Flush()
		return
	}
	for j:=0; j<n; j++ {
		w.WriteString("0 ")
		w.WriteString(strconv.Itoa(j)+"\n")
	}
	w.Flush()
}

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var n, k int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdin)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	r.Scan()
	k, _ = strconv.Atoi(r.Text())
	x := (n-1)*n/2
	if k > x {
		w.WriteString("no solution\n")
		w.Flush()
		return
	}
	for i:=1; i<=n; i++ {
		w.WriteString("0 "+strconv.Itoa(i)+"\n")
	}
	w.Flush()
}


You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of $$$a$$$ and the length of $$$b$$$ correspondingly. The second line of the input contains one huge integer $$$a$$$. It is guaranteed that this number consists of exactly $$$n$$$ zeroes and ones and the first digit is always $$$1$$$. The third line of the input contains one huge integer $$$b$$$. It is guaranteed that this number consists of exactly $$$m$$$ zeroes and ones and the first digit is always $$$1$$$.

Print the answer to this problem in decimal notation modulo $$$998244353$$$.

package main

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

const mod int64 = 998244353

var (
	bc  int64
	sum int64
	n   int
	m   int
	a   string
	b   string
)

func main() {
	r := bufio.NewReader(os.Stdin)
	fmt.Fscan(r, &n, &m)
	fmt.Fscan(r, &a, &b)
	bs := make([]int, m)
	bs[0] = 1
	for i := 1; i < m; i++ {
		bs[i] = bs[i-1]
		if b[i] == '1' {
			bs[i]++
		}
	}
	var sum int64
	for i, j, s := n-1, 0, int64(1); i >= 0 && j < m; i-- {
		if a[i] == '1' {
			sum += (int64(bs[m-j-1]) * s) % mod
		}
		s = (s * 2) % mod
		j++
	}
	fmt.Println(sum % mod)
}

package main

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

const mod = 998244353

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

	var ndigs, mdigs int
	fmt.Fscan(r, &ndigs, &mdigs)

	var n, m string
	fmt.Fscan(r, &n, &m)

	psum := make([]int64, mdigs)
	for i := 0; i < mdigs; i++ {
		if i > 0 {
			psum[i] = psum[i-1]
		}
		if m[i] == '1' {
			psum[i]++
		}
	}
	var ans, base int64
	base = 1
	for i := 0; i < ndigs; i++ {
		if pos := ndigs - i - 1; n[pos] == '1' {
			p := mdigs - i - 1
			if p >= 0 {
				ans = (ans + base*psum[p]) % mod
			}
		}
		base = (base * 2) % mod
	}
	fmt.Println(ans)
}

package main

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

const (
	MaxN = 200005
	Mod  = 998244353
)

var n, m int
var powers [MaxN]int64
var counts [MaxN]int
var ones []int
var num []int

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

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &m)
	ones = make([]int, 0)
	biggest := max(n, m)

	for i := 0; i < n; i++ {
		var tmp byte
		fmt.Fscanf(buf, "%c", &tmp)
		if tmp == '1' {
			ones = append(ones, n - i - 1)
		}
	}

	fmt.Fscanf(buf, "\n")

	num = make([]int, biggest)
	for i := 0; i < m; i++ {
		var tmp byte
		fmt.Fscanf(buf, "%c", &tmp)
		ind := i + biggest - m
		num[ind] = 0
		if tmp == '1' {
			num[ind] = 1
		}
	}

	for i := 1; i < biggest; i++ {
		num[i] += num[i-1]
	}

	powers[0] = 1
	for i := 1; i < biggest; i++ {
		powers[i] = (powers[i - 1] * 2) % Mod
	}

	ans := int64(0)
	for i := 0; i < len(ones); i++ {
		ans = (ans + (powers[ones[i]] * int64(num[biggest - ones[i] - 1])) % Mod) % Mod
	}

	fmt.Println(ans)
}

package main

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

const mod = 998244353

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

	var ndigs, mdigs int
	fmt.Fscan(r, &ndigs, &mdigs)

	var n, m string
	fmt.Fscan(r, &n, &m)

	psum := make([]int64, mdigs)
	for i := 0; i < mdigs; i++ {
		if i > 0 {
			psum[i] = psum[i-1]
		}
		if m[i] == '1' {
			psum[i]++
		}
	}
	var ans, base int64
	base = 1
	for i := 0; i < ndigs; i++ {
		if pos := ndigs - i - 1; n[pos] == '1' {
			p := mdigs - i - 1
			if p >= 0 {
				ans += (base * psum[p]) % mod
			}
		}
		base = (base * 2) % mod
	}
	fmt.Println(ans)
}

package main

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

const (
	MaxN = 200005
	Mod  = 998244353
)

var n, m int
var powers [MaxN]int
var counts [MaxN]int
var ones []int
var num []int

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

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n", &n, &m)
	ones = make([]int, 0)
	biggest := max(n, m)

	for i := 0; i < n; i++ {
		var tmp byte
		fmt.Fscanf(buf, "%c", &tmp)
		if tmp == '1' {
			ones = append(ones, n - i - 1)
		}
	}

	fmt.Fscanf(buf, "\n")

	num = make([]int, m)
	for i := 0; i < m; i++ {
		var tmp byte
		fmt.Fscanf(buf, "%c", &tmp)
		ind := i + biggest - m
		num[ind] = 0
		if tmp == '1' {
			num[ind] = 1
		}
	}

	for i := 1; i < biggest; i++ {
		num[i] += num[i-1]
	}

	powers[0] = 1
	for i := 1; i < biggest; i++ {
		powers[i] = (powers[i - 1] * 2) % Mod
	}

	ans := 0
	for i := 0; i < len(ones); i++ {
		ans = (ans + (powers[ones[i]] * num[biggest - ones[i] - 1]) % Mod) % Mod
	}

	fmt.Println(ans)
}


Toad Zitz has an array of integers, each integer is between $$$0$$$ and $$$m-1$$$ inclusive. The integers are $$$a_1, a_2, \ldots, a_n$$$.In one operation Zitz can choose an integer $$$k$$$ and $$$k$$$ indices $$$i_1, i_2, \ldots, i_k$$$ such that $$$1 \leq i_1 < i_2 < \ldots < i_k \leq n$$$. He should then change $$$a_{i_j}$$$ to $$$((a_{i_j}+1) \bmod m)$$$ for each chosen integer $$$i_j$$$. The integer $$$m$$$ is fixed for all operations and indices.Here $$$x \bmod y$$$ denotes the remainder of the division of $$$x$$$ by $$$y$$$.Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 300\,000$$$) — the number of integers in the array and the parameter $$$m$$$. The next line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < m$$$) — the given array.

Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print $$$0$$$. It is easy to see that with enough operations Zitz can always make his array non-decreasing.

NoteIn the first example, the array is already non-decreasing, so the answer is $$$0$$$.In the second example, you can choose $$$k=2$$$, $$$i_1 = 2$$$, $$$i_2 = 5$$$, the array becomes $$$[0,0,1,3,3]$$$. It is non-decreasing, so the answer is $$$1$$$.

package main

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

func solveAll(jam Jam) {
	s, l, ui, f, d, p, pf := jam.Str, jam.Long, jam.Int, jam.Float, jam.D, jam.P, jam.PF
	//	Live Templates: for0l for1l for0ui for1ui forr vl0 vln vui0 vuin ; Casts: l i

	n,m := ui(), ui()
	a := make([]uint32, n, n)
	for i := uint32(0); i < n; i++ {
		a[i] = ui()
	}

	p(
		"%d\n",
		sort.Search(
			int(m),
			func(probeInt int) bool {
				probe := uint32(probeInt)
				//d("PROBE=%d\n", probe)
				minBound := ti((a[0] + probe) >= m, 0, a[0])
				//d("%d:%d ", a[0], minBound)
				for i := uint32(1); i < n; i++ {
					if minBound > a[i] + probe  {
						//d("%d:FALSE\n", a[i])
						return false
					}
					if (a[i] + probe) >= m && (a[i] + probe) % m >= minBound {
						// do nothing
					} else {
						minBound = maxi(a[i], minBound)
					}
					//d("%d:%d ", a[i], minBound)
				}
				//d(" TRUE\n")
				return true
			},
		),
	)

	if false { d("%v", []interface{}{s, l, ui, f, d, p, pf}) }
}

//	TODO wipe unused shorthand methods for math
type Uint32Sort []uint32
func (s Uint32Sort) Len() int           { return len(s) }
func (s Uint32Sort) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s Uint32Sort) Less(i, j int) bool { return s[i] < s[j] }

func t(b bool, t, f int64) int64 { if b {return t};return f }
func min(a, b int64) int64 { if a < b {return a}; return b }
func max(a, b int64) int64 { if a > b {return a}; return b }
func abs(a int64) int64 { if a < 0 { return -a }; return a }
func ti(b bool, t, f uint32) uint32 { if b {return t};return f }
func mini(a, b uint32) uint32 { if a < b { return a }; return b }
func maxi(a, b uint32) uint32 { if a > b { return a }; return b }

func round(x float64) float64 { //	https://www.cockroachlabs.com/blog/rounding-implementations-in-go/
	const (
		mask     = 0x7FF
		shift    = 64 - 11 - 1
		bias     = 1023

		signMask = 1 << 63
		fracMask = (1 << shift) - 1
		halfMask = 1 << (shift - 1)
		one      = bias << shift
	)

	bits := math.Float64bits(x)
	e := uint(bits>>shift) & mask
	switch {
	case e < bias:
		// Round abs(x)<1 including denormals.
		bits &= signMask // +-0
		if e == bias-1 {
			bits |= one // +-1
		}
	case e < bias+shift:
		// Round any abs(x)>=1 containing a fractional component [0,1).
		e -= bias
		bits += halfMask >> e
		bits &^= fracMask >> e
	}
	return math.Float64frombits(bits)
}

func main() {
	jam, closeFunc := JamNew()
	defer closeFunc()
	solveAll(jam)
}

type Jam interface {
	Scanner() *bufio.Scanner
	Writer() *bufio.Writer
	Close()

	Str() string
	Long() int64
	Int() uint32
	Float() float64

	D(format string, values ...interface{})
	P(format string, values ...interface{})
	PF(format string, values ...interface{})
}

func JamNew() (Jam, func()) {
	if len(os.Args) > 1 {
		panic("running with input file path is not supported")
	}

	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)

	var writer = bufio.NewWriterSize(os.Stdout, 1024*1024)
	jam := &jam{scanner, writer}
	return jam, jam.Close
}

type jam struct {
	sc *bufio.Scanner
	wr *bufio.Writer
}

func (j *jam) Close() {
	if err := j.wr.Flush(); err != nil {
		panic(err)
	}
}

func (j *jam) Scanner() *bufio.Scanner {
	return j.sc
}

func (j *jam) Writer() *bufio.Writer {
	return j.wr
}

func (j *jam) Str() string {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	return j.sc.Text()
}

func (j *jam) Long() int64 {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	res, err := strconv.ParseInt(j.sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}

	return res
}

func (j *jam) Int() uint32 {
	return uint32(j.Long())
}

func (j *jam) Float() float64 {
	j.sc.Scan()
	res, err := strconv.ParseFloat(j.sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

func (j *jam) D(format string, values ...interface{}) {
	_ /*bytesWritten*/, err := fmt.Fprintf(os.Stderr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) P(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) PF(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
	if err = j.wr.Flush(); err != nil {
		panic(err)
	}
}

package main

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

func distance(from, to, m int) int {
    if to >= from {
        return to - from
    } else {
        return to + m - from
    }
}

func check(a []int, x, m int) bool {
    minval := 0
    for _, item := range a {
        dist := distance(item, minval, m)
        if dist <= x {
            continue
        }
        if item >= minval {
            minval = item
        } else {
            return false
        }
    }

    return true
}

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

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

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

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

    left, right := 0, m
    ans := -1
    for right >= left {
        mid := (left + right) / 2
        if check(a, mid, m) {
            ans = mid
            right = mid - 1
        } else {
            left = mid + 1
        }
    }

    fmt.Println(ans)
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

func readInt() int {
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	return n
}

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

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

func check(arr []int, m, k int) bool {
	prev := -1
	for i := 0; i < len(arr); i++ {
		if arr[i]+k < m { // simple contiguous case
			if prev > arr[i]+k {
				return false
			}
			prev = max(prev, arr[i])
		} else { // wrap around case
			if prev <= (arr[i]+k)%m {
				// prev is unchanged
			} else {
				prev = max(prev, arr[i])
			}
		}
	}
	return true
}

func main() {
	scanner.Split(bufio.ScanWords)

	n, m := readInt(), readInt()
	arr := readIntSlice(n)

	lo, hi := 0, m-1
	for lo < hi {
		mid := (lo + hi) / 2
		if check(arr, m, mid) {
			hi = mid
		} else {
			lo = mid + 1
		}
	}

	fmt.Println(hi)
}

package main

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func readInt() int {
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	return n
}

func readLong() int64 {
	scanner.Scan()
	n, err := strconv.ParseInt(scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return n
}

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

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

func test(arr []int, m, k int) bool {
	prev := -1
	for i := 0; i < len(arr); i++ {
		if arr[i]+k >= m { // wrap-around case
			if prev <= (arr[i]+k)%m {
				// no change in prev -- keep same value
			} else {
				prev = max(prev, arr[i])
			}
		} else { // simple contiguous range case
			if prev > arr[i]+k {
				return false
			}
			prev = max(prev, arr[i])
		}
	}
	return true
}

func solve(arr []int, m, lo, hi int) int {
	for lo < hi {
		mid := (lo + hi) / 2
		if !test(arr, m, mid) {
			lo = mid + 1
		} else {
			hi = mid
		}
	}

	return hi
}

func main() {
	scanner.Split(bufio.ScanWords)

	n, m := readInt(), readInt()
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = readInt()
	}
	fmt.Println(solve(arr, m, 0, m-1))
}

package main

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

func check(arr []int, m, k int) bool {
	prev := 0
	for _, v := range arr {
		if (prev-v+m)%m <= k {
			continue
		}
		if v+k < prev {
			return false
		}
		prev = v
	}
	return true
}

func (io *IO) Solve() {
	n := io.Int()
	m := io.Int()
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = io.Int()
	}
	if check(arr, m, 0) {
		io.Print(0)
		return
	}
	l, r := 0, m-1
	for r > l+1 {
		mid := (r + l) / 2
		if check(arr, m, mid) {
			r = mid
		} else {
			l = mid
		}
	}
	io.Print(r)
}

func main() {
	NewIO().Solve()
}

type IO struct {
	scanner *bufio.Scanner
	writer  io.Writer
}

func NewIO() *IO {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return &IO{scanner, os.Stdout}
}

func (io *IO) Skip() {
	io.scanner.Scan()
}

func (io *IO) Int32() (n int32) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int32(v-'0')
	}
	return
}

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

func (io *IO) Print(a interface{}) {
	fmt.Fprint(io.writer, a)
}

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

package main

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

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

	var n, m int
	Fscan(in, &n, &m)
	arr := make([]int, n)
	for i := range arr {
		Fscan(in, &arr[i])
	}
	ans := sort.Search(m, func(op int) bool {
		min := 0
		for _, a := range arr {
			if a+op < m+min {
				if a+op < min {
					return false
				}
				if a > min {
					min = a
				}
			}
		}
		return true
	})
	Fprintln(out, ans)
}

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

package main

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

func distance(from, to, m int) int {
    if from > to {
        return m - from + to
    }else {
        return to - from
    }
}
func check(a []int, x, m int) bool {
    maxval := 0
    for _, item := range a {
        dist:=distance(item, maxval, m)
        if dist <= x {
           continue
        }
        if item >= maxval {
            maxval = item
        } else {
            return false
        }
    }
    return true
}

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

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

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

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

    left, right := 0, m
    ans := -1
    for right >= left {
        mid := (left + right) >> 1
        if check(a, mid, m) {
            ans = mid
            right = mid - 1
        } else {
            left = mid + 1
        }
    }

    fmt.Println(ans)
}

package main

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

func solveAll(jam Jam) {
	s, l, ui, f, d, p, pf := jam.Str, jam.Long, jam.Int, jam.Float, jam.D, jam.P, jam.PF
	//	Live Templates: for0l for1l for0ui for1ui forr vl0 vln vui0 vuin ; Casts: l i

	n,m := ui(), ui()
	a := make([]uint32, n, n)
	for i := uint32(0); i < n; i++ {
		a[i] = ui()
	}

	p(
		"%d\n",
		sort.Search(
			int(m),
			func(probeInt int) bool {
				probe := uint32(probeInt)
				minBound := ti((a[0] + probe) >= m, 0, a[0])
				for i := uint32(1); i < n; i++ {
					if minBound > a[i] && minBound - a[i] > probe {
						return false
					}
					minBound = maxi(minBound, ti((a[i] + probe) >= m, 0, a[i]))
				}
				return true
			},
		),
	)

	if false { d("%v", []interface{}{s, l, ui, f, d, p, pf}) }
}

//	TODO wipe unused shorthand methods for math
type Uint32Sort []uint32
func (s Uint32Sort) Len() int           { return len(s) }
func (s Uint32Sort) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s Uint32Sort) Less(i, j int) bool { return s[i] < s[j] }

func t(b bool, t, f int64) int64 { if b {return t};return f }
func min(a, b int64) int64 { if a < b {return a}; return b }
func max(a, b int64) int64 { if a > b {return a}; return b }
func abs(a int64) int64 { if a < 0 { return -a }; return a }
func ti(b bool, t, f uint32) uint32 { if b {return t};return f }
func mini(a, b uint32) uint32 { if a < b { return a }; return b }
func maxi(a, b uint32) uint32 { if a > b { return a }; return b }

func round(x float64) float64 { //	https://www.cockroachlabs.com/blog/rounding-implementations-in-go/
	const (
		mask     = 0x7FF
		shift    = 64 - 11 - 1
		bias     = 1023

		signMask = 1 << 63
		fracMask = (1 << shift) - 1
		halfMask = 1 << (shift - 1)
		one      = bias << shift
	)

	bits := math.Float64bits(x)
	e := uint(bits>>shift) & mask
	switch {
	case e < bias:
		// Round abs(x)<1 including denormals.
		bits &= signMask // +-0
		if e == bias-1 {
			bits |= one // +-1
		}
	case e < bias+shift:
		// Round any abs(x)>=1 containing a fractional component [0,1).
		e -= bias
		bits += halfMask >> e
		bits &^= fracMask >> e
	}
	return math.Float64frombits(bits)
}

func main() {
	jam, closeFunc := JamNew()
	defer closeFunc()
	solveAll(jam)
}

type Jam interface {
	Scanner() *bufio.Scanner
	Writer() *bufio.Writer
	Close()

	Str() string
	Long() int64
	Int() uint32
	Float() float64

	D(format string, values ...interface{})
	P(format string, values ...interface{})
	PF(format string, values ...interface{})
}

func JamNew() (Jam, func()) {
	if len(os.Args) > 1 {
		panic("running with input file path is not supported")
	}

	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)

	var writer = bufio.NewWriterSize(os.Stdout, 1024*1024)
	jam := &jam{scanner, writer}
	return jam, jam.Close
}

type jam struct {
	sc *bufio.Scanner
	wr *bufio.Writer
}

func (j *jam) Close() {
	if err := j.wr.Flush(); err != nil {
		panic(err)
	}
}

func (j *jam) Scanner() *bufio.Scanner {
	return j.sc
}

func (j *jam) Writer() *bufio.Writer {
	return j.wr
}

func (j *jam) Str() string {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	return j.sc.Text()
}

func (j *jam) Long() int64 {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	res, err := strconv.ParseInt(j.sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}

	return res
}

func (j *jam) Int() uint32 {
	return uint32(j.Long())
}

func (j *jam) Float() float64 {
	j.sc.Scan()
	res, err := strconv.ParseFloat(j.sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

func (j *jam) D(format string, values ...interface{}) {
	_ /*bytesWritten*/, err := fmt.Fprintf(os.Stderr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) P(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) PF(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
	if err = j.wr.Flush(); err != nil {
		panic(err)
	}
}

package main

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

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

	var n, m int
	Fscan(in, &n, &m)
	arr := make([]int, n)
	for i := range arr {
		Fscan(in, &arr[i])
	}
	ans := sort.Search(m, func(op int) bool {
		min := 0
		for _, a := range arr {
			if a+op < m {
				if a+op < min {
					return false
				}
				if a > min {
					min = a
				}
			}
		}
		return true
	})
	Fprintln(out, ans)
}

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