object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  println((1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    if (i != t)
      in.next()
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), j)
    }
    val dy = Math.abs(yo1 - yo2)
    val dx = Math.abs(xo1 - xo2)
    if (dy == 4 && dx == 4)
      "YES"
    else if (dy == 4 && dx == 0)
      "YES"
    else if (dy == 0 && dx == 4)
      "YES"
    else
      "NO"
  }.mkString("\n"))
}

object A extends App {

  def canReach(i0: Int, j0: Int, i: Int, j: Int): Int = {
    val di = Math.abs(i - i0)
    val dj = Math.abs(j - j0)
    if (di % 2 != 0 || dj % 2 != 0 || (di + dj) % 4 != 0) -1
    else (Math.max(di, dj) / 2) % 2
  }

  val t = readInt
  var first = true

  for (test <- 0 until t) {
    if (!first) readLine
    first = false
    val board = Array.fill(8)(readLine)
    var i1, j1, i2, j2 = -1
    for (i <- 0 until 8; j <- 0 until 8; if board(i)(j) =='K') {
      if (i1 == -1) {
        i1 = i; j1 = j
      } else {
        i2 = i; j2 = j
      }
    }
    var ok = false
    for (i <- 0 until 8; j <- 0 until 8; if board(i)(j) !='#') {
      val cr1 = canReach(i1, j1, i, j)
      val cr2 = canReach(i2, j2, i, j)
      if (cr1 >= 0 && cr2 >= 0 && cr1 == cr2) ok =  true
    }
    println(if (ok) "YES" else "NO")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  println((1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    if (i != t)
      in.next()
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), j)
    }
    val dy = Math.abs(yo1 - yo2)
    val dx = Math.abs(xo1 - xo2)
    if (dy % 2 != 0 || dx % 2 != 0)
      "NO"
    else if (dy % 4 != dx % 4)
      "NO"
    else
      "YES"
  }.mkString("\n"))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  println((1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j,  data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), y2)
    }
    if ((xo1 - xo2) % 2 == 0 && (yo1 - yo2) % 2 == 0) "YES"
    else "NO"
  }.mkString("\n"))
}
//fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  (1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j,  data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), y2)
    }
    if ((xo1 - xo2) % 2 == 0 && (yo1 - yo2) % 2 == 0) "YES"
    else "NO"
  }
}
//fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  println((1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    if (i != t)
      in.next()
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), y2)
    }
    val dy = Math.abs(yo1 - yo2)
    val dx = Math.abs(xo1 - xo2)
    if (dy % 2 != 0 || dx % 2 != 0)
      "NO"
    else if (dy % 4 != dx % 4)
      "NO"
    else
      "YES"
  }.mkString("\n"))
}


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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val mask = (1 << K) - 1

    val maxs = Array.fill[SegmentTree](1 << K)(new SegmentTree(N, -1e9.toInt - 10))

    def aggr(a: Array[Int], bit: Int) = {
      var sum = 0
      REP(K) { k =>
        val sign = if ((bit & 1 << k) > 0) 1 else -1
        sum += sign * a(k)
      }
      sum
    }

    def set(i: Int, a: Array[Int]) = {
      REP(1 << K) { bit =>
        maxs(bit).update(i, aggr(a, bit))
      }
    }

    REP(N) { i =>
      val a = na(K)
      set(i, a)
    }

    REP(ni()) { _ =>
     if (ni() == 1) {
        val i = ni() - 1
        val b = na(K)
        set(i, b)
      } else {
        val l, r = ni() - 1
        var mx = 0
        REP((1 << K) / 2) { bit =>
          maxs(bit).query(l, r + 1)
          val rev = ~bit & mask
          mx = max(mx, abs(maxs(bit).query(l, r) + maxs(rev).query(l, r)))
        }

        out.println(mx)
      }
    }
  }

  /**
    * @param n 個数 最大値じゃないぞ。
    * iの範囲は[0, n - 1]
    *
    * AがIntやLongのときは埋め込んでしまおう
    */
  class SegmentTree(n: Int, zero: Int) {
    import math.{max => f}

    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b]
      */
    def query(a: Int, b: Int): Int = {
      var res: Int = zero
      var left = a + N
      var right = b + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }

  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)

  def solve(): Unit = {
    val N, K = ni()
    val mask = (1 << K) - 1

    val maxs = Array.fill[SegmentTree](1 << K)(new SegmentTree(N, -1e9.toInt - 10))

    def aggr(a: Array[Int], bit: Int) = {
      var sum = 0
      REP(K) { k =>
        val sign = if ((bit & 1 << k) > 0) 1 else -1
        sum += sign * a(k)
      }
      sum
    }

    def set(i: Int, a: Array[Int]) = {
      REP(1 << K) { bit =>
        maxs(bit).update(i, aggr(a, bit))
      }
    }

    REP(N) { i =>
      val a = na(K)
      set(i, a)
    }

    REP(ni()) { _ =>
      ni() match {
        case 1 =>
          val i = ni() - 1
          val b = na(K)
          set(i, b)
        case 2 =>
          val l, r = ni() - 1
          var mx = 0
          REP((1 << K) / 2) { bit =>
            maxs(bit).query(l, r + 1)
            val rev = ~bit & mask
            mx = max(mx, abs(maxs(bit).query(l, r) + maxs(rev).query(l, r)))
          }

          out.println(mx)
      }
    }
  }

  /**
    * @param n 個数 最大値じゃないぞ。
    * iの範囲は[0, n - 1]
    *
    * AがIntやLongのときは埋め込んでしまおう
    */
  class SegmentTree(n: Int, zero: Int) {
    import math.{max => f}

    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b]
      */
    def query(a: Int, b: Int): Int = {
      var res: Int = zero
      var left = a + N
      var right = b + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }

  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 scala.collection.mutable.ArrayBuffer

object G extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  case class MaxSegTree(as: Array[Int]) {

    val NEUTRAL = -10000000

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = Math.max(t(v2), t(v2 + 1))
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      if (l > r) NEUTRAL
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        Math.max(query(l, Math.min(r, tm), v2, tl, tm),
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))
      }
    }

    def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) = newT
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, newT, v2, tl, tm)
        else update(pos, newT, v2 + 1, tm + 1, tr)
        t(v) = Math.max(t(v2), t(v2 + 1))
      }
    }

  }

  val Array(n, k) = readInts(2)

  val maxDim = (1 << k) - 1
  val zeros = Array.fill(n)(0)
  val maxSTs = Array.fill(maxDim + 1){ MaxSegTree(zeros) }

  val cs = Array.ofDim[Int](maxDim + 1, k)
  for (dim <- 0 to maxDim) {
    var j = 0
    while (j < k) {
      cs(dim)(j) = if ((dim & (1 << j)) > 0) -1 else 1
      j += 1
    }
  }

  val dimMirrors = Array.tabulate(maxDim + 1){ i =>
    val mirror = cs(i).map(- _)
    cs.indexWhere(_ sameElements mirror)
  }

  val as = Array.ofDim[Int](k)

  for (i <- 0 until n) {
    val tok = new java.util.StringTokenizer(readLine)
    var jj = 0
    while (jj < k) {
      as(jj) = tok.nextToken().toInt
      jj += 1
    }
    var dim = 0
    while (dim <= maxDim) {
      var dist = 0
      var j = 0
      while (j < k) {
        dist += cs(dim)(j) * as(j)
        j += 1
      }
      maxSTs(dim).update(i, dist)
      dim += 1
    }
  }

  val Array(q) = readInts(1)
  val res = ArrayBuffer.empty[Int]

  for (_ <- 1 to q) {
    val s = readLine
    if (s.head == '1') {
      val tok = new java.util.StringTokenizer(s)
      tok.nextToken()
      val i = tok.nextToken().toInt - 1
      var jj = 0
      while (jj < k) {
        as(jj) = tok.nextToken().toInt
        jj += 1
      }
      var dim = 0
      while (dim <= maxDim) {
        var dist = 0
        var j = 0
        while (j < k) {
          dist += cs(dim)(j) * as(j)
          j += 1
        }
        maxSTs(dim).update(i, dist)
        dim += 1
      }
    } else {
      val tok = new java.util.StringTokenizer(s)
      tok.nextToken()
      val l = tok.nextToken().toInt - 1
      val r = tok.nextToken().toInt - 1
      var max = 0
      var dim = 0
      while (dim <= maxDim) {
        val mirrorDim = dimMirrors(dim)
        val d = maxSTs(dim).query(l, r) + maxSTs(mirrorDim).query(l, r)
        if (d > max) max = d
        dim += 1
      }
      res += max
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString("\n"))
  Console.flush
}

import scala.collection.mutable.ArrayBuffer

object G extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  case class MaxSegTree(as: Array[Int]) {

    val NEUTRAL = -10000000

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = Math.max(t(v2), t(v2 + 1))
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      if (l > r) NEUTRAL
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        Math.max(query(l, Math.min(r, tm), v2, tl, tm),
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))
      }
    }

    def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) = newT
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, newT, v2, tl, tm)
        else update(pos, newT, v2 + 1, tm + 1, tr)
        t(v) = Math.max(t(v2), t(v2 + 1))
      }
    }

  }

  val Array(n, k) = readInts(2)

  val maxDim = BigInt(2).pow(k).toInt - 1
  val zeros = Array.fill(n)(0)
  val maxSTs = Array.fill(maxDim + 1){ MaxSegTree(zeros) }

  val cs = Array.ofDim[Int](maxDim + 1, k)
  for (dim <- 0 to maxDim) {
    var j = 0
    var dd = dim
    while (j < k) {
      val ddd = dd % 2
      cs(dim)(j) = if (ddd == 0) -1 else 1
      j += 1
      dd /= 2
    }
  }

  val dimMirrors = Array.tabulate(maxDim + 1){ i =>
    val mirror = cs(i).map(- _)
    cs.indexWhere(_ sameElements mirror)
  }

  val as = Array.ofDim[Int](k)

  for (i <- 0 until n) {
    val tok = new java.util.StringTokenizer(readLine)
    var jj = 0
    while (jj < k) {
      as(jj) = tok.nextToken().toInt
      jj += 1
    }
    var dim = 0
    while (dim <= maxDim) {
      var dist = 0
      var j = 0
      while (j < k) {
        dist += cs(dim)(j) * as(j)
        j += 1
      }
      maxSTs(dim).update(i, dist)
      dim += 1
    }
  }

  val Array(q) = readInts(1)
  val res = ArrayBuffer.empty[Int]

  for (_ <- 1 to q) {
    val s = readLine
    if (s.head == '1') {
      val tok = new java.util.StringTokenizer(s)
      tok.nextToken()
      val i = tok.nextToken().toInt - 1
      var jj = 0
      while (jj < k) {
        as(jj) = tok.nextToken().toInt
        jj += 1
      }
      var dim = 0
      while (dim <= maxDim) {
        var dist = 0
        var j = 0
        while (j < k) {
          dist += cs(dim)(j) * as(j)
          j += 1
        }
        maxSTs(dim).update(i, dist)
        dim += 1
      }
    } else {
      val tok = new java.util.StringTokenizer(s)
      tok.nextToken()
      val l = tok.nextToken().toInt - 1
      val r = tok.nextToken().toInt - 1
      var max = 0
      var dim = 0
      while (dim <= maxDim) {
        val mirrorDim = dimMirrors(dim)
        val d = maxSTs(dim).query(l, r) + maxSTs(mirrorDim).query(l, r)
        if (d > max) max = d
        dim += 1
      }
      res += max
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString("\n"))
  Console.flush
}

import scala.collection.mutable.ArrayBuffer

object G extends App {

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

  case class MaxSegTree(as: Array[Int]) {

    val NEUTRAL = -10000000

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = Math.max(t(v2), t(v2 + 1))
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      if (l > r) NEUTRAL
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        Math.max(query(l, Math.min(r, tm), v2, tl, tm),
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))
      }
    }

    def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) = newT
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, newT, v2, tl, tm)
        else update(pos, newT, v2 + 1, tm + 1, tr)
        t(v) = Math.max(t(v2), t(v2 + 1))
      }
    }

  }

  val Array(n, k) = readInts(2)

  val maxDim = BigInt(3).pow(k).toInt - 1
  val zeros = Array.fill(n)(0)
  val maxSTs = Array.fill(maxDim + 1){ MaxSegTree(zeros) }

  val cs = Array.ofDim[Int](maxDim + 1, k)
  for (dim <- 1 to maxDim) {
    var j = 0
    var dd = dim
    while (j < k) {
      val ddd = dd % 3
      cs(dim)(j) = if (ddd == 2) -1 else ddd
      j += 1
      dd /= 3
    }
  }

  val dimMirrors = Array.tabulate(maxDim + 1){ i =>
    val mirror = cs(i).map(- _)
    cs.indexWhere(_ sameElements mirror)
  }

  val as = Array.ofDim[Int](k)

  for (i <- 0 until n) {
    val tok = new java.util.StringTokenizer(readLine)
    var jj = 0
    while (jj < k) {
      as(jj) = tok.nextToken().toInt
      jj += 1
    }
    var dim = 1
    while (dim <= maxDim) {
      var dist = 0
      var j = 0
      while (j < k) {
        dist += cs(dim)(j) * as(j)
        j += 1
      }
      maxSTs(dim).update(i, dist)
      dim += 1
    }
  }

  val Array(q) = readInts(1)
  val res = ArrayBuffer.empty[Int]

  for (_ <- 1 to q) {
    val s = readLine
    if (s.head == '1') {
      val tok = new java.util.StringTokenizer(s)
      tok.nextToken()
      val i = tok.nextToken().toInt - 1
      var jj = 0
      while (jj < k) {
        as(jj) = tok.nextToken().toInt
        jj += 1
      }
      var dim = 1
      while (dim <= maxDim) {
        var dist = 0
        var j = 0
        while (j < k) {
          dist += cs(dim)(j) * as(j)
          j += 1
        }
        maxSTs(dim).update(i, dist)
        dim += 1
      }
    } else {
      val tok = new java.util.StringTokenizer(s)
      tok.nextToken()
      val l = tok.nextToken().toInt - 1
      val r = tok.nextToken().toInt - 1
      var max = 0
      var dim = 1
      while (dim <= maxDim) {
        val mirrorDim = dimMirrors(dim)
        val d = maxSTs(dim).query(l, r) - maxSTs(mirrorDim).query(l, r)
        if (d > max) max = d
        dim += 1
      }
      res += max
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString("\n"))
  Console.flush
}

import scala.collection.mutable.ArrayBuffer

object G extends App {

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

  case class MaxSegTree(as: Array[Int]) {

    val NEUTRAL = -10000000

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) max t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      if (l > r) NEUTRAL
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        query(l, Math.min(r, tm), v2, tl, tm) max
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
      }
    }

    def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) = newT
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, newT, v2, tl, tm)
        else update(pos, newT, v2 + 1, tm + 1, tr)
        t(v) = t(v2) max t(v2 + 1)
      }
    }

  }

  case class MinSegTree(as: Array[Int]) {

    val NEUTRAL = 10000000

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) min t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      if (l > r) NEUTRAL
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        query(l, Math.min(r, tm), v2, tl, tm) min
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
      }
    }

    def update(pos: Int, newT: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) = newT
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, newT, v2, tl, tm)
        else update(pos, newT, v2 + 1, tm + 1, tr)
        t(v) = t(v2) min t(v2 + 1)
      }
    }

  }

  val Array(n, k) = readInts(2)
  val maxDim = (1 << k) - 1
  val zeros = Array.fill(n)(0)
  val minSTs = Array.fill(maxDim + 1){ MinSegTree(zeros) }
  val maxSTs = Array.fill(maxDim + 1){ MaxSegTree(zeros) }

  for (i <- 0 until n) {
    val as = readInts(k)
    for (dim <- 1 to maxDim) {
      var dist = 0
      var j = 0
      while (j < k) {
        if ((dim & (1 << j)) > 0) dist += as(j)
        j += 1
      }
      minSTs(dim).update(i, dist)
      maxSTs(dim).update(i, dist)
    }
  }

  val Array(q) = readInts(1)
  val res = ArrayBuffer.empty[Int]

  for (_ <- 1 to q) {
    val s = readLine
    if (s.head == '1') {
      val tok = new java.util.StringTokenizer(s)
      tok.nextToken()
      val i = tok.nextToken().toInt - 1
      val as = Array.fill(k){ tok.nextToken().toInt }
      for (dim <- 1 to maxDim) {
        var dist = 0
        var j = 0
        while (j < k) {
          if ((dim & (1 << j)) > 0) dist += as(j)
          j += 1
        }
        minSTs(dim).update(i, dist)
        maxSTs(dim).update(i, dist)
      }
    } else {
      val tok = new java.util.StringTokenizer(s)
      tok.nextToken()
      val l = tok.nextToken().toInt - 1
      val r = tok.nextToken().toInt - 1
      var max = 0
      for (dim <- 1 to maxDim) {
        val d = maxSTs(dim).query(l, r) - minSTs(dim).query(l, r)
        if (d > max) max = d
      }
      res += max
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString("\n"))
  Console.flush
}


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

import scala.collection.mutable._

object Solution {

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

  def gao(x: Array[Int], v: Array[Int], t: Double): Boolean = {
    var l: Double = 0
    var r: Double = 1e9

    for (i <- x.indices) {
      l = Math.max(l, x(i) - v(i) * t)
      r = Math.min(r, x(i) + v(i) * t)
    }

    l <= r
  }

  def main(args: Array[String]) {
    val Array(n) = readInts(1)

    val x = readInts(n)
    val v = readInts(n)

    var l: Double = 0
    var r: Double = 1e9
    var ans: Double = 0

    while (Math.abs(l-r) / Math.max(1, l) > 1e-9) {
      val mid = (l + r) / 2

      //println(l + " " + r)

      if (gao(x, v, mid)) {
        ans = mid
        r = mid
      }
      else l = mid
    }

    println(ans)

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import scala.io.StdIn.readLine

object B extends App {
  val n = readLine.toInt

  val x = readLine.split(' ').map(_.toInt)
  val v = readLine.split(' ').map(_.toInt)

  def meet(t: Double): Boolean = {
    val (from, to) = (0 until n).foldLeft((Double.MinValue, Double.MaxValue)) {
      case ((begin, end), i) ⇒ (begin.max(x(i) - v(i) * t), end.min(x(i) + v(i) * t))
    }
    to >= from
  }

  def binSearch(a: Double, b: Double): Double = {
    val m = (a + b) / 2
    if ((b - a) / (b + 1) < 1e-9) m else if (meet(m)) binSearch(a, m) else binSearch(m, b)
  }

  val res = binSearch(0, 3e9)
  println(f"$res%.9f")
}


object C {
  def main(args: Array[String]) = {
    val data = readLine().split(' ').map(t => t.toInt)
    val n = data(0)
    val r: Long = data(1)
    val avg: Long = data(2)
    val goal = avg * n
    val exams = (1 to n).map(_ => {
      val ab = readLine.split(' ').map(t => t.toLong)
      (ab(0), ab(1))
    }).sortBy(e => e._2)
    var ans: Long = 0
    val sum = exams.foldLeft(0L)((sum, e) => sum + e._1)
    exams.foldLeft(sum)((acc, e) => {
      val add: Long = math.max(0L, math.min(r - e._1, goal - acc))
      ans += add * e._2
      acc + add
    })
    println(ans)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, r, avg) = in.next().split(" ").map(_.toInt)
  val data = (1 to n).map{_ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt)
    (b, a)
  }.sorted
  val sum = data.map(_._2).foldLeft(0l)(_+_)
  val all = avg * 1l * n
  val t = data.foldLeft((sum, 0l)) {
    case((s, inc), el) if s >= all => (s, inc)
    case((s, inc), (b, a)) =>
      val need = all - s
      val referats = Math.min(need, r - a)
      (s + referats, inc + referats * b)
  }
  println(t._2)

}

import scala.collection._

object C extends App {

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

  val Array(n, r, avg) = readLongs(3)

  val as, bs = Array.ofDim[Long](n.toInt)

  for (i <- 0 until n.toInt) {
    var Array(a, b) = readInts(2)
    as(i) = a
    bs(i) = b
  }
  val abs = (bs zip as).sorted

  var need = avg * n - as.sum
  var cnt = 0L
  var i = 0

  while (need > 0) {
    val take = need min (r - abs(i)._2)
    cnt += take * abs(i)._1
    need -= take
    i += 1
  }

  println(cnt)
}

object P492C {
	def convert(a: Array[Long]) : (Long, Long) = (a(0), a(1))

	def pick(need: Long, max: Long, options: List[(Long, Long)]) : Long = {
		if (need < 1) {
			0
		} else {
			val points = math.min(need, max - options.head._1)
			val essays = points * options.head._2
			essays + pick(need - points, max, options.tail)
		}
	}

	def main(args: Array[String]) {
		val lines = scala.io.Source.stdin.getLines.toList
		val Array(n, r, avg) = lines.head.split(" ").map(_.toLong)
		val exams = lines.tail.map(_.split(" ").map(_.toLong)).map(convert)
		val options = exams.filter(_._1 < r).sortBy(_._2)
		val points = n * avg - exams.map(_._1).sum
		println(pick(points, r, options))
	}
}

import java.io._
import java.util._
import java.util.StringTokenizer

import scala.util.Sorting

object Solution {

  class Pair(val first: Int, val second: Int) extends Comparable[Pair] {
      override def compareTo(p: Pair): Int = {
        if (first != p.first)
          return first - p.first
        return second - p.second
      }
  }

  def solve(in: FastScanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val max = in.nextInt()
    val avg: Long = in.nextLong()
    val want: Long = avg * n
    var have: Long = 0
    val a = new Array[Pair](n)
    for (i <- 0 until n) {
      val curr = in.nextInt()
      val cost = in.nextInt()
      have += curr
      a(i) = new Pair(cost, max - curr)
    }
    Sorting.quickSort(a)
    var res: Long = 0
    if (have > want)
      have = want
    for (i <- 0 until n) {
      val add: Long = Math.min(want - have, a(i).second)
      have += add
      res += add * a(i).first
    }
    out.println(res)
  }

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

  class FastScanner(val in: InputStream) {
    var st: StringTokenizer = null
    var br = new BufferedReader(new InputStreamReader(in))

    def next(): String = {
      while (st == null || !st.hasMoreTokens()) {
        val line = br.readLine()
        if (line == null)
          throw new IOException()
        st = new StringTokenizer(line)
      }
      return st.nextToken()
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def close(): Unit = {
      br.close()
    }
  }

}

object Main extends App {
  val Array(n,r,avg) = readLine.split(" ").map(_.toLong)
  val abi = (1L to n).map({ _ =>
    val Array(a,b) = readLine.split(" ").map(_.toLong)
    (a,b)
  })
  val total = abi.map(_._1).sum
  val goal = n * avg
  if(total >= goal) {
    println("0")
  } else {
    val diff = goal - total
    val abit = abi.sortBy(_._2)
    val (_, counter) = abi.sortBy(_._2).foldLeft((diff, 0L))({
      case ((0L, count), _) => (0L, count)
      case ((d, count), (a, b)) => {
        val available = r - a
        if(d >= available) {
          ((d-available), count + available*b)
        } else {
          (0L, count + d*b)
        }
      }
    })
    println(counter)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, r, avg) = in.next().split(" ").map(_.toInt)
  val data = (1 to n).map{_ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt)
    (b, a)
  }.sorted
  val sum = data.map(_._2).sum
  val t = data.foldLeft((sum, 0)) {
    case((s, inc), el) if s >= avg * n => (s, inc)
    case((s, inc), (b, a)) =>
      val need = avg * n - s
      val referats = Math.min(need, r - a)
      (s + referats, inc + referats * b)
  }
  println(t._2)

}

import scala.collection._

object C extends App {

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

  val Array(n, r, avg) = readInts(3)

  val as, bs = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    var Array(a, b) = readInts(2)
    as(i) = a
    bs(i) = b
  }
  val abs = (bs zip as).sorted

  var need = avg * n - as.sum
  var cnt = 0
  var i = 0

  while (need > 0) {
    val take = need min (r - abs(i)._2)
    cnt += take * abs(i)._1
    need -= take
    i += 1
  }

  println(cnt)
}

object C {
  def main(args: Array[String]) = {
    val data = readLine().split(' ').map(t => t.toInt)
    val n = data(0)
    val r: Long = data(1)
    val avg: Long = data(2)
    val goal = avg * n
    val exams = (1 to n).map(_ => {
      val ab = readLine.split(' ').map(t => t.toLong)
      (ab(0), ab(1))
    }).sortBy(e => e._2)
    var ans: Long = 0
    val sum = exams.foldLeft(0L)((sum, e) => sum + e._1)
    exams.foldLeft(sum)((acc, e) => {
      val add: Long = math.min(r - e._1, goal - acc)
      ans += add * e._2
      acc + add
    })
    println(ans)
  }
}

object P492C {
	def convert(a: Array[Int]) : (Int, Int) = (a(0), a(1))

	def pick(need: Int, max: Int, options: List[(Int, Int)]) : Int = {
		if (need < 1) {
			0
		} else {
			val points = math.min(need, max - options.head._1)
			val essays = points * options.head._2
			essays + pick(need - points, max, options.tail)
		}
	}

	def main(args: Array[String]) {
		val lines = scala.io.Source.stdin.getLines.toList
		val Array(n, r, avg) = lines.head.split(" ").map(_.toInt)
		val exams = lines.tail.map(_.split(" ").map(_.toInt)).map(convert)
		val options = exams.filter(_._1 < r).sortBy(_._2)
		val points = n * avg - exams.map(_._1).sum
		println(pick(points, r, options))
	}
}

object Main extends App {
  val Array(n,r,avg) = readLine.split(" ").map(_.toLong)
  val abi = (1L to n).map({ _ =>
    val Array(a,b) = readLine.split(" ").map(_.toLong)
    (a,b)
  })
  val total = abi.map(_._1).sum
  val goal = n * avg
  if(total >= goal) {
    println("0")
  } else {
    val diff = goal - total
    val abit = abi.sortBy(_._2)
    val (_, counter) = abi.sortBy(_._2).foldLeft((diff, 0L))({
      case ((0L, count), _) => (0L, count)
      case ((d, count), (a, b)) => {
        val available = r - a
        if(d >= available) {
          ((d-available), count + available*b)
        } else {
          (0L, count + (available-d)*b)
        }
      }
    })
    println(counter)
  }
}


import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

object _595B extends CodeForcesApp {
  override type Result = Long

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, k) = (nextInt(), nextInt())
    val blocks = n/k
    val as = Seq.fill(blocks)(nextLong())
    val bs = Seq.fill(blocks)(nextLong())
    val maxBlock = pow(10, k)
    val p = maxBlock/10

    var ans = 1L
    for {
      (a, b) <- as zip bs
    } {
      val t1 = numberOfMultiples(0, maxBlock - 1, a)
      val t2 = numberOfMultiples(b*p, ((b+1)*p) - 1, a)
      val t = t1 - t2
      //debug(a, b, b*p, ((b+1)*p) - 1, t1, t2)
      ans = (ans * t) % mod
    }
    ans
  }

  def pow(a: Int, b: Int): Long = {
    var ans = 1L
    repeat(b) {
      ans *= a
    }
    ans
  }

  /**
    * @return number of multiples of c in [a,b]
    */
  def numberOfMultiples(a: Long, b: Long, c: Long): Long = {
    implicit def toInt(x: Boolean): Long = if (x) 1L else 0L
    c.signum match {
      case -1 => numberOfMultiples(a, b, -c)
      case 1 if b >= a => (b + (b < 0))/c - (a - (a > 0))/c + (a <= 0 && b >= 0)
      case _ => 0
    }
  }

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

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

import scala.collection._

object B extends App {

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

  val Array(n, k) = readInts(2)
  val nk = n / k
  val as = readInts(nk)
  val bs = readInts(nk)
  //val as = Array.fill(nk)(4564654)
  //val bs = Array.fill(nk)(5)

  val mul = BigInt(10).pow(k - 1)
  val MOD = 1000000007L
  val MODB = BigInt(MOD)
  var res = 1L

  for (i <- 0 until nk) {
    val r = if (bs(i) == 0) (10 * mul - 1) / as(i) - (mul - 1) / as(i)
    else 1 + (bs(i) * mul - 1) / as(i) + (10 * mul - 1) / as(i) - ((bs(i) + 1) * mul - 1) / as(i)
    res = (r % MODB).toLong * res % MOD
  }

  println(res % MOD)
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

object _595B extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, k) = (nextInt(), nextInt())
    val blocks = n/k
    val as = Seq.fill(blocks)(nextInt())
    val bs = Seq.fill(blocks)(nextInt())
    val maxBlock = pow(10, k)
    val p = maxBlock/10

    var ans = 1
    for {
      (a, b) <- as zip bs
    } {
      val t1 = numberOfMultiples(0, maxBlock - 1, a)
      val t2 = numberOfMultiples(b*p, ((b+1)*p) - 1, a)
      val t = t1 - t2
      //debug(a, b, b*p, ((b+1)*p) - 1, t1, t2)
      ans = (ans * t) % mod
    }
    ans
  }

  def pow(a: Int, b: Int) = {
    var ans = 1
    repeat(b) {
      ans *= a
    }
    ans
  }

  /**
    * @return number of multiples of c in [a,b]
    */
  def numberOfMultiples(a: Int, b: Int, c: Int): Int = {
    implicit def toInt(x: Boolean): Int = if (x) 1 else 0
    c.signum match {
      case -1 => numberOfMultiples(a, b, -c)
      case 1 if b >= a => (b + (b < 0))/c - (a - (a > 0))/c + (a <= 0 && b >= 0)
      case _ => 0
    }
  }

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

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}


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

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

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

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

  def solve(): Unit = {
    val T = ni()
    rep(T) { _ =>
      val L, v, l, r = ni()
      val all = L/v - 1 /v + (if (1 % v == 0) 1 else 0)
      val hidden = r/v - l/v + (if (l % v == 0) 1 else 0)
      out.println(all - hidden)
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

object A extends App {

  def readInt1(): Int = scala.io.StdIn.readInt()

  val t = readInt1()

  def lamps(l: Int, r: Int, u:Int):Int = {
    r/u-(l-1)/u
  }

  for{i<-0 until t}{
    val line=scala.io.StdIn.readLine()
    val Array(_L,u,l,r)=line.split(" ").map(_.toInt)
    println(lamps(1,_L,u)-lamps(l,r,u))
  }
}

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

  override def apply(io: IO): io.type = {
    val queries = io.read[Traversable[(Int, Int, Int, Int)]]
    val ans = queries map { case (n, v, l, r) => numberOfMultiples(1, n, v) - numberOfMultiples(l, r, v)}
    io.writeAll(ans, separator = "\n")
  }

  def numberOfMultiples(a: Int, b: Int, c: Int): Int = (b + (b < 0))/c - (a - (a > 0))/c + (a <= 0 && b >= 0)
  implicit def toInt(x: Boolean): Int = if (x) 1 else 0
}
/****************************[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 A extends App {

  def readInt1(): Int = scala.io.StdIn.readInt()

  val t = readInt1()
  for{i<-0 until t}{
    val line=scala.io.StdIn.readLine()
    val Array(_L,u,l,r)=line.split(" ").map(_.toInt)
    println(_L/u-(r-l+1))
  }
}


import java.util.StringTokenizer

object _545A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => (1 to n).map(j => next.toInt).toArray).toArray
  val ans = for {
    i <- 0 until n
    if (0 until n).filter(j => i != j).forall(j => i != j && (a(i)(j) & 1) == 0)
  } yield i

  println(ans.length)
  if (ans.length > 0) println(ans.map(i => i + 1).mkString(" "))
}

import scala.io.StdIn

/**
 * Created by tignatchenko on 07.09.2015.
 */
object z1 extends App {
  var n:Int = StdIn.readInt()
  var mtx = Array.ofDim[Int](n,n)
  var dd = new Array[Int](n)
  for (i<-0 until n) {
      mtx(i)= StdIn.readLine().split(" ").map(Integer.parseInt)
      for(j<-0 until n) {
        val n = mtx(i)(j)
        if (n==1 || n==3) dd(i)+=1
        if (n==2 || n==3) dd(j)+=1
      }
  }
  println(dd.count(_==0))
  var k = 0;
  dd.foreach(x=>{
    k+=1
    if(x==0) print(k+" ")

  })
}

import scala.io.StdIn
object z1 extends App {
  var dd = new Array[Int](StdIn.readInt())
  var k = 0
  (0 until dd.length).foreach(i=>StdIn.readLine().split(" ").map(Integer.parseInt).foreach(n=>{ if (n==1 || n==3) dd(i)+=1 }))
  println(dd.count(_==0))
  dd.foreach(x=>{k+=1; if(x==0) print(k+" ")})
}

object A545 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val mat = Array.fill(n)(readInts(n))
    var ret = Array.empty[Int]

    for(i <- 0 until n) {
      if(!mat(i).exists{x => (x == 1 || x == 3)}) {
        ret ++= Array(i+1)
      }
    }

    println(ret.length)
    println(ret.mkString(" "))
  }

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

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

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

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

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

}

object A545 extends App {
  var mp = Map[Int, Int]()
  val n = readInt
  for(i <- 0 until n)
  {
    mp += (i -> 0)
    val row = readLine.split(' ').map(_.toInt)
    for(j <- 0 until n if i != j) {
      row(j)
      match
      {
        case 1 => mp += (i -> 1)
        case 2 => mp += (j -> 1)
        case 3 => mp += (i -> 1); mp += (i -> 1)
        case _ =>
      }
    }
  }

  val result = mp.filter(_._2 == 0).map(p => (p._1 + 1, p._2)).keys.toList
  if (result.isEmpty)
    print(0)
  else {
    println(result.size)
    println(result.sorted.mkString(" "))
  }
}

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

import scala.collection.mutable

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Array[Int]](n)
    val machines = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      a(i) = new Array[Int](n)
      machines.add(i)
    }
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        a(i)(j) = nextInt
        a(i)(j) match {
          case 1 => machines.remove(i)
          case 2 => machines.remove(j)
          case 3 => {
            machines.remove(i)
            machines.remove(j)
          }
          case _ =>
        }
      }
    }
    out.println(machines.size)
    val list = new Array[Int](machines.size)
    var ind = 0
    for (x <- machines) {
      list(ind) = (x + 1)
      ind += 1
    }
    list.sorted.foreach(x => out.print(x + " "))

    return 0
  }
}

object _545A extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[List[Int]]
  override type Output = List[Int]

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    val n = nextInt
    List.fill(n, n)(nextInt)
  }

  override def solve(input: Input) = {
    input.zipWithIndex flatMap {case (line, idx) =>
      when (!(line contains 1) && !(line contains 3)) {
        idx
      }
    }
  }

  override def format(result: Output) = s"${result.length}${result.sorted.map(_ + 1).mkString("\n", " ", "")}"
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

import scala.io.StdIn

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

    val bPerf = Array.fill[Boolean](n)(true);

    for(i <- 0 until n; nums = StdIn.readLine().split(" ").map(Integer.parseInt);
        j <- 0 until n; num = nums(j)) {

      def setFalse(ind : Int*) = ind.foreach(bPerf(_) = false)

      num match {
          case -1 | 0 => ;
          case 1 => setFalse(i)
          case 2 => setFalse(j)
          case 3 => setFalse(i, j)
      }
    }

    val listPerf = bPerf.zipWithIndex.filter(_._1).map(_._2);

    println(listPerf.length);
    listPerf.foreach( x => print((x + 1) + " ") )
  }
}

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

object A extends App {
  val n = readInt()
  val Cars = Array.ofDim[Int](n, n)
  for (i <- 0 until n) {
    Cars(i) = readLine().split(" ").map(_.toInt)
  }

  var answer = new ArrayBuffer[Int]()
  def solve() = {
    for (i <- 0 until n) {
      var turnedOver = false
      for (j <- 0 until n) {
//        println(s"Consider $car1 vs $car2")

        if (Cars(i)(j) == 1 || Cars(i)(j) == 3) {
          turnedOver = true
        }
      }

      if (!turnedOver) answer += i + 1
    }

    println(answer.size)
    if (answer.size > 0) println(answer.mkString(" "))
  }

  solve()
}

import scala.io.StdIn
object a extends App {
  val n = StdIn.readInt()
  val y = (1 to n).toSet -- (1 to n).map{
    i => StdIn.readLine().split(" ").map(_.toInt).map{
      x => if (x==1 || x==3) Some(i) else None
    }.flatten
  }.flatten
  println(y.size)
  y.toList.sorted.foreach(x => print(x+" "))
}

import scala.io.StdIn._

/**
 * Created by przemek on 19.05.15.
 */
object ToyCar {
  def main(args : Array[String]) = {
    val N = readInt()
    val A = Array.ofDim[Int](N,N)
    for (i <- 0 to N -1) {
      A(i) = readLine().split(" ").map(_.toInt)
    }

    var c = 0
    val buf = scala.collection.mutable.ArrayBuffer.empty[Int]
    for(i <- 0 to N - 1)
    {
      var bad = false
      for( j <- 0 to N -1){
        if(A(i)(j) == 1 || A(i)(j)==3){
         bad = true
        }
      }

      if(!bad){
        c = c + 1
        buf += i+1
      }
    }
    println(c)
    println( buf.mkString(" "))
//    println(A.map(_.mkString(" ")).mkString(" "))
  }
}

object Atest{
  //import scala.collection.mutable.PriorityQueue
  import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val g=ArrayBuffer[Int]()
    for(i<-1 to n){
      var good=true
      for(_<- 0 until n){
        val k=nextInt
        if(k==1||k==3){
          good=false
        }
      }
      if(good){
        g+=i
      }
    }
    out.println(g.length)
    if(g.length>0){
      for(i<-g){
        out.print(i+" ")
      }
    }

    //code ends here
    out.flush
    out.close
  }
}

object A545 extends App {
  var mp = Map[Int, Int]()
  val n = readInt
  for(i <- 0 until n)
  {
    mp += (i -> 0)
    val row = readLine.split(' ').map(_.toInt)
    for(j <- 0 until n if i != j) {
      row(j)
      match
      {
        case 1 => mp += (i -> 1)
        case 2 => mp += (j -> 1)
        case 3 => mp += (i -> 1); mp += (i -> 1)
        case _ =>
      }
    }
  }

  val result = mp.filter(_._2 == 0).map(p => (p._1 + 1, p._2)).keys
  if (result.isEmpty)
    print(0)
  else
    println(result.mkString(" "))
}

object A545 extends App {
  var mp = Map[Int, Int]()
  val n = readInt
  for(i <- 0 until n)
  {
    mp += (i -> 0)
    val row = readLine.split(' ').map(_.toInt)
    for(j <- 0 until n if i != j) {
      row(j)
      match
      {
        case 1 => mp += (i -> 1)
        case 2 => mp += (j -> 1)
        case 3 => mp += (i -> 1); mp += (i -> 1)
        case _ =>
      }
    }
  }

  val result = mp.filter(_._2 == 0).map(p => (p._1 + 1, p._2)).keys
  if (result.isEmpty)
    print(0)
  else {
    println(result.size)
    println(result.mkString(" "))
  }
}

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

import scala.collection.mutable

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Array[Int]](n)
    val machines = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      a(i) = new Array[Int](n)
      machines.add(i)
    }
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        a(i)(j) = nextInt
        a(i)(j) match {
          case 1 => machines.remove(i)
          case 2 => machines.remove(j)
          case 3 => {
            machines.remove(i)
            machines.remove(j)
          }
          case _ =>
        }
      }
    }
    out.println(machines.size)
    for (x <- machines) {
      out.print((x + 1) + " ")
    }
    return 0
  }
}

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

object A extends App {
  val n = readInt()
  val Cars = Array.ofDim[Int](n, n)
  for (i <- 0 until n) {
    Cars(i) = readLine().split(" ").map(_.toInt)
  }

  var answer = new ArrayBuffer[Int]()
  def solve() = {
    for (i <- 0 until n) {
      var turnedOver = false
      var car1 = i + 1
      for (j <- 0 until n) {
        var car2 = j + 1
//        println(s"Consider $car1 vs $car2")

        if (i != j && (Cars(i)(j) == 1 || Cars(i)(j) == 3)) {
          turnedOver = !turnedOver
        }
      }

      if (!turnedOver) answer += i + 1
    }

    println(answer.size)
    if (answer.size > 0) println(answer.mkString(" "))
  }

  solve()
}

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

object A extends App {
  val n = readInt()
  val Cars = Array.ofDim[Int](n, n)
  for (i <- 0 until n) {
    Cars(i) = readLine().split(" ").map(_.toInt)
  }

  var answer = new ArrayBuffer[Int]()
  def solve() = {
    for (i <- 0 until n) {
      var turnedOver = false
      var car1 = i + 1
      for (j <- 0 until n) {
        var car2 = j + 1
//        println(s"Consider $car1 vs $car2")

        if (i != j && (Cars(i)(j) == 1 || Cars(i)(j) == 3)) {
          turnedOver = !turnedOver
        }
      }

      if (!turnedOver) answer += i + 1
    }

    println(answer.size)
    if (answer.size > 0) println(answer.mkString(" "))
  }

  if (n > 1) solve() else println(0)
}

import scala.io.StdIn
object a extends App {
  val n = StdIn.readInt()
  val y = (1 to n).toSet -- (1 to n).map{
    i => StdIn.readLine().split(" ").map(_.toInt).map{
      x => List(if (x==1 || x==3) i)
    }.flatten
  }.flatten
  println(y.size)
  y.foreach(x => print(x+" "))
}


import java.io.BufferedInputStream
import java.util.Scanner

object Main extends App {
  val inputReader = new Scanner(new BufferedInputStream(System.in))
  val T = inputReader.nextInt()
  @scala.annotation.tailrec
  def bestK(d: Int, bestSoFar: Int): Int = {
    val k = bestSoFar + 1
    if (k * (k + 1) < d) {
      bestK(d, k)
    } else {
      bestSoFar
    }
  }
  for (_ <- 0 until T) {
    val n = inputReader.nextInt()
    val d = inputReader.nextInt()
    val x = bestK(d, 1) - 1
    val minDays = Math.min(x + (d + x) / (x + 1), x + 1 + (d + x + 1) / (x + 2))
    if (minDays <= n) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val Array(n, d) = readLine.split(" ").map(_.toInt)
        if (f2(n, d)) { println("YES") } else { println("NO") }
    }

    def f2(n: Long, d: Long): Boolean = {
        val x = bs(0, d, d)
        (x + (d + x) / (x + 1) <= n)
    }

    def bs(min: Long, max: Long, d: Long): Long = if (min + 1 >= max) min else {
        val mid = (min + max) / 2
        if (aux(mid, d)) bs(mid, max, d) else bs(min, mid, d)
    }

    def aux(x: Long, d: Long): Boolean = x < ((d + x) / (x + 1))
  }

import scala.io.StdIn._
object Main extends App {

  for (_ ← 0 until readInt) {
    val Array(n, d) = readLine.trim.split(' ').map(_.toInt)
    println(
      if ((0 to math.sqrt(d).toInt).exists(x ⇒ x + ((d + x) / (x + 1)) <= n)) "YES" else "NO"
    )
  }
}

object Main extends App {
    val t = new Adilbek
    t.run
}

class Adilbek {
    def run() = {
        val t = scala.io.StdIn.readLine().toInt
        for(i <- 0 until t) {
            val test = scala.io.StdIn.readLine()
            calc(test)
        }
    }

    def calc(test:String):Unit = {
        val args = test.split(" ").map(_.toInt)
        for(opt <- 0 to args(0)-1) {
            if( opt*opt + (1-args(0))*opt + (args(1) -args(0)) <= 0 ){
                println("YES")
                return
            }
        }
        println("NO")
    }
}

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val Array(n, d) = readLine.split(" ").map(_.toInt)
        if (f2(n, d)) { println("YES") } else { println("NO") }
    }

    def f2(n: Long, d: Long): Boolean = {
        val x = bs(0, n, d)
        (x + (d + x) / (x + 1) <= n)
    }

    def bs(min: Long, max: Long, d: Long): Long = if (min + 1 >= max) min else {
        val mid = (min + max) / 2
        if (aux(mid, d)) bs(mid + 1, max, d) else bs(min, mid, d)
    }

    def aux(x: Long, d: Long): Boolean = x < ((d + x) / (x + 1))
  }

object Main extends App {
    val t = new Adilbek
    t.run
}

class Adilbek {
    def run() = {
        val t = scala.io.StdIn.readLine().toInt
        for(i <- 0 until t) {
            val test = scala.io.StdIn.readLine()
            calc(test)
        }
    }

    def calc(test:String):Unit = {
        val args = test.split(" ").map(_.toInt)
        for(opt <- 0 to args(0)-1) {
            if( opt*opt + (1-args(0))*opt + (args(1) -args(0)) <= 0 ){
                println("TRUE")
                return
            }
        }
        println("FALSE")
    }
}


//package solutions

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

import scala.collection.mutable

/**
  * @author traff
  */

object SolTaskA extends App {
  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new Scanner(System.in), out)

    out.close()
  }

  def run(s: Scanner, out: PrintWriter): Unit = {

    val Array(v, r) = s.nextLine().split(" ")

    out.println(s"$v $r")

    val n = s.nextLine().toInt

    val a = new Array[String](n)

    val map = new mutable.HashMap[String, Int]()

    val set = new mutable.HashSet[String]()

    set.add(r)
    set.add(v)
    map(r) = 0
    map(v) = 0

    for (i <- 1 to n) {
      val Array(v, r) = s.nextLine().split(" ")
      a(i-1) = v
      map(r) = i
      set += v
      set += r
    }

    for (i <- 0 until n) {
      map.remove(a(i))
      set.remove(a(i))

      if (i >0) {
        var min = n
        var name = ""
        set.foreach(f => {
          val l = map.getOrElse(f, 0)
          if (l < min) {
            min = l
            name = f
          }
        })

        out.println(s"${a(i)} $name")
      }
    }

    val i = set.iterator

    out.println(s"${i.next()} ${i.next()}")
  }
}

import collection.mutable.ListBuffer

object Serial {
  def main(args : Array[String]) {
    var ans = new ListBuffer[String]
    val tok = io.StdIn.readLine.split(" ")
    var a = tok(0)
    var b = tok(1)
    val n = io.StdIn.readLine.toInt
    ans.append(a)
    ans.append(b)
    for (i<-1 to n) {
      val tok = io.StdIn.readLine.split(" ")
      if (tok(0) == a) a = tok(1)
      else b = tok(1)
      ans.append(a)
      ans.append(b)
    }
    for (i<-0 to n) {
      println(ans(i*2).toString + " " +  ans(i*2 + 1).toString)
    }
  }
}

import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._

object _776A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val init = read[Seq, String](2)
    val replaces = read[Seq[(String, String)]]

    val ans = replaces.scanLeft(init) {
      case (curr, (from, to)) =>
        curr map {
          case `from` => to
          case x => x
        }
    }

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

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

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

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

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

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

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

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

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

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


//package codeforces.contest1102

object DoorsBreakingAndRepairing {
  def main(args: Array[String]): Unit = {
    val Array(n, x, y), seq = io.StdIn.readLine.split(" ").map(_.toInt)

    if (x > y) println(seq.length)
    else println((seq.count(_ <= x) + 1) / 2)

  }
}

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

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

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

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

  def solve(): Unit = {
    val N, X, Y = ni()
    val A = na(N)
    if (X > Y) {
      out.println(N)
    } else {
      val b = A.count(_ <= X)
      val ans = b / 2 + b % 2
      out.println(ans)
    }
  }

  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 CF_531_3_C {

  type In  = (Int, Int, Int, Seq[Int])
  type Out = Int

  def solve(in: In): Out = {
    val (n, break, repair, as) = in

    if (break > repair) as.length
    else math.ceil(as.count(_ <= break)/2.0).toInt
  }
//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int, i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object CF_531_3_C {

  type In  = (Int, Int, Int, Seq[Int])
  type Out = Int

  def solve(in: In): Out = {
    val (n, break, repair, as) = in

    if (break > repair) as.length
    else divideCeil(as.count(_ <= break), 2)
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int, i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}