import scala.collection.mutable
import scala.io.StdIn

object Codeforces1163B {

  def getLongestPossibleStreak(n: Int, u: Seq[Int]): Int = {
    val isStreak = new Array[Boolean](n)
    val colorFrequencyMap = new mutable.HashMap[Int, Int]()
    val countTracker = new FrequencyCountTracker
    for (i <- 0 until n) {
      val previousFrequency = colorFrequencyMap.getOrElse(u(i), 0)
      colorFrequencyMap(u(i)) = previousFrequency + 1

      countTracker.decreaseCount(previousFrequency)
      countTracker.increaseCount(previousFrequency + 1)

      isStreak(i) = countTracker.isEqualFrequencyByRemovingOne
    }
    for (i <- isStreak.indices.reverse) {
      if (isStreak(i)) return i + 1
    }
    1
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val u = StdIn.readLine().trim.split(" ").map(_.toInt)
    val longestPossibleStreak = getLongestPossibleStreak(n, u)
    println(longestPossibleStreak)
  }

  class FrequencyCountTracker {
    val frequencyCountMap = new mutable.HashMap[Int, Int]()

    def increaseCount(frequency: Int): Unit = {
      val previousFrequencyCount = frequencyCountMap.getOrElse(frequency, 0)
      frequencyCountMap(frequency) = previousFrequencyCount + 1
    }

    def decreaseCount(frequency: Int): Unit = {
      if (frequency == 0) return
      val previousFrequencyCount = frequencyCountMap(frequency)
      previousFrequencyCount match {
        case 1 => frequencyCountMap.remove(frequency)
        case _ => frequencyCountMap(frequency) = previousFrequencyCount - 1
      }
    }

    def isEqualFrequencyByRemovingOne: Boolean = {
      frequencyCountMap.keys.size match {
        case 1 =>
          frequencyCountMap.keys.head == 1 || frequencyCountMap.values.head == 1
        case 2 =>
          val maxFrequency = frequencyCountMap.keys.max
          val minFrequency = frequencyCountMap.keys.min
          if (minFrequency == 1 && frequencyCountMap(minFrequency) == 1) true
          else if (minFrequency == maxFrequency - 1 && frequencyCountMap(maxFrequency) == 1) true
          else false
        case _ =>
          false
      }
    }
  }

}

object _1163B1 extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val nums = io.read[Vector[Int]]

    val numToCount, countToMap = mutable.Map.empty[Int, Int].withDefaultValue(0)
    val ans = nums map {i =>
      val curr = numToCount(i)
      if (curr > 0) {
        countToMap(curr) -= 1
        if (countToMap(curr) <= 0) countToMap.remove(curr)
      }
      numToCount(i) = curr + 1
      countToMap(curr + 1) += 1

      val it = countToMap.keysIterator

      val res = countToMap.size match {
        case 1 =>
          val c1 = it.next()
          c1 == 1 || countToMap(c1) == 1
        case 2 =>
          val _c1, _c2 = it.next()
          val c1 = _c1 min _c2
          val c2 = _c1 max _c2

          ((c1 == 1) && countToMap(c1) == 1) ||
          (c1 == c2 - 1 && countToMap(c2) == 1)
        case _ => false
      }
      //debug(i, numToCount, countToMap, res)
      res
    }

    io.write(ans.lastIndexWhere(identity) + 1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val C = Array.ofDim[Int](1e5.toInt)
    val D = mutable.Map[Int, Int]()
    var ans = 0
    var mx = 0
    REP(N) { i =>
      val u = ni() - 1

      if (D.contains(C(u))) {
        D(C(u)) = D(C(u)) - 1
        if (D(C(u)) == 0) D.remove(C(u))
      }

      C(u) += 1
      mx = max(mx, C(u))

      if (!D.contains(C(u))) D(C(u)) = 0
      D(C(u)) = D(C(u)) + 1

      if (D.size == 2) {
        // 最大を一つ減らせばいい
        if (D(mx) == 1 && D.contains(mx - 1)) {
          ans = i + 1
        // 1を一つ減らせばいい
        } else if (D.contains(1) && D(1) == 1) {
          ans = i + 1
        }
      } else if (D.size == 1) {
        if (mx == 1 || D(mx) == 1) {
          ans = i + 1
        }
      }
    }

    out.println(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val C = Array.ofDim[Int](1e5.toInt)
    val D = mutable.Map[Int, Int]()
    var ans = 0
    var mx = 0
    REP(N) { i =>
      val u = ni() - 1

      if (D.contains(C(u))) {
        D(C(u)) = D(C(u)) - 1
        if (D(C(u)) == 0) D.remove(C(u))
      }

      C(u) += 1
      mx = max(mx, C(u))

      if (!D.contains(C(u))) D(C(u)) = 0
      D(C(u)) = D(C(u)) + 1

      if (D.size == 2) {
        // 最大を一つ減らせばいい
        if (D(mx) == 1 && D.contains(mx - 1)) {
          ans = i + 1
        // 1を一つ減らせばいい
        } else if (D.contains(1) && D(1) == 1) {
          ans = i + 1
        }
      } else if (D.size == 1) {
        if (mx == 1) {
          ans = i + 1
        }
      }
    }

    out.println(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val C = Array.ofDim[Int](1e5.toInt)
    val D = mutable.Map[Int, Int]()
    var ans = 0
    var mx = 0
    REP(N) { i =>
      val u = ni() - 1
      C(u) += 1
      mx = max(mx, C(u))
      if (!D.contains(C(u))) D(C(u)) = 0
      D(C(u)) = D(C(u)) + 1
      if (C(u) - 1 > 0) {
        D(C(u) - 1) = D(C(u) - 1) - 1
        if (D(C(u) - 1) == 0) D.remove(C(u) - 1)
      }

      if (D.size == 2) {
        // 最大を一つ減らせばいい
        if (D(mx) == 1 && D.contains(mx - 1)) {
          ans = i + 1
        // 1を一つ減らせばいい
        } else if (D.contains(1) && D(1) == 1) {
          ans = i + 1
        }
      } else if (D.size == 1) {
        if (mx == 1) {
          ans = i + 1
        }
      }
    }

    out.println(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val C = Array.ofDim[Int](1e5.toInt)
    val D = mutable.Map[Int, Int]()
    var ans = 0
    var mx = 0
    REP(N) { i =>
      val u = ni() - 1
      C(u) += 1
      mx = max(mx, C(u))
      if (!D.contains(C(u))) D(C(u)) = 0
      D(C(u)) += 1
      if (C(u) - 1 > 0) {
        D(C(u) - 1) -= 1
        if (D(C(u) - 1) == 0) D.remove(C(u) - 1)
      }

      if (D.size == 2) {
        // 最大を一つ減らせばいい
        if (D(mx) == 1 && D.contains(mx - 1)) {
          ans = i + 1
        // 1を一つ減らせばいい
        } else if (D.contains(1) && D(1) == 1) {
          ans = i + 1
        }
      } else if (D.size == 1) {
        if (mx == 1) ans = i + 1
      }
    }

    out.println(ans)
  }
}


object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val s = readLine
  println(s + s.reverse)
}

object A932 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    var tests = 1 // readInt
    while(tests > 0) {
      val n = read
      out.print(n)
      out.println(n.reverse)
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object A extends App {
  val a = scala.io.StdIn.readLine()
  def b(a: String): String = {
    def _b(l: List[Char], r: List[Char], i: Int, j: Int): String =
      if (i > j) l.reverse.mkString("") + r.mkString("")
      else {
        val ai = a(i)
        val aj = a(j)
        if (ai == aj) _b(ai :: l, aj :: l, i + 1, j - 1)
        else _b(ai :: l, ai :: l, i + 1, j)
      }

    _b(Nil, Nil, 0, a.length - 1)
  }

  println(b(a))
}

object _932A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO): io.type = {
    val a = io.read[String]
    io.write(a + a.reverse)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(p._2))
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    //def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


object P102B extends App {
  def f(n: String) = n.toCharArray.map(_.getNumericValue).sum.toString()
  var n = readLine
  var c = 0
  while (n.size > 1) {
    n = f(n)
    c += 1
  }
  print(c)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next()
  var sum = data.foldLeft(0l){case (acc, el) => acc + el.asDigit}
  var i = 0
  if (data.length != 1) {
    i = 1
    while (sum > 9) {
      i += 1
      sum = sum.toString.foldLeft(0l) { case (acc, el) => acc + el.asDigit }
    }
  }
  println(i)
}

object Main {
  def main(args: Array[String]) {
    var n = readLine()
    var step = 0
    while(n.size != 1) {
      val sum = n.map(_.toLong - '0').sum
      n = sum.toString
      step += 1
    }
    println(step)
  }
}

object Solver {
    def main(args: Array[String]) {
        var data = Console.readLine
        var count = 0

        while (data.length > 1) {
            data = data.map(_.toInt - '0'.toInt).reduceRight(_ + _).toString
            count += 1
        }
        println(count)
    }
}


object _1729C extends CodeForcesAppMulti({io =>
  import Math._
  val line = io.nextLine().toSeq.map(_ - 'a' + 1)
  val n = line.length
  val (start, end) = (line(0), line(n-1))
  var indexed = line.zipWithIndex
    .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})
    .drop(1).dropRight(1).sorted

  if (start > end) indexed = indexed.reverse
  val cost = (start - end).abs
  val m = indexed.length + 2
  val ans = indexed.map(_._2).mkString(" ")

  io.printLine(
    s"$cost $m",
    s"1 $ans $n".replace("  ", " ")
  )
})
/**************************** [Ignore Template Below] **************************************/
class CodeForcesApp(solution: IO => Any) {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solution(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
}
class CodeForcesAppMulti(solution: IO => Any) extends CodeForcesApp(solution) {
  override def run(io: IO) = try io.repeat()(solution(io)) finally io.close()
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): Unit = out.print(xs.mkString(" "))
  def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)

  override def close() = out.close()
}

object _1729C extends CodeForcesApp{
  import Math._
  override def solve(io: IO) = io.repeat() {
    val line = io.nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n - 1))
    var indexed = line.zipWithIndex
      .collect({ case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i + 1) })
      .drop(1).dropRight(1).sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    io.print(cost, m).printLine().print(1, ans, n).printLine()
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

  override def close() = out.close()
}

object _1729C extends CodeForcesApp{
  import Math._
  override def solve(io: IO) = io.repeat() {
    val line = io.nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n - 1))
    var indexed = line.zipWithIndex
      .collect({ case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i + 1) })
      .drop(1).dropRight(1).sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    io.printLine(
      s"$cost $m",
      s"1 $ans $n".replace("  ", " ")
    )
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): Unit = out.print(xs.mkString(" "))
  def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)

  override def close() = out.close()
}

object _1729C extends CodeForcesApp({io =>
  import Math._

  io.repeat() {
    val line = io.nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n-1))
    var indexed = line.zipWithIndex
      .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})
      .drop(1).dropRight(1).sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    io.printLine(
      s"$cost $m",
      s"1 $ans $n".replace("  ", " ")
    )
  }
})
/**************************** [Ignore Template Below] **************************************/
class CodeForcesApp(solution: IO => Any) {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solution(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))
  override def close() = out.close()
  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))
  // input utils
  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }
  //output utils
  def print(xs: Any*): Unit = out.print(xs.mkString(" "))
  def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)
}

import scala.annotation.tailrec

object _1729C extends CodeForcesApp {
  import Math._

  override def solve() = repeat() {
    val line = nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n-1))
    var indexed = line.zipWithIndex
      .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})
      .drop(1).dropRight(1).sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    printLine(
      s"$cost $m",
      s"1 $ans $n".replace("  ", " ")
    )
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  import java.io._
  private var in = new BufferedReader(new InputStreamReader(System.in))
  private var out = new PrintWriter(System.out)

  def setIO(inputFile: File, outputFile: File): Unit = {
    in = new BufferedReader(new FileReader(inputFile))
    out = new PrintWriter(new FileWriter(outputFile))
  }

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: String)(res: => A): A = {printLine(query); out.flush(); res}

  def print(xs: Any*): Unit = out.print(xs.mkString(" "))
  def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")

  def main(args: Array[String]): Unit = try solve() finally out.flush()
  def solve(): Any
}

object _1729C extends CodeForcesApp {
  import Math._

  override def solve() = repeat() {
    val line = nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n-1))
    var indexed = line.zipWithIndex.collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})
      .drop(1).dropRight(1)
      .sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    out.println(s"$cost $m")
    out.println(s"1 $ans $n".replace("  ", " "))
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  import java.io._
  var in = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: String, res: => A): A = {out.println(query); out.flush(); res}

  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def illegal(msg: String = "can't happen") = throw new IllegalStateException(msg)

  def main(args: Array[String]): Unit = try solve() finally out.flush()
  def solve(): Any
}

object _1729C extends CodeForcesApp {
  import Math._

  override def solve() = repeat() {
    val line = nextLine().toSeq.map(_ - 'a' + 1)
    val (start, end) = (line.head, line.last)
    var indexed = line.zipWithIndex.collect({case (n, i) if min(start, end) <= n && n <= max(start, end) => (n, i+1)}).sorted
    if (end < start) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length
    val ans = indexed.map(_._2).mkString(" ")
    out.println(s"$cost $m")
    out.println(ans)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  import java.io._
  var in = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: String, res: => A): A = {out.println(query); out.flush(); res}

  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def illegal(msg: String = "can't happen") = throw new IllegalStateException(msg)

  def main(args: Array[String]): Unit = try solve() finally out.flush()
  def solve(): Any
}


object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    import java.util
    val N, M = ni()
    val (p, c) = na2(N)

    var vote1 = 0
    val V = Array.fill[java.util.ArrayList[Integer]](M)(new util.ArrayList())
    REP(N) { i =>
      if (p(i) == 1) vote1 += 1
      else V(p(i) - 1).add(c(i))
    }
    REP(M) { i =>
      import java.util.Collections
      Collections.sort(V(i))
    }

    val ans = map(N) { remain =>
      var res = 0L
      var cnt = 0
      var mx = 0
      val q = new java.util.PriorityQueue[Int]()
      REP(M) { m =>
        val v = V(m)
        val n = v.size()

        val del = if (n > remain) v.size - remain else 0
        REP(del) { k =>
          res += v.get(k)
          cnt += 1
        }
        REP(n) { k =>
          if (k >= del) q.add(v.get(k))
        }
        mx = max(mx, n - del)
      }

      if (vote1 + cnt <= mx) {
        REP(mx + 1 - vote1 - cnt) { _ =>
          res += q.poll()
        }
      }

      res
    }.min

    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import scala.collection.mutable.PriorityQueue
import java.security.SecureRandom

object CF_503_C {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//  println(Test.big)
//    runTest(Test.big)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line = readLine
    val n = line.int
    val m = line.int
    val vArr = new Array[(Int, Int)](n)
    val pArr = new Array[Int](m+1)
    var pQ = Array.fill[List[Int]](m+1)(List())
    (0 until n).foreach(x => {
      val vLine = readLine
      val p = vLine.int
      val money = vLine.int
      vArr(x) = (p, money)
      pArr(p) += 1
      pQ(p) ::= money
    })

    pQ = pQ.map(_.sorted)

    val from = if (m == 1) pArr(1) else pArr.drop(2).min+1
    val levels = (from to pArr.max+1)

    val variants = levels.map{ l =>
      debug("level=" + l)
      val parts = pArr.clone()
      val prices = pQ.clone
      var variant = 0l
      (2 to m).foreach{ pp =>
        while (parts(pp) >= l) {
          val vv = prices(pp).head;
          prices(pp) = prices(pp).tail
//          debug(s" take from $pp - $vv")
          parts(1) += 1
          parts(pp) -= 1
          variant += vv
        }
      }
      val toTakeFromLeft = if (parts(1) < l) l - parts(1) else 0
      var ll: List[(Int, Int)] = List()
      for(i <- 2 until prices.length) {
        prices(i).foreach(lp => ll ::= (lp, i) )
      }

      val left2 = ll.toArray.sorted.take(toTakeFromLeft)

//      val unsortedLeft = prices.zipWithIndex.drop(2).flatMap(x => x._1.map(y => (y, x._2)))
//      val left = unsortedLeft.sortBy(_._1).take(toTakeFromLeft)
      left2.foreach{ x =>
//        debug(s" take left from ${x._2} - ${x._1}")
        parts(1) += 1
        parts(x._2) -= 1
        variant += x._1
      }

      val maxLeft = if (m == 1) 0 else parts.drop(2).max
      if (maxLeft >= parts(1)) -1
      else variant

    }.filterNot(_ == -1)

    outLn(variants.min+"")

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
1 2
1 100
"""

val sa2 = """
5 5
2 100
3 200
4 300
5 400
5 900
""" //500

val sa3 = """
5 5
2 100
3 200
4 300
5 800
5 900
""" //600

val big = {
    var rr = "3000 3000\n"
    for (i <- 1 to 3000) {
      rr += "3000 " + new SecureRandom().nextInt().abs + "\n"
    }
    rr
  }

}

}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    import java.util
    val N, M = ni()
    val (p, c) = na2(N)

    var vote1 = 0
    val V = Array.fill[java.util.ArrayList[Integer]](M)(new util.ArrayList())
    REP(N) { i =>
      if (p(i) == 1) vote1 += 1
      else V(p(i) - 1).add(c(i))
    }
    REP(M) { i =>
      import java.util.Collections
      Collections.sort(V(i))
    }

    val ans = map(N) { remain =>
      var res = 0
      var cnt = 0
      var mx = 0
      val q = new java.util.PriorityQueue[Int]()
      REP(M) { m =>
        val v = V(m)
        val n = v.size()

        val del = if (n > remain) v.size - remain else 0
        REP(del) { k =>
          res += v.get(k)
          cnt += 1
        }
        REP(n) { k =>
          if (k >= del) q.add(v.get(k))
        }
        mx = max(mx, n - del)
      }

      if (vote1 + cnt <= mx) {
        REP(mx + 1 - vote1 - cnt) { _ =>
          res += q.poll()
        }
      }

      res
    }.min

    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import scala.collection.mutable.PriorityQueue

object CF_503_C {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa3)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line = readLine
    val n = line.int
    val m = line.int
    val vArr = new Array[(Int, Int)](n)
    val pArr = new Array[Int](m+1)
    val pQ = Array.fill[List[Int]](m+1)(List())
    (0 until n).foreach(x => {
      val vLine = readLine
      val p = vLine.int
      val money = vLine.int
      vArr(x) = (p, money)
      pArr(p) += 1
//      if (pQ(p) == null) {
//        pQ(p) = PriorityQueue()(Ordering.Int.reverse)
//      }
//      pQ(p).enqueue(money)
      pQ(p) ::= money
    })

    pQ.map(_.sorted)

    val levels = (pArr.drop(2).min+1 to pArr.max+1)

    val variants = levels.map{ l =>
      debug("level=" + l)
      val parts = pArr.clone()
      val prices = pQ.clone
      var variant = 0
      (2 to m).foreach{ pp =>
        while (parts(pp) >= l) {
          val vv = prices(pp).head;
          prices(pp) = prices(pp).tail
          debug(s" take from $pp - $vv")
          parts(1) += 1
          parts(pp) -= 1
          variant += vv
        }
      }
      val toTakeFromLeft = if (parts(1) < l) l - parts(1) else 0
      val unsortedLeft = prices.zipWithIndex.drop(2).flatMap(x => x._1.map(y => (y, x._2)))
      val left = unsortedLeft.sortBy(_._1).take(toTakeFromLeft)
      left.foreach{ x =>
        debug(s" take left from ${x._2} - ${x._1}")
        parts(1) += 1
        parts(x._2) -= 1
        variant += x._1
      }

      val maxLeft = parts.drop(2).max
      if (maxLeft >= parts(1)) -1
      else variant

    }.filterNot(_ == -1)

    outLn(variants.min)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
1 2
1 100
"""

val sa2 = """
5 5
2 100
3 200
4 300
5 400
5 900
""" //500

val sa3 = """
5 5
2 100
3 200
4 300
5 800
5 900
""" //600
}

}


object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextLong
  val s = (v.sorted, (1 to n)).zipped.map((x, y) => scala.math.abs(x - y)).sum
  out.println(s)

  out.flush
}

object Main {
  def main(args: Array[String]) {
    val n = readLong
    val a = readLine().split(" ").map(_.toLong)
    val count = a.sorted.zipWithIndex.foldLeft(0L) { (a, t) =>
      a + (t._2 + 1 - t._1).abs
    }
    println(count)
  }
}

import scala.annotation.tailrec
import scala.math._
object Main {

  def main(args: Array[String]): Unit = {
    val N = readInt()
    val list = readLine split (" ") map (_ toInt) sortWith (_ < _)
    val dList = 1.to(N).map(i => (list(i - 1) - i).abs.toLong);
    print(dList.sum)
  }
}

import scala.annotation.tailrec
import scala.math._
object Main {

  def main(args: Array[String]): Unit = {
    val N = readLine.toInt
    val list = readLine split (" ") map (_ toInt) sortWith (_ < _)
    @tailrec
    def loop(pos: Int = 0, ans: Long = 0): Long = {
      if (pos < list.length) {
        loop(pos + 1, ans + abs(list(pos) - (pos + 1)))
      } else {
        ans
      }
    }
    println(loop())
  }
}

import scala.annotation.tailrec
import scala.math._
object Main {

  def main(args: Array[String]): Unit = {
    val N = readInt()
    val list = readLine split(" ") map(_ toInt) sortWith(_ < _)

    @tailrec
    def loop(step: Int = 0, acc: Long = 0): Long = {
      if (step == N) {
        acc
      } else {
        loop(step + 1, acc + abs(list(step) - (step + 1)))
      }
    }
    val ans = loop()
    print(ans)
  }
}

import java.util.StringTokenizer

object _285C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toLong).sorted
  val b = (a zip (1 to n)).map(i => (i._1 - i._2).abs)
  println(b.sum)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var changes = 0l
  var counts = Array.ofDim[Int](n)
  data.foreach{i => if (i < 1) {
      counts(0) += 1
      changes += -i + 1
    } else if (i > n) {
      counts(n - 1) += 1
      changes += i - n
    } else {
      counts(i - 1) += 1
    }
  }
  var leftZero = 0
  while (leftZero != n && counts(leftZero) != 0)
    leftZero += 1
  var leftMoreOne = 0
  while (leftMoreOne != n && counts(leftMoreOne) < 2)
    leftMoreOne += 1

  while (leftZero < n && leftMoreOne < n) {

    changes += Math.abs(leftZero - leftMoreOne)
    counts(leftZero) = 1
    while (leftZero != n && counts(leftZero) != 0)
      leftZero += 1
    counts(leftMoreOne) -= 1
    while (leftMoreOne != n && counts(leftMoreOne) < 2)
      leftMoreOne += 1
  }

  println(changes)
}

object C285 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readLongs(n).sorted.zipWithIndex.map{case (x, y) => (x, y+1)}
    println(in.map{case (a, b) => math.abs(a-b)}.sum)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine;
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt
  val s = v.sorted.view.zip(1 to n).map(x => scala.math.abs(x._1 - x._2).toLong).sum
  out.println(s)

  out.flush
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextLong
  val s = v.sorted.view.zip(1 to n).map(x => scala.math.abs(x._1 - x._2)).sum
  out.println(s)

  out.flush
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt.toLong
  val s = v.sorted.view.zipWithIndex.map(x => scala.math.abs(x._1 - (x._2 + 1))).sum
  out.println(s)

  out.flush
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt
  val s = v.sorted.zip(1 to n).map(x => scala.math.abs(x._1 - x._2).toLong).sum
  out.println(s)

  out.flush
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P285C extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N = sc.nextInt
  val as0 = Array.fill(N)(sc.nextLong).sorted
  val as = new Array[Long](N + 1)
  as0.copyToArray(as, 1)

  val answer: Long = {
    @tailrec
    def loop(acc: Long, i: Int): Long =
      if (i > N) acc
      else loop(acc + math.abs(as(i) - i), i + 1)
    loop(0, 1)
  }

  out.println(answer)
  out.close
}

import scala.io.StdIn

object BuildingPermutation {

  def dist2(l:List[Long]):Long = {
    val n = l.length
    val ls = l.sorted
    val OneN = 1 to n

    ((OneN zip ls).map { x => Math.abs(x._1-x._2) }).sum
  }

  def dist(l:List[Long]):Long = {
    val n = l.length
    val ls = l.sorted
    val OneN = 1 to n
    //
    val minl = ls filter (x=>{x<=1})
    //System.err.println("minl:"+ minl)
    val maxl = ls filter (x=>{x>=n})
    //System.err.println("maxl:" + maxl)
    val midl = ls filter (x=>{x>1 && x<n})
    //System.err.println("midl:" + midl)

    val OneNLeft = OneN filter (x=>{!(midl contains x)})
    //System.err.println("OneNLeft:" + OneNLeft.toList)
    val common = OneN filter (x=>(midl contains x))
    //System.err.println("common:" + common)
    val midlLeft = midl diff common
    //System.err.println("mildLeft:" + midlLeft)

    val lowerOneNLeft = OneNLeft take (minl.length)
    //System.err.println("lowerOneNLeft:" + lowerOneNLeft.toList)

    val upperOneNLeft = OneNLeft takeRight (maxl.length)
   // System.err.println("upperOneNLeft:" + upperOneNLeft.toList)

    val midOneNLeft = OneNLeft.slice(minl.length, n-maxl.length)
    //System.err.println("midOneNLeft:" + midOneNLeft.toList)

    ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum +
    ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum +
    ((midlLeft zip midOneNLeft) map {x=>Math.abs(x._1-x._2)}).sum
  }

  def main(arg:Array[String]){
    val n = StdIn.readLine().toInt;
    val il:List[Long] = (StdIn.readLine().split(" ").map { x => x.toLong }).toList
    println(dist2(il))
  }
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val n = readInt
  def ans = readInts.sorted.zip(1 to n).map(_.productIterator.map(_.asInstanceOf[Int]).reduceLeft(_-_).abs.toLong).sum

  def main(args: Array[String]) {
    println(ans)
  }
}

import scala.annotation.tailrec
import scala.math._
object C
{
    def main(args: Array[String])
    {
        val n = readLine.toInt
        val a = readLine split(" ") map(_ toInt) sortWith(_ < _)
        @tailrec
        def solve(pos : Int = 0, ans : Long = 0): Long = {
            if(pos<a.length){
                solve(pos+1,ans+abs(a(pos)-(pos+1)))
            }
            else{ans}
        }
        println(solve())
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var changes = 0
  var counts = Array.ofDim[Int](n)
  data.foreach{i => if (i < 1) {
      counts(0) += 1
      changes += -i + 1
    } else if (i > n) {
      counts(n - 1) += 1
      changes += i - n
    } else {
      counts(i - 1) += 1
    }
  }
  var leftZero = 0
  while (leftZero != n && counts(leftZero) != 0)
    leftZero += 1
  var leftMoreOne = 0
  while (leftMoreOne != n && counts(leftMoreOne) < 2)
    leftMoreOne += 1

  while (leftZero < n && leftMoreOne < n) {

    changes += Math.abs(leftZero - leftMoreOne)
    counts(leftZero) = 1
    while (leftZero != n && counts(leftZero) != 0)
      leftZero += 1
    counts(leftMoreOne) -= 1
    while (leftMoreOne != n && counts(leftMoreOne) != 0)
      leftMoreOne += 1
  }

  println(changes)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var changes = 0
  var counts = Array.ofDim[Int](n)
  data.foreach{i => if (i < 1) {
      counts(0) += 1
      changes += -i + 1
    } else if (i > n) {
      counts(n - 1) += 1
      changes += i - n
    } else {
      counts(i - 1) += 1
    }
  }
  var leftZero = 0
  while (leftZero != n && counts(leftZero) != 0)
    leftZero += 1
  var leftMoreOne = 0
  while (leftMoreOne != n && counts(leftMoreOne) < 2)
    leftMoreOne += 1

  while (leftZero < n && leftMoreOne < n) {

    changes += Math.abs(leftZero - leftMoreOne)
    counts(leftZero) = 1
    while (leftZero != n && counts(leftZero) != 0)
      leftZero += 1
    counts(leftMoreOne) -= 1
    while (leftMoreOne != n && counts(leftMoreOne) < 2)
      leftMoreOne += 1
  }

  println(changes)
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt
  val s = v.sorted.zip(1 to n).map(x => scala.math.abs(x._1 - x._2)).sum
  out.println(s)

  out.flush
}

import scala.io.StdIn

object BuildingPermutation {

  def dist(l:List[Long]):Long = {
    val n = l.length
    val ls = l.sorted
    val OneN = 1 to n
    //
    val minl = ls filter (x=>{x<=1})
    //System.err.println("minl:"+ minl)
    val maxl = ls filter (x=>{x>=n})
    //System.err.println("maxl:" + maxl)
    val midl = ls filter (x=>{x>1 && x<n})
    //System.err.println("midl:" + midl)

    val OneNLeft = OneN filter (x=>{!(midl contains x)})
    //System.err.println("OneNLeft:" + OneNLeft.toList)
    val lowerOneNLeft = OneNLeft take (minl.length)
    //System.err.println("lowerOneNLeft:" + lowerOneNLeft.toList)
    val upperOneNLeft = OneNLeft takeRight (maxl.length)
    //System.err.println("upperOneNLeft:" + upperOneNLeft.toList)

    ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum +
    ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum
  }

  def main(arg:Array[String]){
    val n = StdIn.readLine().toInt;
    val il:List[Long] = (StdIn.readLine().split(" ").map { x => x.toLong }).toList
    println(dist(il))
  }
}

import scala.io.StdIn

object BuildingPermutation {

  def dist(l:List[Int]):Int = {
    val n = l.length
    val ls = l.sorted
    val OneN = 1 to n
    //
    val minl = ls filter (x=>{x<=1})
    System.err.println("minl:"+ minl)
    val maxl = ls filter (x=>{x>=n})
    System.err.println("maxl:" + maxl)
    val midl = ls filter (x=>{x>1 && x<n})
    System.err.println("midl:" + midl)

    val OneNLeft = OneN filter (x=>{!(midl contains x)})
    System.err.println("OneNLeft:" + OneNLeft.toList)
    val lowerOneNLeft = OneNLeft take (minl.length)
    System.err.println("lowerOneNLeft:" + lowerOneNLeft.toList)
    val upperOneNLeft = OneNLeft takeRight (maxl.length)
    System.err.println("upperOneNLeft:" + upperOneNLeft.toList)

    ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum +
    ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum
  }

  def main(arg:Array[String]){
    val n = StdIn.readLine().toInt;
    val il:List[Int] = (StdIn.readLine().split(" ").map { x => x.toInt }).toList
    println(dist(il))
  }
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val n = readInt
  def ans = readInts.sorted.zip(1 to n).map(_.productIterator.map(_.asInstanceOf[Int]).reduceLeft(_-_).abs).sum

  def main(args: Array[String]) {
    println(ans)
  }
}

import scala.annotation.tailrec
import scala.math._
object C
{
    def main(args: Array[String])
    {
        val n = readLine.toInt
        val a = readLine split(" ") map(_ toInt) sortWith(_ < _)
        @tailrec
        def solve(pos : Int = 0, ans : Int = 0): Int = {
            if(pos<a.length){
                solve(pos+1,ans+abs(a(pos)-(pos+1)))
            }
            else{ans}
        }
        println(solve())
    }
}

object Main {
  def main(args: Array[String]) {
    val n = readLong
    val a = readLine().split(" ").map(_.toLong)
    val step1 = a.foldLeft(0L) { (a, e) =>
      if (e < 1) a + 1 - e
      else if (e > n) a + e - n
      else a
    }
    val a1 = a.map{ e =>
      if (e < 1) 1
      else if (e > n) n
      else e
    }
    val step2 = (a1.sum - n * (n + 1) / 2).abs
    println(step1 + step2)
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val a = readLine().split(" ").map(_.toInt)
    val step1 = a.foldLeft(0) { (a, e) =>
      if (e < 1) a + 1 - e
      else if (e > n) a + e - n
      else a
    }
    val a1 = a.map{ e =>
      if (e < 1) 1
      else if (e > n) n
      else e
    }
    val step2 = (a1.sum - n * (n + 1) / 2).abs
    println(step1 + step2)
  }
}

import scala.annotation.tailrec
import scala.math._
object Main {

  def main(args: Array[String]): Unit = {
    val N = readInt()
    val list = readLine split (" ") map (_ toInt) sortWith (_ < _)
    val dList = 1.to(N).map(i => (list(i - 1) - i).abs);
    print(dList.sum)
  }
}


//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskC extends App {
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(y => {

    val splitted = readLine().split("")
    var a = 0
    var b = 0
   res(y) = 0
    splitted.foreach(x => {
      if (x == "(")
        a += 1
      else if(x == ")" && a > 0) {
        a-= 1
        res(y) +=1
      }else if(x == "[")
        b +=1
      else if(x == "]" && b > 0){
        b -=1
        res(y) +=1
      }
    })
  })

  (0 until sets).foreach(x => {
    println(res(x))
  })
}

import scala.io.StdIn._

object Main extends App {
  val t = readInt()
  // val t = 2
  (0 until t).foreach(_ => {
    val s = readLine()
    // val s = "[(])"
    val ans = run(s, '[', ']') + run(s, '(', ')')
    println(ans)
  })

  def run(s: String, a: Char, b: Char): Int = {
    var ans = 0
    var left = 0
    for (c <- s) {
      if (c == a) {
          left += 1
      } else if (c == b && left > 0) {
          ans += 1
          left -= 1
      }
    }
    ans
  }
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskC extends App{
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(a => {
   // println("        " + a)
    var splitted = readLine().split("")

    while (splitted.contains("[") && splitted.contains("]") ){
      val s = splitted.indexOf("[")
     // println("s: " + s)
      val f = splitted.indexOf("]")
     // println("f: " + f)

      //println(splitted)

     // println(splitted)
     // println()

      if (s< f) {
        res(a) += 1
        //println("+")
        splitted(s) = "a"
        splitted(f) = "a"
      }else{
        splitted(f) = "a"
      }
    }

    while(splitted.contains("(") && splitted.contains(")")) {

      val s = splitted.indexOf("(")
      //println("s: " + s)
      val f = splitted.indexOf(")")
      //println("f: " + f)

      splitted(s) = "a"
      splitted(f) = "a"

      //println(splitted)
     // println()
      if (s< f) {
        res(a) += 1
        //println("+")
        splitted(s) = "a"
        splitted(f) = "a"
      }else{
        splitted(f) = "a"
      }

    }

    /*val splitted = readLine().split("")
    val oc = splitted.count(x => x == "[")
    val cc = splitted.count(x => x == "]")
    val ob = splitted.count(x => x == "(")
    val cb = splitted.count(x => x == ")")

    var totalc = 0
    var totalb = 0

    var minc = 0
    var minb = 0
    (0 until splitted.length).foreach(x => {
      if(splitted(x) == "]") totalc-=1
      if(splitted(x) == "[") totalc+=1

      if(splitted(x) == ")") totalb-=1
      if(splitted(x) == "(") totalb+=1

      minc = min(totalc, minc)
      minb = min(totalb, minb)
    })

    val resi = min(oc, cc)+minc + min(ob, cb)+minb
    if (resi < 0) res(a) = 0
    else res(a) = resi*/

  })

  (0 until sets).foreach(x => {
    println(res(x))

  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._
import scala.math.min

object taskC extends App{
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(a => {
    val splitted = readLine().split("")
    val oc = splitted.count(x => x == "[")
    val cc = splitted.count(x => x == "]")
    val ob = splitted.count(x => x == "(")
    val cb = splitted.count(x => x == ")")

    var totalc = 0
    var totalb = 0

    var minc = 0
    var minb = 0
    (0 until splitted.length).foreach(x => {
      if(splitted(x) == "]") totalc-=1
      if(splitted(x) == "[") totalc+=1

      if(splitted(x) == ")") totalb-=1
      if(splitted(x) == "(") totalb+=1

      minc = min(totalc, minc)
      minb = min(totalb, minb)
    })

    val resi = min(oc, cc)+minc + min(ob, cb)+minb
    if (resi < 0) res(a) = 0
    else res(a) = resi

  })

  (0 until sets).foreach(x => {
    println(res(x))

  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskC extends App {
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(y => {

    val splitted = readLine().split("")
    var a = 0
    var b = 0
   res(y) = 0
    splitted.foreach(x => {
      if (x == "(")
        a += 1
      else if(x == ")" && a > 0) {
        a-= 1
        res(y) +=1
      }else if(x == "[")
        b +=1
      else if(b > 0){
        b -=1
        res(y) +=1
      }
    })
  })

  (0 until sets).foreach(x => {
    println(res(x))
  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._
import scala.math.min

object taskC extends App{
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(a => {
    var splitted = readLine().split("").toList

    while (splitted.contains("[") && splitted.contains("]") ){
      val s = splitted.indexOf("[")
      val f = splitted.indexOf("]")

      splitted = splitted.drop(s)
      splitted = splitted.drop(f)

      if (s< f) {
        res(a) += 1
      }
    }

    while(splitted.contains("(") && splitted.contains(")")) {

      val s = splitted.indexOf("(")
      val f = splitted.indexOf(")")

      splitted = splitted.drop(s)
      splitted = splitted.drop(f)

      if (s< f) {
        res(a) += 1
      }

    }

    /*val splitted = readLine().split("")
    val oc = splitted.count(x => x == "[")
    val cc = splitted.count(x => x == "]")
    val ob = splitted.count(x => x == "(")
    val cb = splitted.count(x => x == ")")

    var totalc = 0
    var totalb = 0

    var minc = 0
    var minb = 0
    (0 until splitted.length).foreach(x => {
      if(splitted(x) == "]") totalc-=1
      if(splitted(x) == "[") totalc+=1

      if(splitted(x) == ")") totalb-=1
      if(splitted(x) == "(") totalb+=1

      minc = min(totalc, minc)
      minb = min(totalb, minb)
    })

    val resi = min(oc, cc)+minc + min(ob, cb)+minb
    if (resi < 0) res(a) = 0
    else res(a) = resi*/

  })

  (0 until sets).foreach(x => {
    println(res(x))

  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskC extends App{
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(a => {
   // println("        " + a)
    var splitted = readLine().split("")

    while (splitted.contains("[") && splitted.contains("]") ){
      val s = splitted.indexOf("[")
     // println("s: " + s)
      val f = splitted.indexOf("]")
     // println("f: " + f)

      //println(splitted)
      splitted(s) = "a"
      splitted(f) = "a"

     // println(splitted)
     // println()

      if (s< f) {
        res(a) += 1
        //println("+")
      }
    }

    while(splitted.contains("(") && splitted.contains(")")) {

      val s = splitted.indexOf("(")
      //println("s: " + s)
      val f = splitted.indexOf(")")
      //println("f: " + f)

      splitted(s) = "a"
      splitted(f) = "a"

      //println(splitted)
     // println()
      if (s< f) {
        res(a) += 1
       // println("+")
      }

    }

    /*val splitted = readLine().split("")
    val oc = splitted.count(x => x == "[")
    val cc = splitted.count(x => x == "]")
    val ob = splitted.count(x => x == "(")
    val cb = splitted.count(x => x == ")")

    var totalc = 0
    var totalb = 0

    var minc = 0
    var minb = 0
    (0 until splitted.length).foreach(x => {
      if(splitted(x) == "]") totalc-=1
      if(splitted(x) == "[") totalc+=1

      if(splitted(x) == ")") totalb-=1
      if(splitted(x) == "(") totalb+=1

      minc = min(totalc, minc)
      minb = min(totalb, minb)
    })

    val resi = min(oc, cc)+minc + min(ob, cb)+minb
    if (resi < 0) res(a) = 0
    else res(a) = resi*/

  })

  (0 until sets).foreach(x => {
    println(res(x))

  })
}


object a992 {
  def main(args: Array[String]): Unit = {
    scala.io.StdIn.readLine()
    println(scala.io.StdIn.readLine().split(" ").filter(_!="0").distinct.length)
  }
}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val as = readInts(n)

  println(as.filter(_ != 0).distinct.size)
}

import scala.collection.mutable._
import scala.io.StdIn

object Solution {
  def main(args: Array[String]) {
    val n = io.StdIn.readLine.trim.toInt
    val a = io.StdIn.readLine.split(" ").map(_.trim.toInt)

    val set = a.toSet
    if (set.contains(0)) println(set.size - 1)
    else println(set.size)
  }
 }

object _992A extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val nums = io.read[Seq[Int]]
    val ans = nums.filter(_ != 0).distinct.size
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val a = StdIn.readLine().split(" ").map(item => item.toInt)
    println(a.distinct.count(item => item != 0))
  }
}

object Main extends App {
  readInt
  val array = readLine.split(" ").map(_.toInt)
  println(array.distinct.length - (if (array.contains(0)) 1 else 0))
}