There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai.For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are:  the first monster can't eat the second monster because a1 = 1 is not greater than a2 = 2;  the second monster can't eat the third monster because a2 = 2 is not greater than a3 = 2;  the second monster can't eat the fifth monster because they are not neighbors;  the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.

The first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial queue. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial weights of the monsters. The third line contains single integer k (1 ≤ k ≤ n) — the number of monsters in the queue after the joke.  The fourth line contains k integers b1, b2, ..., bk (1 ≤ bj ≤ 5·108) — the weights of the monsters after the joke.  Monsters are listed in the order from the beginning of the queue to the end.

In case if no actions could lead to the final queue, print "NO" (without quotes) in the only line.  Otherwise print "YES" (without quotes) in the first line. In the next n - k lines print actions in the chronological order. In each line print x — the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again.  When one monster eats another the queue decreases. If there are several answers, print any of them.

NoteIn the first example, initially there were n = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue:  the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2];  the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2];  the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3];  the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5]. Note that for each step the output contains numbers of the monsters in their current order in the queue.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val k = in.next().toInt
  val after = in.next().split(' ').map(_.toInt)

  def split(start: Int, current: Int, i: Int, sum: Int, answer: List[Array[Int]]): List[Array[Int]] = {
    if (current == n && i == k)
      answer.reverse
    else if (current == n || i == k)
      Nil
    else if (sum + line(current) == after(i))
      split(current + 1, current + 1, i + 1, 0, line.slice(start, current + 1) :: answer)
    else if (sum + line(current) > after(i))
      Nil
    else
      split(start, current + 1, i, sum + line(current), answer)
  }

  val sol = split(0, 0, 0, 0, Nil).map(_.toList)

  if (sol.exists(l => l.length > 1 && l.distinct.size == 1) || sol.isEmpty) {
    println("NO")
  } else {
    println("YES")
    val res = sol.zipWithIndex.filter(_._1.length > 1).flatMap {
      case (l, index) =>
        val maxValue = l.max
        val maxIndex =
          l.indices.find(i => l(i) == maxValue && ((i != 0 && l(i - 1) != maxValue)
            || (i != l.length - 1 && l(i + 1) != maxValue))).get
        if (maxIndex != 0 && l(maxIndex - 1) != maxValue) {
          (maxIndex to 1 by -1).map(i => s"${i + index + 1} L").toList ::: (maxIndex until l.length - 1).map(i => s"${index + 1} R").toList
        } else {
          (maxIndex until l.length - 1).map(i => s"${maxIndex + index + 1} R").toList ::: (maxIndex to 1 by -1).map(i => s"${i + index + 1} L").toList
        }
    }
    println(res.mkString("\n"))
  }

}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    val TEST =
      """2
        |1 2
        |2
        |3 1
      """.stripMargin.trim

    //System.setIn(new ByteArrayInputStream(TEST.getBytes))

    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(' ').toSeq.map(_.toLong)
    val k = input.next().toInt
    val b = input.next().split(' ').toSeq.map(_.toLong)
    val res = Try {
      assert(a.sum == b.sum)
      val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>
        if (l.isEmpty || l.head.sum == b(l.length - 1)) {
          assert (i <= b(l.length))
          Seq(i) +: l
        } else if (l.head.sum < b(l.length - 1)) {
          assert (l.head.sum + i <= b(l.length - 1))
          (i +: l.head) +: l.tail
        } else {
          throw new Exception()
        }
      }
      val g = f.map(_.reverse).reverse
      assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))
      g.zipWithIndex.filter(_._1.size > 1).flatMap(pair => {
        val k = pair._1
        val base = pair._2 + 1
        val max = k.max
        val notMaxIndex = k.indexWhere(_ != max)
        val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2
        if (nearestMaxIndex > notMaxIndex) {
          (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))
        } else {
          (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L'))
        }
      })
    }
    val sol = res match {
      case Success(a) => "YES" + a.map(b => "\n" + b._1 + " " + b._2).mkString
      case Failure(e) => "NO"
    }

    println(sol)
  }
}

import java.io._

import scala.io.Source

object ProblemC {
  def main(args: Array[String]): Unit = processStdInOut()

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below
  case class Move(index: Int, direction: Char) {
    override def toString() = s"$index $direction"
  }

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val n = lines.next().toInt
    val a = lines.next().split(' ').map(_.toInt)
    val k = lines.next().toInt
    val b = lines.next().split(' ').map(_.toInt)
    val solution = solve(n, k, a, b)
    solution match {
      case Some(moves) => {
        bw.write("YES")
        moves.foreach { move =>
          bw.newLine()
          bw.write(move.toString)
        }
      }
      case None => bw.write("NO")
    }
    bw.newLine()
  }

  /** The approach is to folder over the weights in the a matrix,
    * until the current group of a values matches the next b value, and track the largest monster in the group.
    * If there are multiple largest monsters, then the first will eat all monsters to its left then all to its right.
    * The exception is if the first of these largest monsters starts the group and has other largest monsters after it.
    * In this case, take the last largest monster in this initial group of largest monsters.
    * It will eat all monsters to its right, then all monsters to its left.
    * But beware... if all monsters in the group are identical, then there is no solution, as none can eat any other.
    *
    * The Accumulator class tracks the state after all previous weights (entries in a) have been evaluated.
    * In particular it tracks the current group (corresponding to the next b value to be matched).
    */
  case class Accumulator(indexInGroup: Int, sizeOfGroup: Int,
                         groupIndex: Int, groupSum: Int,
                         groupMaxValue: Int, indexOfMaxInGroup: Int, maxStartsGroup: Boolean,
                         moves: IndexedSeq[Move]
                         ) {
    def setNewGroupMaxValue(weight: Int) = copy(
      groupMaxValue = weight,
      indexOfMaxInGroup = indexInGroup,
      maxStartsGroup = (indexInGroup == 0)
    )
    def areAllWeightsIdenticalAndIsThereMoreThanOne: Boolean = {
      maxStartsGroup && (indexOfMaxInGroup == indexInGroup) && (sizeOfGroup > 1)
    }
    def canGroupBeCollapsed: Boolean = !areAllWeightsIdenticalAndIsThereMoreThanOne
    def monstersAfterMaxMonsterInGroup: Int = sizeOfGroup - indexOfMaxInGroup - 1
    def monstersBeforeMaxMonsterInGroup: Int = indexOfMaxInGroup
    def globalIndexOfMaxMonster: Int = groupIndex + indexOfMaxInGroup + 1
    def updateWithMovesToCollapseGroup(): Accumulator = {
      // Calculate the moves that collapse the group to a single value (assuming this is possible)...
      if (sizeOfGroup == 1) this  // With a single monster in the group, no eating will occur
      else {
        val newMoves = if (maxStartsGroup) {
          // Eat monsters to the right, then to the left:
          IndexedSeq.fill(monstersAfterMaxMonsterInGroup)(Move(globalIndexOfMaxMonster, 'R')) ++
          IndexedSeq.tabulate(monstersBeforeMaxMonsterInGroup)(i => Move(globalIndexOfMaxMonster - i, 'L' ))
        } else {
          // Eat monsters to the left, then the right:
          IndexedSeq.tabulate(monstersBeforeMaxMonsterInGroup) (i => Move(globalIndexOfMaxMonster - i, 'L' )) ++
          IndexedSeq.fill(monstersAfterMaxMonsterInGroup)(Move(groupIndex + 1, 'R'))
        }
        this.copy(moves = moves ++ newMoves)
      }
    }
    def startNextGroup(): Accumulator = {
      this.copy(indexInGroup = -1, sizeOfGroup = 0,
        groupIndex = groupIndex + 1, groupSum = 0, groupMaxValue = 0,
        indexOfMaxInGroup = -1, false)
    }
  }

  def solve(n: Int, k: Int, a: Array[Int], b: Array[Int]): Option[Seq[Move]] = {
    val initialAccumulator = Accumulator(-1, 0, 0, 0, 0, -1, false, IndexedSeq[Move]())
    val finalAcc = a.foldLeft[Option[Accumulator]](Some(initialAccumulator)) {
      (maybeAcc: Option[Accumulator], weight: Int) => {
        maybeAcc flatMap { acc =>
          if (b.length <= acc.groupIndex) None  // note enough weights in b to match all the weights in a
          else {
            val target = b(acc.groupIndex)

            // First update the fields that don't depend on other logic:
            var newAcc = acc.copy(
              groupSum = acc.groupSum + weight,
              indexInGroup = acc.indexInGroup + 1,
              sizeOfGroup = acc.sizeOfGroup + 1)

            // Track the maximum value in the group (that isn't surrounded by other biggest monsters),
            // as we can eat up the other monsters starting from it:
            if (newAcc.groupMaxValue < weight) newAcc = newAcc.setNewGroupMaxValue(weight)
            else if (newAcc.maxStartsGroup && (newAcc.groupMaxValue == weight)
              && (newAcc.indexOfMaxInGroup == newAcc.indexInGroup - 1)) {
              // If a block of max values (largest monsters) starts the group, then track the last one found,
              // as only the last one in the block can eat up the rest of the group (by eating right first, not left):
              newAcc = newAcc.copy(indexOfMaxInGroup = newAcc.indexInGroup)
            }

            if (newAcc.groupSum < target) Some(newAcc) // The group is incomplete, so keep iterating...
            else if (newAcc.groupSum > target) None // array a and b are incompatible, so no valid solution
            else if (!newAcc.canGroupBeCollapsed) None // target reached, but all monsters identical, so an impasse
            else {
              newAcc = newAcc.updateWithMovesToCollapseGroup()
              newAcc = newAcc.startNextGroup()
              Some(newAcc)
            }
          }
        }
      }
    }
    finalAcc match {
      case Some(acc) if acc.groupIndex == k => Some(acc.moves)  // Check that all b's were matched
      case _ => None
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val k = in.next().toInt
  val after = in.next().split(' ').map(_.toInt)

  def split(start: Int, current: Int, i: Int, sum: Int, answer: List[Array[Int]]): List[Array[Int]] = {
    if (current == n && i == k)
      answer.reverse
    else if (current == n || i == k)
      Nil
    else if (sum + line(current) == after(i))
      split(current + 1, current + 1, i + 1, 0, line.slice(start, current + 1) :: answer)
    else if (sum + line(current) > after(i))
      Nil
    else
      split(start, current + 1, i, sum + line(current), answer)
  }

  val sol = split(0, 0, 0, 0, Nil).map(_.toList)

  if (sol.exists(l => l.length > 1 && l.distinct.size == 1)) {
    println("NO")
  } else {
    println("YES")
    val res = sol.zipWithIndex.filter(_._1.length > 1).flatMap {
      case (l, index) =>
        val maxValue = l.max
        val maxIndex =
          l.indices.find(i => l(i) == maxValue && ((i != 0 && l(i - 1) != maxValue)
            || (i != l.length - 1 && l(i + 1) != maxValue))).get
        if (maxIndex != 0 && l(maxIndex - 1) != maxValue) {
          (maxIndex to 1 by -1).map(i => s"${i + index + 1} L").toList ::: (maxIndex until l.length - 1).map(i => s"${index + 1} R").toList
        } else {
          (maxIndex until l.length - 1).map(i => s"${maxIndex + index + 1} R").toList ::: (maxIndex to 1 by -1).map(i => s"${i + index + 1} L").toList
        }
    }
    println(res.mkString("\n"))
  }

}

import scala.util._

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(' ').toSeq.map(_.toLong)
    val k = input.next().toInt
    val b = input.next().split(' ').toSeq.map(_.toLong)
    val res = Try {
      val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>
        if (l.isEmpty || l.head.sum == b(l.length - 1)) {
          assert (i <= b(l.length))
          Seq(i) +: l
        } else if (l.head.sum < b(l.length)) {
          assert (l.head.sum + i <= b(l.length))
          (i +: l.head) +: l.tail
        } else {
          throw new Exception()
        }
      }
      assert (f.last.sum == b.last)
      val g = f.map(_.reverse).reverse
      assert(g.forall(l => !l.forall(_ == l.head)))
      g.zipWithIndex.flatMap(pair => {
        val k = pair._1
        val base = pair._2 + 1
        val max = k.max
        val notMaxIndex = k.indexWhere(_ != max)
        val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2
        if (nearestMaxIndex > notMaxIndex) {
          (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))
        } else {
          (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L'))
        }
      })
    }
    val sol = res match {
      case Success(a) => "YES" + a.map(b => "\n" + b._1 + " " + b._2).mkString
      case Failure(e) => "NO"
    }

    println(sol)
  }
}

import scala.util._

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(' ').toSeq.map(_.toLong)
    val k = input.next().toInt
    val b = input.next().split(' ').toSeq.map(_.toLong)
    val res = Try {
      val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>
        if (l.isEmpty || l.head.sum == b(l.length - 1)) {
          assert (i <= b(l.length))
          Seq(i) +: l
        } else if (l.head.sum < b(l.length)) {
          assert (l.head.sum + i <= b(l.length))
          (i +: l.head) +: l.tail
        } else {
          throw new Exception()
        }
      }
      assert (f.last.sum == b.last)
      val g = f.map(_.reverse).reverse
      assert(g.forall(l => !l.forall(_ == l.head)))
      g.zipWithIndex.flatMap(pair => {
        val k = pair._1
        val base = pair._2 + 1
        val max = k.max
        val notMaxIndex = k.indexWhere(_ != max)
        val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2
        if (nearestMaxIndex > notMaxIndex) {
          (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))
        } else {
          (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L'))
        }
      })
    }
    val sol = res match {
      case Success(a) => "YES" + a.map(b => "\n" + b._1 + " " + b._2).mkString
      case Failure(e) => e.getMessage //"NO"
    }

    println(sol)
  }
}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    val TEST =
      """
5
1 1 1 1 2
3
1 1 4
      """.stripMargin.trim

//    System.setIn(new ByteArrayInputStream(TEST.getBytes))

    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(' ').toSeq.map(_.toLong)
    val k = input.next().toInt
    val b = input.next().split(' ').toSeq.map(_.toLong)
    val res = Try {
      val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>
        if (l.isEmpty || l.head.sum == b(l.length - 1)) {
          assert (i <= b(l.length))
          Seq(i) +: l
        } else if (l.head.sum < b(l.length - 1)) {
          assert (l.head.sum + i <= b(l.length - 1))
          (i +: l.head) +: l.tail
        } else {
          throw new Exception()
        }
      }
      val g = f.map(_.reverse).reverse
      assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))
      g.zipWithIndex.flatMap(pair => {
        val k = pair._1
        val base = pair._2 + 1
        val max = k.max
        val notMaxIndex = k.indexWhere(_ != max)
        val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2
        if (nearestMaxIndex > notMaxIndex) {
          (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))
        } else {
          (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L'))
        }
      })
    }
    val sol = res match {
      case Success(a) => "YES" + a.map(b => "\n" + b._1 + " " + b._2).mkString
      case Failure(e) => "NO"
    }

    println(sol)
  }
}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    val TEST =
      """3
        |2 2 1
        |1
        |5
      """.stripMargin.trim

    //System.setIn(new ByteArrayInputStream(TEST.getBytes))

    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(' ').toSeq.map(_.toLong)
    val k = input.next().toInt
    val b = input.next().split(' ').toSeq.map(_.toLong)
    val res = Try {
      val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>
        if (l.isEmpty || l.head.sum == b(l.length - 1)) {
          assert (i <= b(l.length))
          Seq(i) +: l
        } else if (l.head.sum < b(l.length - 1)) {
          assert (l.head.sum + i <= b(l.length - 1))
          (i +: l.head) +: l.tail
        } else {
          throw new Exception()
        }
      }
      val g = f.map(_.reverse).reverse
      assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))
      g.zipWithIndex.filter(_._1.size > 1).flatMap(pair => {
        val k = pair._1
        val base = pair._2 + 1
        val max = k.max
        val notMaxIndex = k.indexWhere(_ != max)
        val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2
        if (nearestMaxIndex > notMaxIndex) {
          (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))
        } else {
          (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L'))
        }
      })
    }
    val sol = res match {
      case Success(a) => "YES" + a.map(b => "\n" + b._1 + " " + b._2).mkString
      case Failure(e) => "NO"
    }

    println(sol)
  }
}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    val TEST =
      """2
        |1 2
        |2
        |3 1
      """.stripMargin.trim

    //System.setIn(new ByteArrayInputStream(TEST.getBytes))

    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(' ').toSeq.map(_.toLong)
    val k = input.next().toInt
    val b = input.next().split(' ').toSeq.map(_.toLong)
    val res = Try {
      assert(a.sum == b.sum)
      val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>
        if (l.isEmpty || l.head.sum == b(l.length - 1)) {
          assert (i <= b(l.length))
          Seq(i) +: l
        } else if (l.head.sum < b(l.length - 1)) {
          assert (l.head.sum + i <= b(l.length - 1))
          (i +: l.head) +: l.tail
        } else {
          throw new Exception()
        }
      }
      val g = f.map(_.reverse).reverse
      println(g)
      assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))
      g.zipWithIndex.filter(_._1.size > 1).flatMap(pair => {
        val k = pair._1
        val base = pair._2 + 1
        val max = k.max
        val notMaxIndex = k.indexWhere(_ != max)
        val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2
        if (nearestMaxIndex > notMaxIndex) {
          (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))
        } else {
          (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L'))
        }
      })
    }
    val sol = res match {
      case Success(a) => "YES" + a.map(b => "\n" + b._1 + " " + b._2).mkString
      case Failure(e) => "NO"
    }

    println(sol)
  }
}

import java.io.FileInputStream

import scala.util._

object Main {

  def main(args: Array[String]) = {

    //    System.setIn(new FileInputStream("test.txt"))

    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(' ').toSeq.map(_.toLong)
    val k = input.next().toInt
    val b = input.next().split(' ').toSeq.map(_.toLong)
    val res = Try {
      val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>
        if (l.isEmpty || l.head.sum == b(l.length - 1)) {
          assert (i <= b(l.length))
          Seq(i) +: l
        } else if (l.head.sum < b(l.length - 1)) {
          assert (l.head.sum + i <= b(l.length - 1))
          (i +: l.head) +: l.tail
        } else {
          throw new Exception()
        }
      }
      val g = f.map(_.reverse).reverse
      assert (g.last.sum == b.last)
      assert(g.forall(l => !l.forall(_ == l.head)))
      g.zipWithIndex.flatMap(pair => {
        val k = pair._1
        val base = pair._2 + 1
        val max = k.max
        val notMaxIndex = k.indexWhere(_ != max)
        val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2
        if (nearestMaxIndex > notMaxIndex) {
          (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))
        } else {
          (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base, 'L'))
        }
      })
    }
    val sol = res match {
      case Success(a) => "YES" + a.map(b => "\n" + b._1 + " " + b._2).mkString
      case Failure(e) => "NO"
    }

    println(sol)
  }
}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    val TEST =
      """3
        |2 2 1
        |1
        |5
      """.stripMargin.trim

    System.setIn(new ByteArrayInputStream(TEST.getBytes))

    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(' ').toSeq.map(_.toLong)
    val k = input.next().toInt
    val b = input.next().split(' ').toSeq.map(_.toLong)
    val res = Try {
      val f = a.foldLeft(Seq.empty[Seq[Long]]) { (l, i) =>
        if (l.isEmpty || l.head.sum == b(l.length - 1)) {
          assert (i <= b(l.length))
          Seq(i) +: l
        } else if (l.head.sum < b(l.length - 1)) {
          assert (l.head.sum + i <= b(l.length - 1))
          (i +: l.head) +: l.tail
        } else {
          throw new Exception()
        }
      }
      val g = f.map(_.reverse).reverse
      assert(g.forall(l => l.size == 1 || !l.forall(_ == l.head)))
      g.zipWithIndex.filter(_._1.size > 1).flatMap(pair => {
        val k = pair._1
        val base = pair._2 + 1
        val max = k.max
        val notMaxIndex = k.indexWhere(_ != max)
        val nearestMaxIndex = k.zipWithIndex.filter(pair => pair._1 == max).minBy(a => (a._2 - notMaxIndex).abs)._2
        if (nearestMaxIndex > notMaxIndex) {
          (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L')) ++ (0 until (k.length - nearestMaxIndex - 1)).map(_ => (base, 'R'))
        } else {
          (0 until (k.length - nearestMaxIndex - 1)).map(_ => (nearestMaxIndex + base, 'R')) ++ (0 until nearestMaxIndex).reverse.map(a => (a + base + 1, 'L'))
        }
      })
    }
    val sol = res match {
      case Success(a) => "YES" + a.map(b => "\n" + b._1 + " " + b._2).mkString
      case Failure(e) => "NO"
    }

    println(sol)
  }
}


n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.What is the maximum amount of people that could stay at the party in the end?

The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).

For each test output in a separate line one number — the maximum amount of people that could stay in the end.

object Party23B  extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    val strinbBuilder = new StringBuilder()

    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      strinbBuilder.append(Math.max(n-2,0)).append(System.lineSeparator())
    }
    out.println(strinbBuilder.toString)

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int = return next().toInt
  }
}

object Party23B  extends App {
  import java.io._
  import java.util.StringTokenizer
  //solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      if((n+1)%4 == 0){
        out.println((n+1)/2-1)
      }else{
        out.println(((n/4)*4)/2)
      }

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int = return next().toInt
  }
}

object Party23B extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    val strinbBuilder = new StringBuilder()

    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      if((n+1)%4 == 0){
        strinbBuilder.append((n+1)/2-1).append(System.lineSeparator())

      }else{
        strinbBuilder.append(((n/4)*4)/2).append(System.lineSeparator())
      }

    }
    out.println(strinbBuilder.toString)

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int = return next().toInt
  }
}


Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has ai rows from A. Similarly, second cluster containing table B has n partitions, i-th one having bi rows from B. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.

First line contains two integer numbers, m and n (1 ≤ m, n ≤ 105). Second line contains description of the first cluster with m space separated integers, ai (1 ≤ ai ≤ 109). Similarly, third line describes second cluster with n space separated integers, bi (1 ≤ bi ≤ 109).

Print one integer — minimal number of copy operations.

NoteIn the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operationsIn the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2·3 = 6 copy operations.

import scala.collection._

object B 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, m) = readInts(2)
  val as = readLongs(n)
  val bs = readLongs(m)
  val sumA = as.sum
  val sumB = bs.sum
  val maxA = as.max
  val maxB = bs.max

  var res = 0L
  if (maxA > maxB || (maxA == maxB && sumA > sumB)) {
    val maxIdx = as.indexOf(maxA)
    for (i <- as.indices) res += (if (i == maxIdx) sumB else (as(i) min sumB))
  } else {
    val maxIdx = bs.indexOf(maxB)
    for (i <- bs.indices) res += (if (i == maxIdx) sumA else (bs(i) min sumA))
  }

  println(res)
}


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

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

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

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

object C {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextLongs(n)
      var res = n
      if (res == 1) {
        res = 0
      }

      for (l <- 0 until n) {
        val al = as(l)
        for (r <- l + 1 until n) {
          val ar = as(r)
          val d = r - l
          var cntBad = 0
          var i = 0
          while (i < n) {
            val expected = al + (i - l) * (ar - al) / d
            if (expected != as(i) || (i - l) * (ar - al) % d != 0) cntBad += 1
//            println(i, expected, l, r, d)
            i += 1
          }
          if (cntBad < res) {
            res = cntBad
          }
        }
      }

      out.println(res)
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val l: Int, val r: Int, val p: Boolean)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (r-l).compareTo(that.r-that.l)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n+1)
        val d = new Array[Int](n+1)
        for (i <- 1 to n) {
            arr(i) = readInt()
        }
        var ans = 0
        var a = 0
        var b = 0
        var c = false
        var tmp = 0
        var p = pair(0, 0, false)
        for (i <- 1 to n) {
            val mp = mutable.Map[pair, Int]()
            //println(i)
            for (j <- 1 to n) {
                if (i != j) {
                    c = false
                    a = arr(i) - arr(j)
                    b = i - j
                    if (a < 0) {
                        a *= -1
                        c = !c
                    }
                    if (b < 0) {
                        b *= -1
                        c = !c
                    }
                    tmp = gcd(a, b)
                    if (tmp != 0) {
                        a /= tmp
                        b /= tmp
                    }
                    p = pair(a, b, c)
                    //println(j, a, b, c)
                    if (!mp.contains(p)) {
                        mp(p) = 1
                        d(i) = max(d(i), 1)
                    } else {
                        tmp = mp(p)
                        mp(p) = tmp + 1
                        d(i) = max(d(i), tmp + 1)
                    }
                }
            }
            ans = max(ans, d(i) + 1)
        }
        writer.println(n - ans)

        def check(kk: Long): Boolean = {
            return true
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}


Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.

The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word. It is guaranteed that both words consist of 2·n characters "0" and "1".

Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.

import io.Source
import java.io.PrintWriter
import scala.util.Random

object CF293A {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val a, b = in()
    var c00, c01, c10, c11 = 0
    for (i <- 0 until a.length) {
      if (a(i) == '0') {
        if (b(i) == '0') {
          c00 += 1
        } else {
          c01 += 1
        }
      } else {
        if (b(i) == '0') {
          c10 += 1
        } else {
          c11 += 1
        }
      }
    }
    for (i <- 0 until n) {
      val d1 = if (c11 > 0) {
        c11 -= 1
        1
      } else if (c10 > 0) {
        c10 -= 1
        1
      } else if (c01 > 0) {
        c01 -= 1
        0
      } else if (c00 > 0) {
        c00 -= 1
        0
      } else {
        throw new AssertionError()
      }
      val d2 = if (c11 > 0) {
        c11 -= 1
        1
      } else if (c01 > 0) {
        c01 -= 1
        1
      } else if (c10 > 0) {
        c10 -= 1
        0
      } else if (c00 > 0) {
        c00 -= 1
        0
      } else {
        throw new AssertionError()
      }
      if (d1 != d2) {
        if (d1 > d2) {
          out.println("First")
        } else {
          out.println("Second")
        }
        return
      }
    }
    out.println("Draw")
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      def run() {
        val in: In = new In(Source.fromInputStream(System.in))
        val out: PrintWriter = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "thread", 64000000).run()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}


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

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

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

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

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

  override def solve(io: IO) = io.repeat {
    val ps = io.read[Seq[Int]].zipWithIndex.toMap
    val n = ps.size

    var l = n
    var r = -1

    val ans = (1 to n) map {i =>
      l = l min ps(i)
      r = r max ps(i)
      if (r - l + 1 == i) 1 else 0
    }

    io.write(ans.mkString)
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    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 {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[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")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  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 B_1265 extends App {
  val t = readInt()
  1 to t foreach { _ =>
    val n = readInt()
    val A = readLine().split(" ").map(_.toInt)
    val pos = A.zipWithIndex.toMap

    var posMax = pos(1)
    var posMin = pos(1)
    val result = Array.fill(n)(false)
    result(0) = true

    2 to n foreach { m =>
      posMax = Math.max(posMax, pos(m))
      posMin = Math.min(posMin, pos(m))
      result(posMax - posMin) = posMax - posMin + 1 == m
//      println(s"$m -> ($posMin, $posMax)")
    }

    println(result.map(x => if (x) "1" else "0").mkString)
    //100000000000000000000001

  }
}

import scala.io.StdIn._

object B_1265 extends App {
  val t = readInt()
  1 to t foreach { _ =>
    val n = readInt()
    val A = readLine().split(" ").map(_.toInt)
    val pos = A.zipWithIndex.toMap

    var posMax = pos(1)
    var posMin = pos(1)
    val result = Array.fill(n)(false)
    result(0) = true

    2 to n foreach { m =>
      posMax = Math.max(posMax, pos(m))
      posMin = Math.min(posMin, pos(m))
      result(posMax - posMin) = true
    }

    println(result.map(x => if (x) "1" else "0").mkString)

  }
}


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

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

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

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

object L{
    def main (args: Array[String])= {
        val sc = new java.util.Scanner(System.in)
        val n, k = sc.nextInt()
        val s = sc.next()
        var a = new Array[Int](n+5)
        var last = 0
        for (i<-0 to n-1) {
            if (s.charAt(i)=='0') last=i
            a(i)=last
        }
        var lo = -1
        var hi = n
        while (lo+1<hi) {
            var m=(lo+hi)/2
            var cur=0
            for (i<-2 to k) {
                cur=a(Math.min(n-1, cur+m+1))
            }
            if (cur==n-1) hi=m
            else lo=m
        }
        println(hi)
    }
}

import scala.io.StdIn
import scala.util.control.Breaks

/**
  * @author Daniyar Itegulov
  */
object L extends App {
  val sc = new java.util.Scanner(System.in)
  val n, k = sc.nextInt()
  val s = sc.next().map(_ == '0')
  val d = Array.ofDim[Int](n)
  var prev = 0
  d(0) = 0
  for (i <- 1 until n) {
    if (s(i)) {
      prev = i
    }
    d(i) = prev
  }
  var l = -1
  var r = n - 1
  while (r - l > 1) {
    val m = (l + r) / 2
    var pos = 0
    var good = false
    Breaks.breakable {
      for (i <- 0 until (k - 1)) {
        pos = d(Math.min(n - 1, pos + m + 1))
        if (pos == n - 1) {
          good = true
          Breaks.break()
        }
      }
    }
    if (good) {
      r = m
    } else {
      l = m
    }
  }
  println(r)
}

import scala.io.StdIn
import scala.util.control.Breaks

/**
  * @author Daniyar Itegulov
  */
object L extends App {
  val sc = new java.util.Scanner(System.in)
  val n, k = sc.nextInt()
  val s = sc.next().map(_ == '0')
  var l = 0
  var r = n - 2
  while (r - l > 1) {
    val m = (l + r) / 2
    var pos = 0
    var good = false
    Breaks.breakable {
      for (i <- 0 until (k - 1)) {
        pos = Math.min(n - 1, pos + m + 1)
        while (!s(pos)) {
          pos -= 1
        }
        if (pos == n - 1) {
          good = true
          Breaks.break()
        }
      }
    }
    if (good) {
      r = m
    } else {
      l = m
    }
  }
  println(r)
}

import scala.io.StdIn
import scala.util.control.Breaks

/**
  * @author Daniyar Itegulov
  */
object L extends App {
  val sc = new java.util.Scanner(System.in)
  val n, k = sc.nextInt()
  val s = sc.next().map(_ == '0')
  if (n == 2) {
    print(0)
    System.exit(0)
  }
  var l = 0
  var r = n - 1
  while (r - l > 1) {
    val m = (l + r) / 2
    var pos = 0
    var good = false
    Breaks.breakable {
      for (i <- 0 until (k - 1)) {
        pos = Math.min(n - 1, pos + m + 1)
        while (!s(pos)) {
          pos -= 1
        }
        if (pos == n - 1) {
          good = true
          Breaks.break()
        }
      }
    }
    if (good) {
      r = m
    } else {
      l = m
    }
  }
  println(r)
}

import scala.io.StdIn
import scala.util.control.Breaks

/**
  * @author Daniyar Itegulov
  */
object L extends App {
  val sc = new java.util.Scanner(System.in)
  val n, k = sc.nextInt()
  val s = sc.next().map(_ == '0')
  var l = 0
  var r = n - 1
  while (r - l > 1) {
    val m = (l + r) / 2
    var pos = 0
    var good = false
    Breaks.breakable {
      for (i <- 0 until (k - 1)) {
        val prevPos = pos
        pos = Math.min(n - 1, pos + m + 1)
        while (!s(pos)) {
          pos -= 1
        }
        if (pos == n - 1) {
          good = true
          Breaks.break()
        }
      }
    }
    if (good) {
      r = m
    } else {
      l = m
    }
  }
  println(r)
}


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

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

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

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

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 _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
      }
    }
  }
}

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