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]         // 当前颜色
		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"
	"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))
}


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


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 = (ans + base*psum[p]) % mod
			}
		}
		base = (base * 2) % mod
	}
	fmt.Println(ans)
}

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 += (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)
}


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


package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

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

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

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

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)
	n, k := NextInt(), NextInt()
	a := make([]int, n)
	cnt := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
	}
	sort.Ints(a)

	nl := 0
	for i := 0; i < n; i++ {
		if i == 0 || a[i] != a[i-1] {
			a[nl] = a[i]
			cnt[nl] = 0
			nl++
		}
		cnt[nl-1]++
		if cnt[nl-1] >= k {
			fmt.Fprintln(out, 0)
			return
		}
	}
	n = nl

	leftSum, rightSum := make([]int64, n), make([]int64, n)
	leftCnt, rightCnt := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		if i == 0 {
			leftSum[i] = 0
			leftCnt[i] = cnt[i]
			rightSum[n-i-1] = 0
			rightCnt[n-i-1] = cnt[n-i-1]
		} else {
			leftSum[i] = leftSum[i-1] + int64(a[i]-a[i-1])*int64(leftCnt[i-1])
			leftCnt[i] = leftCnt[i-1] + cnt[i]
			rightSum[n-i-1] = rightSum[n-i] + int64(a[n-i]-a[n-i-1])*int64(rightCnt[n-i])
			rightCnt[n-i-1] = rightCnt[n-i] + cnt[n-i-1]
		}
	}

	var res int64
	res = 1000000000000000000
	// stderr(leftSum)
	// stderr(leftCnt)
	// stderr(rightSum)
	// stderr(rightCnt)
	for i := 0; i < n; i++ {
		var leftsum int64
		leftcount := 0
		dl := 0
		if i > 0 {
			dl = a[i] - a[i-1]
			leftsum = leftSum[i-1]
			leftcount = leftCnt[i-1]
		}
		var rightsum int64
		rightcount := 0
		dr := 0
		if i+1 < n {
			dr = a[i+1] - a[i]
			rightsum = rightSum[i+1]
			rightcount = rightCnt[i+1]
		}
		// stderr("i = ", i, "left", leftcount, leftsum, dl, "right", rightcount, rightsum, dr)
		// stderr(cnt[i])
		if rightcount >= k {
			res = mini64(res, rightsum)
		}
		if leftcount >= k {
			res = mini64(res, leftsum)
		}
		if leftcount+cnt[i] >= k {
			cur := leftsum + int64(k-cnt[i]) + int64(leftcount)*int64(dl-1)
			res = mini64(res, cur)
		}
		if rightcount+cnt[i] >= k {
			cur := rightsum + int64(k-cnt[i]) + int64(rightcount)*int64(dr-1)
			res = mini64(res, cur)
		}
		if leftCnt[i] < k && rightcount >= k-leftCnt[i] {
			cur := leftSum[i] + int64(k-leftCnt[i]) + int64(rightcount)*int64(dr-1) + rightsum
			res = mini64(res, cur)
		}
		if rightCnt[i] < k && leftcount >= k-rightCnt[i] {
			cur := rightSum[i] + int64(k-rightCnt[i]) + int64(leftcount)*int64(dl-1) + leftsum
			res = mini64(res, cur)
		}
	}
	fmt.Fprintln(out, res)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1328F(_r io.Reader, out io.Writer) {
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	var n, k int64
	Fscan(in, &n, &k)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	sort.Ints(a)
	s := make([]int64, n+1)
	for i, v := range a {
		s[i+1] = s[i] + int64(v)
	}
	ans := int64(1e18)
	for i := int64(0); i < n; {
		st := i
		for i++; i < n && a[i] == a[st]; i++ {
		}
		d := k - i + st
		if d <= 0 {
			ans = 0
			break
		}
		v := int64(a[st])
		s1, s2 := (v-1)*st-s[st], s[n]-s[i]-(v+1)*(n-i)
		if i >= k {
			ans = min(ans, s1+d)
		}
		if n-st >= k {
			ans = min(ans, s2+d)
		}
		ans = min(ans, s1+s2+d)
	}
	Fprint(out, ans)
}

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

package main

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

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

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

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

var stdin = NewWordScanner(os.Stdin)
var stdout = NewBufferedWriter(os.Stdout)

type Int64Sorter []int64

func (i Int64Sorter) Len() int {
	return len(i)
}
func (i Int64Sorter) Less(a, b int) bool {
	return i[a] < i[b]
}
func (i Int64Sorter) Swap(a, b int) {
	i[a], i[b] = i[b], i[a]
}

func main() {
	defer stdout.Flush()
	n, k := stdin.NextInt64(), stdin.NextInt64()
	m := map[int64]int64{}
	for i := int64(0); i < n; i++ {
		a := stdin.NextInt64()
		m[a]++
		if m[a] == k {
			stdout.Printf("0\n")
			return
		}
	}
	u := []int64{}
	for v := range m {
		u = append(u, v)
	}
	sort.Sort(Int64Sorter(u))

	solver := &Solver{
		counts: m,
		vals:   u,
		n:      n,
		k:      k,
	}

	stdout.Printf("%d\n", solver.Solve())
}

type Solver struct {
	counts map[int64]int64
	vals   []int64
	n      int64
	k      int64
}

func (s *Solver) Solve() int64 {
	ln := make([]int64, len(s.vals))
	lc := make([]int64, len(s.vals))
	rn := make([]int64, len(s.vals))
	rc := make([]int64, len(s.vals))
	ln[0] = 0
	lc[0] = 0
	rn[len(s.vals)-1] = 0
	rc[len(s.vals)-1] = 0
	for i := 1; i < len(s.vals); i++ {
		ln[i] = ln[i-1] + s.counts[s.vals[i-1]]
		lc[i] = lc[i-1] + (ln[i] * (s.vals[i]-s.vals[i-1]))
	}
	for i := len(s.vals) - 2; i > -1; i-- {
		rn[i] = rn[i+1] + s.counts[s.vals[i+1]]
		rc[i] = rc[i+1] + (rn[i] * (s.vals[i+1]-s.vals[i]))
	}

    minSoFar := lc[0] + rc[0]
    for i := 1; i < len(s.vals); i++ {
        cost := lc[i] + rc[i]
        minSoFar = min(minSoFar, cost)
    }
    if s.n == s.k {
        return minSoFar
    } else {
        minSoFar -= (s.n - s.k)
    }

    var leftRes int64
    for i := 0; i < len(lc); i++ {
        totalSame := ln[i] + s.counts[s.vals[i]]
        if totalSame >= s.k {
            diff := totalSame - s.k
            cost := lc[i]
            leftRes = cost - diff
            break
        }
    }

    var rightRes int64
    for i := len(rc)-1; i > -1; i-- {
        totalSame := rn[i] + s.counts[s.vals[i]]
        if totalSame >= s.k {
            diff := totalSame - s.k
            cost := rc[i]
            rightRes = cost - diff
            break
        }
    }

    return min(minSoFar, leftRes, rightRes)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1328F(_r io.Reader, out io.Writer) {
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	var n, k int
	Fscan(in, &n, &k)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	sort.Ints(a)
	s := make([]int64, n+1)
	for i, v := range a {
		s[i+1] = s[i] + int64(v)
	}
	ans := int64(1e18)
	for i := 0; i < n; {
		st, v := i, a[i]
		for i++; i < n && a[i] == v; i++ {
		}
		if i-st >= k {
			ans = 0
			break
		}
		if i >= k {
			ss := int64(v-1)*int64(st) - s[st]
			ss += int64(k - i + st)
			ans = min(ans, ss)
		}
		if n-st >= k {
			ss := s[n] - s[i] - int64(v+1)*int64(n-i)
			ss += int64(k - i + st)
			ans = min(ans, ss)
		}
		ss := int64(v-1)*int64(st) - s[st]
		ss += s[n] - s[i] - int64(v+1)*int64(n-i)
		ss += int64(k - i + st)
		ans = min(ans, ss)
	}
	Fprint(out, ans)
}

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

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

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

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

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

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)
	n, k := NextInt(), NextInt()
	a := make([]int, n)
	cnt := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
	}
	sort.Ints(a)

	nl := 0
	for i := 0; i < n; i++ {
		if i == 0 || a[i] != a[i-1] {
			a[nl] = a[i]
			cnt[nl] = 0
			nl++
		}
		cnt[nl-1]++
		if cnt[nl-1] >= k {
			fmt.Fprintln(out, 0)
			return
		}
	}
	n = nl

	leftSum, rightSum := make([]int64, n), make([]int64, n)
	leftCnt, rightCnt := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		if i == 0 {
			leftSum[i] = 0
			leftCnt[i] = cnt[i]
			rightSum[n-i-1] = 0
			rightCnt[n-i-1] = cnt[n-i-1]
		} else {
			leftSum[i] = leftSum[i-1] + int64(a[i]-a[i-1])*int64(leftCnt[i-1])
			leftCnt[i] = leftCnt[i-1] + cnt[i]
			rightSum[n-i-1] = rightSum[n-i] + int64(a[n-i]-a[n-i-1])*int64(rightCnt[n-i])
			rightCnt[n-i-1] = rightCnt[n-i] + cnt[n-i-1]
		}
	}

	var res int64
	res = 1000000000000000000
	// stderr(leftSum)
	// stderr(leftCnt)
	// stderr(rightSum)
	// stderr(rightCnt)
	for i := 0; i < n; i++ {
		var leftsum int64
		leftcount := 0
		dl := 0
		if i > 0 {
			dl = a[i] - a[i-1]
			leftsum = leftSum[i-1]
			leftcount = leftCnt[i-1]
		}
		var rightsum int64
		rightcount := 0
		dr := 0
		if i+1 < n {
			dr = a[i+1] - a[i]
			rightsum = rightSum[i+1]
			rightcount = rightCnt[i+1]
		}
		// stderr("i = ", i, "left", leftcount, leftsum, dl, "right", rightcount, rightsum, dr)
		// stderr(cnt[i])
		if rightcount >= k {
			res = mini64(res, rightsum)
		}
		if leftcount >= k {
			res = mini64(res, leftsum)
		}
		if leftcount+cnt[i] >= k {
			cur := leftsum + int64(k-cnt[i])*int64(dl)
			res = mini64(res, cur)
		}
		if rightcount+cnt[i] >= k {
			cur := rightsum + int64(k-cnt[i])*int64(dr)
			res = mini64(res, cur)
		}
		if leftCnt[i] < k && rightcount >= k-leftCnt[i] {
			cur := leftSum[i] + int64(k-leftCnt[i])*int64(dr) + rightsum
			res = mini64(res, cur)
		}
		if rightCnt[i] < k && leftcount >= k-rightCnt[i] {
			cur := rightSum[i] + int64(k-rightCnt[i])*int64(dl) + leftsum
			res = mini64(res, cur)
		}
	}
	fmt.Fprintln(out, res)
}

package main

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

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

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

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

var stdin = NewWordScanner(os.Stdin)
var stdout = NewBufferedWriter(os.Stdout)

type Int64Sorter []int64

func (i Int64Sorter) Len() int {
	return len(i)
}
func (i Int64Sorter) Less(a, b int) bool {
	return i[a] < i[b]
}
func (i Int64Sorter) Swap(a, b int) {
	i[a], i[b] = i[b], i[a]
}

func main() {
	defer stdout.Flush()
	n, k := stdin.NextInt64(), stdin.NextInt64()
	m := map[int64]int64{}
	for i := int64(0); i < n; i++ {
		a := stdin.NextInt64()
		m[a]++
		if m[a] == k {
			stdout.Printf("0\n")
			return
		}
	}
	u := []int64{}
	for v := range m {
		u = append(u, v)
	}
	sort.Sort(Int64Sorter(u))

	solver := &Solver{
		counts: m,
		vals:   u,
		n:      n,
		k:      k,
	}

	stdout.Printf("%d\n", solver.Solve())
}

type Solver struct {
	counts map[int64]int64
	vals   []int64
	n      int64
	k      int64
}

func (s *Solver) Solve() int64 {
	ln := make([]int64, len(s.vals))
	lc := make([]int64, len(s.vals))
	rn := make([]int64, len(s.vals))
	rc := make([]int64, len(s.vals))
	ln[0] = 0
	lc[0] = 0
	rn[len(s.vals)-1] = 0
	rc[len(s.vals)-1] = 0
	for i := 1; i < len(s.vals); i++ {
		ln[i] = ln[i-1] + s.counts[s.vals[i-1]]
		lc[i] = lc[i-1] + (ln[i] * (s.vals[i]-s.vals[i-1]))
	}
	for i := len(s.vals) - 2; i > -1; i-- {
		rn[i] = rn[i+1] + s.counts[s.vals[i+1]]
		rc[i] = rc[i+1] + (rn[i] * (s.vals[i+1]-s.vals[i]))
	}
	minSoFar := lc[0] + rc[0]
	for i := 1; i < len(s.vals); i++ {
		cost := lc[i] + rc[i]
		minSoFar = min(minSoFar, cost)
	}
	return minSoFar - (s.n-s.k)
}

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

package main

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

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

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

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

var stdin = NewWordScanner(os.Stdin)
var stdout = NewBufferedWriter(os.Stdout)

type Int64Sorter []int64

func (i Int64Sorter) Len() int {
	return len(i)
}
func (i Int64Sorter) Less(a, b int) bool {
	return i[a] < i[b]
}
func (i Int64Sorter) Swap(a, b int) {
	i[a], i[b] = i[b], i[a]
}

func main() {
	defer stdout.Flush()
	n, k := stdin.NextInt64(), stdin.NextInt64()
	m := map[int64]int64{}
	for i := int64(0); i < n; i++ {
		a := stdin.NextInt64()
		m[a]++
		if m[a] == k {
			stdout.Printf("0\n")
			return
		}
	}
	u := []int64{}
	for v := range m {
		u = append(u, v)
	}
	sort.Sort(Int64Sorter(u))

	solver := &Solver{
		counts: m,
		vals:   u,
		n:      n,
		k:      k,
	}

	stdout.Printf("%d\n", solver.Solve())
}

type Solver struct {
	counts map[int64]int64
	vals   []int64
	n      int64
	k      int64
}

func (s *Solver) Solve() int64 {
	ln := make([]int64, len(s.vals))
	lc := make([]int64, len(s.vals))
	rn := make([]int64, len(s.vals))
	rc := make([]int64, len(s.vals))
	ln[0] = 0
	lc[0] = 0
	rn[len(s.vals)-1] = 0
	rc[len(s.vals)-1] = 0
	for i := 1; i < len(s.vals); i++ {
		ln[i] = ln[i-1] + s.counts[s.vals[i-1]]
		lc[i] = lc[i-1] + ln[i]
	}
	for i := len(s.vals) - 2; i > -1; i-- {
		rn[i] = rn[i+1] + s.counts[s.vals[i+1]]
		rc[i] = rc[i+1] + rn[i]
	}
	minSoFar := lc[0] + rc[0]
	for i := 1; i < len(s.vals); i++ {
		cost := lc[i] + rc[i]
		minSoFar = min(minSoFar, cost)
	}
	return minSoFar - (s.n-s.k)
}

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