import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._

object _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._
  def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)

  val (n, s) = (nextInt, nextInt)
  val entries = repeat(n) {
    Entry(next == "B", nextInt, nextInt)
  } groupBy {_.key} mapValues(_.reduce(join))

  val (buys, sells) = entries.values.partition(_.buy)

  val bestBuys = buys.toList.sortBy(-_.price)
  val bestSells = sells.toList.sortBy(_.price)

  bestSells.take(s).sortBy(-_.price) ++ bestBuys.take(s)
}) {
  override def format(result: List[Entry]) = result mkString "\n"
}

case class Entry(buy: Boolean, price: Int, qty: Int) {
  val key = (buy, price)
  override def toString = s"${if (buy) 'B' else 'S'} $price $qty"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._

object _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._
  def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)

  val (n, s) = (nextInt, nextInt)
  val entries = repeat(n) {
    Entry(next == "B", nextInt, nextInt)
  } groupBy {_.key} mapValues(_.reduce(join))

  val (buys, sells) = entries.values.partition(_.buy)

  val bestBuys = buys.toList.sortBy(_.price)(desc)
  val bestSells = sells.toList.sortBy(_.price)

  bestSells.take(s).sortBy(_.price)(desc) ++ bestBuys.take(s)
}) {
  override def format(result: List[Entry]) = result mkString "\n"
}

case class Entry(buy: Boolean, price: Int, qty: Int) {
  val key = (buy, price)
  override def toString = s"${if (buy) 'B' else 'S'} $price $qty"
}
/****************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
  final def desc[A: Ordering] =  implicitly[Ordering[A]].reverse
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object OrderBook {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def main(args: Array[String]) {
     val ns = readInts()
     val n = ns(0)
     val s = ns(1)
     val orders = for {
       i <- 1 to n
       val line = readLine.split(' ')
     } yield ( (line(0),line(1).toInt),line(2).toInt)
     val orderBook = orders.groupBy(_._1).map{ case (k,v) => (k, v.map(_._2).sum)}
      val sellOrders = orderBook.filterKeys(_._1 == "S")
        .keys.toList.sortBy(_._2).take(s).reverse
     val buyOrders = orderBook.filterKeys(_._1 == "B")
        .keys.toList.sortBy(_._2).reverse.take(s)

     for (b <- sellOrders) {
       println(b._1 + " " + b._2 + " " + orderBook(b))
     }
      for (b <- buyOrders) {
       println(b._1 + " " + b._2 + " " + orderBook(b))
     }

   }

}

import scala.io.StdIn._

object B extends App {
  val Array(n, s) = readLine().split(" ").map(_.toInt)

  val sell = Array.ofDim[Int](100001)
  val buy = Array.ofDim[Int](100001)

  for (_ <- 1 to n) {
    val input = readLine().split(" ")
    if (input(0) == "S") {
      sell(input(1).toInt) += input(2).toInt
    } else {
      buy(input(1).toInt) += input(2).toInt
    }
  }

  val S = sell.zipWithIndex.filterNot(_._1 == 0).take(s).reverse
  println(S.map(x => "S " + x._2 + " " + x._1).mkString("\n"))

  val B = buy.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse
  println(B.map(x => "B " + x._2 + " " + x._1).mkString("\n"))
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val Array(n, s) = in.next().split(" ").map(_.toInt)
  val data = Range(0, n).map{ _ =>
    val d = in.next().split(" ")
    (d(0).head, d(1).toInt, d(2).toInt)
  }
  val buy = data.filter(_._1 == 'B')
  val sell = data.filter(_._1 == 'S')

  val baggr = buy.groupBy(_._2).map{case(price, listd) => ('B', price, listd.map(_._3).sum ) }.toList.sortBy{
    _._2
  }.reverse.take(s)
  val saggr = sell.groupBy(_._2).map{case(price, listd) => ('S', price, listd.map(_._3).sum ) }.toList.sortBy{
    _._2
  }.take(s).reverse

  saggr.foreach(t => println(s"${t._1} ${t._2} ${t._3}"))
  baggr.foreach(t => println(s"${t._1} ${t._2} ${t._3}"))
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val Array(n, s) = in.next().split(" ").map(_.toInt)
  val data = Range(0, n).map{ _ =>
    val d = in.next().split(" ")
    (d(0).head, d(1).toInt, d(2).toInt)
  }
  val buy = data.filter(_._1 == 'B')
  val sell = data.filter(_._1 == 'S')

  val baggr = buy.groupBy(_._2).map{case(price, listd) => ('B', price, listd.map(_._3).sum ) }.toList.sortBy{
    _._2
  }.reverse.take(s)
  val saggr = sell.groupBy(_._2).map{case(price, listd) => ('S', price, listd.map(_._3).sum ) }.toList.sortBy{
    _._2
  }.take(s)

  saggr.foreach(t => println(s"${t._1} ${t._2} ${t._3}"))
  baggr.foreach(t => println(s"${t._1} ${t._2} ${t._3}"))
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._

object _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._
  def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)

  val (n, s) = (nextInt, nextInt)
  val entries = repeat(n) {
    Entry(next == "B", nextInt, nextInt)
  } groupBy {_.key} mapValues(_.reduce(join))

  val (buys, sells) = entries.values.partition(_.buy)

  val bestBuys = buys.toList.sortBy(-_.price)
  val bestSells = sells.toList.sortBy(_.price)

  bestSells.sortBy(-_.price).take(s) ++ bestBuys.take(s)
}) {
  override def format(result: List[Entry]) = result mkString "\n"
}

case class Entry(buy: Boolean, price: Int, qty: Int) {
  val key = (buy, price)
  override def toString = s"${if (buy) 'B' else 'S'} $price $qty"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._

object _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._
  def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)

  val (n, s) = (nextInt, nextInt)
  val entries = repeat(n) {
    Entry(next == "B", nextInt, nextInt)
  } groupBy {_.key} mapValues(_.reduce(join))

  val (buys, sells) = entries.values.partition(_.buy)

  sells.toList.sortBy(-_.price).take(s) ++ buys.toList.sortBy(-_.price).take(s)
}) {
  override def format(result: List[Entry]) = result mkString "\n"
}

case class Entry(buy: Boolean, price: Int, qty: Int) {
  val key = (buy, price)
  override def toString = s"${if (buy) 'B' else 'S'} $price $qty"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object B extends App {
  val Array(n, s) = readLine().split(" ").map(_.toInt)

  val sell = Array.ofDim[Int](100001)
  val buy = Array.ofDim[Int](100001)

  for (_ <- 1 to n) {
    val input = readLine().split(" ")
    if (input(0) == "S") {
      sell(input(1).toInt) += input(2).toInt
    } else {
      buy(input(1).toInt) += input(2).toInt
    }
  }

  val S = sell.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse
  println(S.map(x => "S " + x._2 + " " + x._1).mkString("\n"))

  val B = buy.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse
  println(B.map(x => "B " + x._2 + " " + x._1).mkString("\n"))
}


//package codeforces.contest1197

object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    implicit val ordering: Ordering[(R, Space, Result)] =
      (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        var minSpace = lastR._2._1 + r - lastR._1
        var minSpaceResult: Result = lastR._2._2

        for ((l, pairOccurrences) <- lSeq) {
          val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

          val space = prevSpace + l - prevR
          val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

          if (minSpace == space)
            minSpaceResult = (minSpaceResult + spaceResult) % MOD
          else if (space < minSpace) {
            minSpace = space
            minSpaceResult = spaceResult
          }
        }

        (r, (minSpace, minSpaceResult))
      }
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL < l)
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val (_, res) = {
      var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)

      for {
        r <- rValuesToConsider
        (space, spaceResult) = doneRValues(r)
      } {
        if (minSpace == space)
          minSpaceResult = (minSpaceResult + spaceResult) % MOD
        else if (space < minSpace) {
          minSpace = space
          minSpaceResult = spaceResult
        }
      }

      (minSpace, minSpaceResult)
    }

    println(res)
  }
}

import scala.language.implicitConversions
//package codeforces.contest1197

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues = new java.util.TreeMap[R, (Space, Result)]
    doneRValues.put(1, (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.floorEntry(r)

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.lastEntry()
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues.get(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }

  implicit  def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =
    (arg.getKey, arg.getValue)
}

//package codeforces.contest1197

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL < l)
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }
}

//package codeforces.contest1197

import scala.language.implicitConversions

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, mutable.TreeMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.lastKey

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.TreeMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.lastKey
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues = new java.util.TreeMap[R, (Space, Result)]
    doneRValues.put(1, (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.floorEntry(r)

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.lastEntry()
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues.get(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }

  implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =
    (arg.getKey, arg.getValue)
}

//package codeforces.contest1197

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues = new java.util.TreeMap[R, (Space, Result)]
    doneRValues.put(1, (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      deconstruct(doneRValues.floorEntry(r))

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = deconstruct(doneRValues.lastEntry())
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues.get(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }

  def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =
    (arg.getKey, arg.getValue)
}

//package codeforces.contest1197

import scala.language.implicitConversions

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {

  import collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, mutable.TreeMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.lastKey

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.TreeMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.lastKey
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }
}

//package codeforces.contest1197
import java.util

import scala.collection.convert.ImplicitConversionsToScala.`map AsScala`
import scala.language.implicitConversions

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: util.TreeMap[R, util.TreeMap[L, R]] =
      new java.util.TreeMap[R, util.TreeMap[L, Int]]() // sorted By r

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap: util.TreeMap[L, R] = {
        Option(pairsMap.get(upper)).getOrElse {
          val res = new util.TreeMap[L, Int]()
          pairsMap.put(upper, res)
          res
        }
      }
      lowerMap.put(lower, lowerMap.getOrDefault(lower, 0) + 1)
    }

    val lastL: L = pairsMap.lastEntry()._2.lastKey()

    @scala.annotation.tailrec
    def loop(ls: List[(R, util.TreeMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.lastKey()
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.tailMap(lastL, false).toList.reverse, List())

    val doneRValues = new java.util.TreeMap[R, (Space, Result)]
    doneRValues.put(1, (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.floorEntry(r)

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.lastEntry()
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues.get(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }

  implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =
    (arg.getKey, arg.getValue)
}

//package codeforces.contest1197

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, mutable.TreeMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.lastKey

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.TreeMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.lastKey
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }
}

//package codeforces.contest1197

object CultureCode {
  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val pairs: IndexedSeq[(R, Seq[(L, Int)])] = (1 to n)
      .map { _ =>
        val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
        (lower, upper)
      }
      .groupBy(_._2)
      .map {
        case (upper, pairValues) =>
          upper -> pairValues
            .map(_._1)
            .groupBy(identity)
            .mapValues(_.length)
            .toSeq
      }
      .toIndexedSeq
      .sortBy(_._1)

    implicit val ordering: Ordering[(R, Space, Result)] =
      (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1

    val doneRValues = collection.mutable.TreeSet[(R, Space, Result)]((1, 1, 1))

    def findLowerBound(r: Int): (R, Space, Result) =
      doneRValues.to((r, -1, -1L)).last

    for ((r, lSeq) <- pairs) {
      val lastR = doneRValues.last
      doneRValues.add(
        lSeq.foldLeft(lastR.copy(_1 = r, _2 = lastR._2 + r - lastR._1)) {
          case ((_, minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (_, space, spaceResult) = findLowerBound(l)

            if (minSpace == space)
              (r, minSpace, (minSpaceResult + spaceResult * pairOccurrences) % MOD)
            else if (minSpace < space)
              (r, minSpace, minSpaceResult)
            else
              (r, space, (spaceResult * pairOccurrences) % MOD)
        }
      )
    }

    val lastL: L = pairs(pairs.length - 1)._2.maxBy(_._1)._1

    val lastRValues = doneRValues.from((lastL + 1, -1, -1L))

    val minSpace = lastRValues.minBy(_._2)._2

    import collection.breakOut
    val res = lastRValues.collect {
      case (_, space, result) if space == minSpace => result
    }(breakOut).sum

    println(res)
  }
}

//package codeforces.contest1197

object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    implicit val ordering: Ordering[(R, Space, Result)] =
      (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        var minSpace = lastR._2._1 + r - lastR._1
        var minSpaceResult: Result = lastR._2._2

        for ((l, pairOccurrences) <- lSeq) {
          val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

          val space = prevSpace + l - prevR
          val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

          if (minSpace == space)
            minSpaceResult = (minSpaceResult + spaceResult) % MOD
          else if (space < minSpace) {
            minSpace = space
            minSpaceResult = spaceResult
          }
        }

        (r, (minSpace, minSpaceResult))
      }
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL <= l)
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List(pairsMap.last._1))

    val (_, res) = {
      var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)

      for {
        r <- rValuesToConsider
        (space, spaceResult) = doneRValues(r)
      } {
        if (minSpace == space)
          minSpaceResult = (minSpaceResult + spaceResult) % MOD
        else if (space < minSpace) {
          minSpace = space
          minSpaceResult = spaceResult
        }
      }

      (minSpace, minSpaceResult)
    }

    println(res)
  }
}

//package codeforces.contest1197

object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val pairsMap: mutable.Map[R, mutable.HashMap[L, R]] = // sorted By r
      collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    implicit val ordering: Ordering[(R, Space, Result)] =
      (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1

    val doneRValues = collection.mutable.TreeSet[(R, Space, Result)]((1, 1, 1))

    def findLowerBound(r: Int): (R, Space, Result) =
      doneRValues.until((r + 1, -1, -1L)).last

    for ((r, lSeq) <- pairsMap) {
      val lastR = doneRValues.last
      doneRValues.add {

        var minSpace = lastR._2 + r - lastR._1
        var minSpaceResult = lastR._3

        for ((l, pairOccurrences) <- lSeq) {
          val (prevR, prevSpace, prevSpaceResult) = findLowerBound(l)

          val space = prevSpace + l - prevR
          val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

          if (minSpace == space)
            minSpaceResult = (minSpaceResult + spaceResult) % MOD
          else if (space < minSpace) {
            minSpace = space
            minSpaceResult = spaceResult
          }
        }

        (r, minSpace, minSpaceResult)
      }
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    val lastRValues = doneRValues.from((lastL + 1, -1, -1L))

    val (_, res) = {
      var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)

      for ((_, space, spaceResult) <- lastRValues) {
        if (minSpace == space)
          minSpaceResult = (minSpaceResult + spaceResult) % MOD
        else if (space < minSpace) {
          minSpace = space
          minSpaceResult = spaceResult
        }
      }

      (minSpace, minSpaceResult)
    }

    println(res)
  }
}


import scala.collection.mutable.ArrayBuffer
import scala.io.Source

object Main extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val res = new ArrayBuffer[String]()
  for (i <- 0 until t) {
    val n = input.next().toInt
    val p = input.next().split(" ").map(_.toInt).toList

    val plr = p.zipWithIndex.map(x => (x._1, x._2 + 1)).filter(x => x._1 != x._2)
    if (plr.isEmpty) res.append(p.mkString(" "))
    else {
      val minInd = plr.min._2 - 1
      val startingInd = plr.head._2 - 1

      val start = p.slice(0, startingInd)
      val md = p.slice(startingInd, minInd + 1).reverse
      val end = if (minInd + 1 == n) Nil else p.slice(minInd + 1, n)
      res.append((start ++ md ++ end).mkString(" "))
    }
  }
  res.foreach(println)
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val optionIndex = a.zipWithIndex.find {
      case (a, index) => a != index + 1
    }
    val answer = optionIndex match {
      case None => a
      case Some((_, index)) =>
        val l = index
        val r = a.indexOf(index + 1)
        a.slice(0, l) ++ a.slice(l, r + 1).reverse ++ a.slice(r + 1, a.length)
    }
    println(answer.mkString(" "))
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def isEmpty() = multiSet.isEmpty
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}


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

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

  val N = sc.nextInt
  val ds = Array.fill(N, 2)(sc.nextInt)

  val answer: Int = {
    for (i <- 0 until 2) yield {
      val closed = (0 until N).map(ds(_)(i)).sum
      closed min (N - closed)
    }
  }.sum

  out.println(answer)
  out.close
}

import java.util._
import java.io._
import java.math._
import java.awt.Point
import java.awt.geom._
import java.lang.System._
import java.lang.Math._

object A {
  var n = -1
  var r: Array[Int] = null
  var l: Array[Int] = null

  def solve(){
    var cl = 0
    var cr = 0
    for(i <- 0 until n) if(l(i) == 1) cl = cl + 1;
    for(i <- 0 until n) if(r(i) == 1) cr = cr + 1;
    println(min(n-cl, cl)+min(n-cr, cr))
  }
  def main(args: Array[String]){
    val sc = new Scanner(in)
    n = sc.nextInt
    l = new Array(n)
    r = new Array(n)
    for(i <- 0 until n){
      l(i) = sc.nextInt
      r(i) = sc.nextInt
    }
    solve
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt

  val data = (1 to n).map{ _ => in.next()}
  val left = data.count(_.head == '1')
  val right = data.count(_.last == '1')

  println(Math.min(left, n - left) + Math.min(right, n - right))
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

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

  val f = Array[Int => Int](x => x, 1-, _ => 0, _ => 1)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum
  }.min

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

import java.io._
import java.util.Locale
import scala.annotation.tailrec

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

  val f = Array[Int => Int](x => x, 1-, 0*, 1|)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_^_))).sum
  }.min

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

import java.io._
import java.util.Locale
import scala.annotation.tailrec

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

  val f = Array[Int => Int](x => x, 1-, 0*, 1|)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum
  }.min

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

import java.io._
import java.util.Locale
import scala.annotation.tailrec

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

  val f = Array((x: Int) => x, (x: Int) => 1 - x, (x: Int) => 0, (x: Int) => 1)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum
  }.min

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

import java.util.Scanner
import java.math._

object B extends App
{
	val cin=new Scanner(System.in);
	val n=cin.nextInt()
	var l,r=0
	for(i <- 1 to n)
	{
		val a,b=cin.nextInt()
		l+=a
		r+=b
	}
	println(math.min(l,n-l)+math.min(r,n-r))
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    var left=0
    var right=0
    0 until n foreach{i=>
    	val Array(l,r)=readLine.split(" ").map(_.toInt)
    	if(l==0) left+=1
    	if(r==0) right+=1
    }

    if(left>n/2) left=n-left
    if(right>n/2) right=n-right

    println(left+right)
}

object Main {
  def readDoor() = {
    val a = readLine().split(" ").map(_.toInt)
    (a(0), a(1))
  }

  def main(args: Array[String]) {
    val n = readInt
    val a = (1 to n).map(_ => readDoor())
    val left = a.map(_._1).sum
    val right = a.map(_._2).sum
    println(left.min(n - left) + right.min(n - right))
  }
}

import java.util._
import java.io._
import java.math._
import java.awt.Point
import java.awt.geom._
import java.lang.System._
import java.lang.Math._

object A {
  def main(args: Array[String]){
    val sc = new Scanner(in)
    n = sc.nextInt
    solve
  }

  var n = -1
  def solve(){
    println(-1)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt

  val data = (1 to n).foldLeft((0, 0)){
    case ((left, right), _) =>
      val str = in.next()
      var newLeft = left
      var newRight = right
      if (str.head == '0')
        newLeft += 1
      else
        newRight += 1
      if (str.last == '0')
        newRight += 1
      else
        newLeft += 1
      (newLeft, newRight)
  }
  println(Math.min(data._1, data._2))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt

  val data = (1 to n).map{ _ => in.next()}
  val left = data.count(_.head == '1')
  val right = data.count(_.head == '1')

  println(Math.min(left, data.size - left) + Math.min(right, data.size - right))
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

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

  val f = Array((x: Int) => x, (x: Int) => 1 - x)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum
  }.min

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


import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _631B extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val n, m, k = in[Int]
    val rowColor, colColor = map[Int] to (0 -> 0)
    (1 to k) foreach {i =>
      val table = if (in[Int] == 1) rowColor else colColor
      table(in[Int]) = i -> in[Int]
    }
    for (r <- 1 to n) {
      for(c <- 1 to m) {
        out += (rowColor(r) max colColor(c))._2
      }
      out.newLine()
    }
  }

  def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Unit
  def main(args: Array[String]): Unit = solve(new InputReader(System.in), new OutputWriter(System.out))
}
/***********************************[Scala I/O]*********************************************/
import java.io._
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

class OutputWriter(out: PrintWriter) {
  def this(out: OutputStream) = this(new PrintWriter(out, true))

  var separator = " "
  private[this] var currentSeparator: Option[String] = None

  def +=(obj: Any): this.type = { //todo: Any*?
    currentSeparator match {
      case Some(x) => out.print(x)
      case _ => currentSeparator = Option(separator)
    }
    out.print(obj)
    this
  }

  def newLine(): this.type = {
    currentSeparator = None
    out.println()
    this
  }

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }
}

import java.io._
import java.util.Scanner

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO {(reader, writer) =>
      val n = reader.nextInt()
      val m = reader.nextInt()
      val k = reader.nextInt()
      val rows = mutable.Map.empty[Int, (Int, Int)]
      val columns = mutable.Map.empty[Int, (Int, Int)]
      (1 to k).foreach { priority =>
        val mode = reader.nextInt()
        val position = reader.nextInt() - 1
        val color = reader.nextInt()
        mode match {
          case 1 => rows.put(position, (priority, color))
          case 2 => columns.put(position, (priority, color))
        }
      }
      for (i <- 0 until n) {
        for (j <- 0 until m) {
          (rows.get(i), columns.get(j)) match {
            case (None, None) => writer.print(0)
            case (None, Some(columnInfo)) => writer.print(columnInfo._2)
            case (Some(rowInfo), None) => writer.print(rowInfo._2)
            case (Some(rowInfo), Some(columnInfo)) =>
              if (rowInfo._1 > columnInfo._1) writer.print(rowInfo._2) else writer.print(columnInfo._2)
          }
          writer.print(" ")
        }
        writer.print(System.lineSeparator())
      }
    }
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val (rowMap, colMap) = (1 to k).foldLeft((Map.empty[Int, (Int, Int)], Map.empty[Int, (Int, Int)])) {
    case ((row, col), i) =>
      in.next().split(' ').map(_.toInt) match {
        case Array(1, r, a) => (row + (r -> (a, i)), col)
        case Array(2, c, a) => (row, col + (c -> (a, i)))
      }
  }
  val res = Array.ofDim[Int](n, m)
  (0 until n).foreach { i =>
    (0 until m).foreach { j =>
      val col = colMap.get(j + 1)
      val row = rowMap.get(i + 1)
      res(i)(j) = if (row.isEmpty && col.isEmpty)
        0
      else if (col.isEmpty || (row.nonEmpty && col.get._2 < row.get._2))
        row.get._1
      else
        col.get._1
    }
  }
  println(res.map(_.mkString(" ")).mkString("\n"))
}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object B631 extends App {

  def solve() = {
    val Array(n,m,k): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val lastRow = Array.ofDim[(Int, Int)](n)
    (0 until n).foreach(i => lastRow(i) = (0, -1))
    val lastCol = Array.ofDim[(Int, Int)](m)
    (0 until m).foreach(j => lastCol(j) = (0, -1))
    for (i <- 0 until k) {
      val Array(t, el, color): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      if (t == 1) {
        // row
        lastRow(el-1) = (color, i)
      } else {
        // col
        lastCol(el-1) = (color, i)
      }
    }
    val builder: StringBuilder = new StringBuilder()
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (lastRow(i)._2 > lastCol(j)._2) {
          builder.append(lastRow(i)._1)
        } else {
          builder.append(lastCol(j)._1)
        }
        builder.append(' ')
      }
      builder.append('\n')
    }
    println(builder)
  }

  solve()

}

import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _631B extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val n, m, k = in[Int]
    val rowColor, colColor = map[Int] to (0 -> 0)
    (1 to k) foreach {i =>
      val table = if (in[Int] == 1) rowColor else colColor
      table(in[Int]) = i -> in[Int]
    }
    for (r <- 1 to n) {
      for(c <- 1 to m) {
        out append (rowColor(r) max colColor(c))._2
      }
      out.newLine()
    }
  }

  def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Unit
  def main(args: Array[String]): Unit = solve(new InputReader(System.in), new OutputWriter(System.out))
}
/***********************************[Scala I/O]*********************************************/
import java.io._
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

class OutputWriter(out: PrintWriter) {
  def this(out: OutputStream) = this(new PrintWriter(out, true))

  var separator = " "
  private[this] var isNewLine: Boolean = true

  def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else out.print(separator)
    out.print(obj)
    this
  }

  def newLine(): this.type = {
    isNewLine = true
    out.println()
    this
  }

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }

  def append(obj: Any*): this.type = this ++= obj
}

import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _631B extends CodeForcesApp {
  override type Result = Stream[Stream[Int]]

  override def solve(read: InputReader) = {
    val n, m, k = read[Int]
    val rowColor, colColor = map[Int] to (0 -> 0)
    (1 to k) foreach {i =>
      val q, s, c = read[Int]
      val table = q match {
        case 1 => rowColor
        case 2 => colColor
      }
      table(s) = i -> c
    }
    Stream.tabulate(n+1, m+1) {case (r, c) => (rowColor(r) max colColor(c))._2}
  }

  def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }

  override def format(result: Result) = {
    val sb = new StringBuilder()
    result.tail foreach {row => sb.append(row.tail.mkString("", " ", "\n"))}
    sb.toString
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}


object HCC2018B1 extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    out.println(new Array[Int]((in.nextInt-1) * 2).map(_ => in.nextInt).groupBy(x => x).filter(_._2.length == 1).size)
  }

  solve
  out.flush
  out.close
}

object MaximumControlB1   extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val a = Array.fill(n)(0)
    (1 until n).foreach{ _ =>
      val u = scanner.nextInt()
      val v = scanner.nextInt()
      a(u-1) += 1
      a(v-1) += 1
    }
    out.println(a.count(_ == 1))
  }
}


import scala.io.Source
import scala.math.log

object ACirnosPerfectBitmasksClassroom {
  def main(args: Array[String]): Unit = {
    val file = Source.stdin.getLines
    //    val file = Source.fromString(
    //      "7\n1\n2\n5\n9\n16\n114514\n1000000"
    //    ).getLines
    var t = file.next.toInt
    while (t > 0) {
      t -= 1
      val a = file.next.toInt
      val ub = (log(a) / log(2)).toInt
      val unitInd = (0 to ub).find(i => (a & (1 << i)) == 1 << i).get
      val res = if (a == 1) 3 else if (1 << unitInd != a) 1 << unitInd else (1 << unitInd) ^ 1
      println(res)
    }
  }
}

import scala.io.Source
import scala.math.log

object ACirnosPerfectBitmasksClassroom {
  def main(args: Array[String]): Unit = {
    val file = Source.stdin.getLines
//    val file = Source.fromString(
//      "7\n1\n2\n5\n9\n16\n114514\n1000000"
//    ).getLines
    var t = file.next.toInt
    while (t > 0) {
      t=t-1
      val a = file.next.toInt
      val ub = (log(a)/log(2)).toInt
      val unitInd = (0 to ub).find(i=> (a&(1<<i))==1<<i).get
      val res = if (a == 1) 3 else if (unitInd == 0) 1 else if (1<<unitInd != a) 1<<unitInd else (1<<unitInd)^1
      println(res)
    }
  }
}

import scala.io.StdIn
import scala.math.BigDecimal.double2bigDecimal

object Main {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()

    for(_ <- 0 until t) {
      val x = StdIn.readLong()

      var xDiv = x
      var countDiv = 0

      while(xDiv % 2 == 0) {
        xDiv = xDiv / 2
        countDiv += 1
      }

      if(xDiv == 1) {
        if(x == 1) {
          println(3)
        } else {
          println(Math.pow(2,countDiv).toLong + 1)
        }
      } else {
        println(Math.pow(2, countDiv).toLong)
      }
    }
  }
}


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)

  case class Pos(id: Int, i: Int, tpe: Int)

  def solve(): Unit = {
    REP(ni()) { _ =>
      import java.util
      import java.util.Comparator
      val N = ni()
      val S = Array.ofDim[Pos](2 * N)
      REP(N) { i =>
        val l, r = ni() - 1
        S(i * 2) = Pos(i, l, 0)
        S(i * 2 + 1) = Pos(i, r, 1)
      }

      util.Arrays.sort(S, 0, S.length, new Comparator[Pos] {
        override def compare(o1: Pos, o2: Pos): Int = {
          if (o1.i != o2.i) Integer.compare(o1.i, o2.i)
          else Integer.compare(o1.tpe, o2.tpe) // open優先
        }
      })

      val ans = Array.ofDim[Int](N)
      var bal = 0
      var group = 1
      REP(2 * N) { i =>
        if (S(i).tpe == 0) bal += 1
        else bal -= 1
        ans(S(i).id) = group
        if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する
      }

      if (ans.forall(_ == 1)) out.println(-1)
      else out.println(ans.mkString(" "))
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  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
import java.util.regex.Pattern

import scala.io.StdIn
import scala.util.Sorting

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  val magicMod = 1000000007

  class UnionFind(var size : Int){
    var parents = Array.ofDim[Int](size)
    var sizes = Array.ofDim[Int](size)

    for (i <- 0 until size) {
      parents(i) = i
      sizes(i) = 1
    }

    def findParent(node : Int): Int = {
      var p = node
      while (parents(p) != p) {
        parents(p) = parents(parents(p))
        p = parents(p)
      }
      parents(node) = p
      p
    }

    def merge(a : Int, b : Int): Unit = {
      var pA = findParent(a)
      var pB = findParent(b)

      if (pA == pB) {
        return
      }

      if (sizes(pA) < sizes(pB)) {
        parents(pB) = pA
        sizes(pA) += sizes(pB)
      } else {
        parents(pA) = pB
        sizes(pB) += sizes(pA)
      }
    }
  }

  def doCase(caseNo: Int): Unit = {
    val N = readInt()
    val segs = Array.fill(N)((0, 0, 0))

    var n = 0
    while (n < N) {
      val Array(l, r) = readIntLine()
      segs(n) = (l, r, n)
      n += 1
    }

    Sorting.quickSort(segs)

    val assignments = Array.fill(N)(0)
    val uf = new UnionFind(N)

    var i = 0
    while (i < N) {
      var j = i + 1
      while (j < N && segs(uf.findParent(i))._2 >= segs(j)._1) {
        val pi = uf.findParent(i)
        uf.merge(pi, j)
        val newParent = uf.findParent(i)
        segs(newParent) = (segs(pi)._1, Math.max(segs(pi)._2, segs(j)._2), segs(newParent)._3)

        j += 1
      }

      i = j
    }

    val roots = uf.parents.zipWithIndex.filter(a => a._1 == a._2).map(_._1)

    if (roots.length < 2) {
      println(-1)
      return
    }

    val firstSet = Set(roots.head)
    val secondSet = roots.tail.toSet

    for (((_, _, origIdx), sortedIdx) <- segs.zipWithIndex) {
      val cluster = uf.findParent(sortedIdx)
      if (firstSet.contains(cluster)) {
        assignments(origIdx) = 1
      } else if (secondSet.contains(cluster)) {
        assignments(origIdx) = 2
      } else {
        throw new RuntimeException()
      }
    }

    println(assignments.mkString(" "))
  }

  def main(args: Array[String]): Unit = {
    val noCases = readInt()
    for (i <- 0 until noCases) {
      doCase(i)
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    StdIn.readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    StdIn.readLine().split(" ").map(BigInt.apply)
  }
}

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)

  case class Pos(id: Int, i: Int, tpe: Int)

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val S = Array.ofDim[Pos](2 * N)
      REP(N) { i =>
        val l, r = ni() - 1
        S(i * 2) = Pos(i, l, 0)
        S(i * 2 + 1) = Pos(i, r, 1)
      }

      implicit val orderingPos: Ordering[Pos] = Ordering.by(a => (a.i, a.tpe)) // open優先
      Sorting.stableSort(S)

      val ans = Array.ofDim[Int](N)
      var bal = 0
      var group = 1
      REP(2 * N) { i =>
        if (S(i).tpe == 0) bal += 1
        else bal -= 1
        ans(S(i).id) = group
        if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する
      }

      if (ans.forall(_ == 1)) out.println(-1)
      else out.println(ans.mkString(" "))
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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)

  case class Pos(id: Int, i: Int, tpe: Int)

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val S = Array.ofDim[Pos](2 * N)
      REP(N) { i =>
        val l, r = ni() - 1
        S(i * 2) = Pos(i, l, 0)
        S(i * 2 + 1) = Pos(i, r, 1)
      }

      Sorting.quickSort(S)(Ordering.by(a => (a.i, a.tpe))) // open優先

      val ans = Array.ofDim[Int](N)
      var bal = 0
      var group = 1
      REP(N) { i =>
        if (S(i).tpe == 0) bal += 1
        else bal -= 1
        if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する
        ans(i) = group
      }

      if (group == 1) out.println(-1)
      else out.println(ans.mkString(" "))
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  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
import java.util.regex.Pattern

import scala.io.StdIn
import scala.util.Sorting

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  val magicMod = 1000000007

  def doCase(caseNo: Int): Unit = {
    val N = readInt()
    val segs = Array.fill(N)((0, 0, 0))

    var n = 0
    while (n < N) {
      val Array(l, r) = readIntLine()
      segs(n) = (l, r, n)
      n += 1
    }

    Sorting.quickSort(segs)

    val assignments = Array.fill(N)(0)

    var f, s = 0
    n = 0
    while (n < N) {
      val (l, r, sn) = segs(n)
      if (n == N - 1 && s == 0 || l <= f && l > s) {
        s = r
        assignments(n) = 2
      } else if (l > f) {
        f = r
        assignments(n) = 1
      } else {
        println(-1)
        return
      }
      n += 1
    }

    println(assignments.mkString(" "))
  }

  def main(args: Array[String]): Unit = {
    val noCases = readInt()
    for (i <- 0 until noCases) {
      doCase(i)
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    StdIn.readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    StdIn.readLine().split(" ").map(BigInt.apply)
  }
}


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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val l, r = io.read[Array, Int](n)
    val ans = Array.ofDim[Int](n)
    val toProcess = mutable.Set(ans.indices : _*)

    @tailrec
    def solve(iter: Int): Boolean = {
      val canFill = toProcess.filter(i => l(i) == 0 && r(i) == 0)
      canFill foreach {i =>
        ans(i) = iter
        toProcess -= i
        (0 until n) foreach {j => if(j < i) r(j) -= 1 else if (j > i) l(j) -= 1}
      }
      if (canFill.isEmpty) toProcess.isEmpty else solve(iter - 1)
    }

    if (solve(n)) io.writeLine("YES").writeAll(ans) else io.writeLine("NO")
  }
}
/****************************[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
      }
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val l, r = io.read[Array, Int](n)
    val ans = Array.ofDim[Int](n)
    val toProcess = mutable.Set(ans.indices : _*)

    def solve(iter: Int): Option[Seq[Int]] = {
      if (toProcess.isEmpty) {
        Some(ans)
      } else {
        val canFill = toProcess.filter(i => l(i) == 0 && r(i) == 0)
        if (canFill.isEmpty) {
          None
        } else {
          canFill foreach {i =>
            (0 until n).foreach(j => if(j < i) r(j) -= 1 else if (j > i) l(j) -= 1 else if (i == j) ans(i) = iter)
            toProcess -= i
//            debug(iter, i)
//            println(ans.mkString(" "))
//            println(l.mkString(" "))
//            println(r.mkString(" "))
//            println("----")
          }
          solve(iter - 1)
        }
      }
    }

    solve(n) match {
      case Some(sol) => io.writeLine("YES").writeAll(sol)
      case _ => io.write("NO")
    }
  }
}
/****************************[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
      }
    }
  }
}