You are given an array $$$a$$$ of $$$n$$$ points in $$$k$$$-dimensional space. Let the distance between two points $$$a_x$$$ and $$$a_y$$$ be $$$\sum \limits_{i = 1}^{k} |a_{x, i} - a_{y, i}|$$$ (it is also known as Manhattan distance).You have to process $$$q$$$ queries of the following two types: $$$1$$$ $$$i$$$ $$$b_1$$$ $$$b_2$$$ ... $$$b_k$$$ — set $$$i$$$-th element of $$$a$$$ to the point $$$(b_1, b_2, \dots, b_k)$$$; $$$2$$$ $$$l$$$ $$$r$$$ — find the maximum distance between two points $$$a_i$$$ and $$$a_j$$$, where $$$l \le i, j \le r$$$.

The first line contains two numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le 5$$$) — the number of elements in $$$a$$$ and the number of dimensions of the space, respectively. Then $$$n$$$ lines follow, each containing $$$k$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, k}$$$ ($$$-10^6 \le a_{i, j} \le 10^6$$$) — the coordinates of $$$i$$$-th point. The next line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, each denoting a query. There are two types of queries:  $$$1$$$ $$$i$$$ $$$b_1$$$ $$$b_2$$$ ... $$$b_k$$$ ($$$1 \le i \le n$$$, $$$-10^6 \le b_j \le 10^6$$$) — set $$$i$$$-th element of $$$a$$$ to the point $$$(b_1, b_2, \dots, b_k)$$$; $$$2$$$ $$$l$$$ $$$r$$$ ($$$1 \le l \le r \le n$$$) — find the maximum distance between two points $$$a_i$$$ and $$$a_j$$$, where $$$l \le i, j \le r$$$. There is at least one query of the second type.

Print the answer for each query of the second type.

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

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


The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.

The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second.

Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road.  Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if  holds.

NoteIn the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds.

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

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


Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi essays. He can raise the exam grade multiple times.What is the minimum number of essays that Vanya needs to write to get scholarship?

The first line contains three integers n, r, avg (1 ≤ n ≤ 105, 1 ≤ r ≤ 109, 1 ≤ avg ≤ min(r, 106)) — the number of exams, the maximum grade and the required grade point average, respectively. Each of the following n lines contains space-separated integers ai and bi (1 ≤ ai ≤ r, 1 ≤ bi ≤ 106).

In the first line print the minimum number of essays.

NoteIn the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.

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


Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, ..., an / k and b1, b2, ..., bn / k. Let's split the phone number into blocks of length k. The first block will be formed by digits from the phone number that are on positions 1, 2,..., k, the second block will be formed by digits from the phone number that are on positions k + 1, k + 2, ..., 2·k and so on. Pasha considers a phone number good, if the i-th block doesn't start from the digit bi and is divisible by ai if represented as an integer. To represent the block of length k as an integer, let's write it out as a sequence c1, c2,...,ck. Then the integer is calculated as the result of the expression c1·10k - 1 + c2·10k - 2 + ... + ck.Pasha asks you to calculate the number of good phone numbers of length n, for the given k, ai and bi. As this number can be too big, print it modulo 109 + 7.

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ min(n, 9)) — the length of all phone numbers and the length of each block, respectively. It is guaranteed that n is divisible by k. The second line of the input contains n / k space-separated positive integers — sequence a1, a2, ..., an / k (1 ≤ ai < 10k). The third line of the input contains n / k space-separated positive integers — sequence b1, b2, ..., bn / k (0 ≤ bi ≤ 9).

Print a single integer — the number of good phone numbers of length n modulo 109 + 7.

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


Vova plans to go to the conference by train. Initially, the train is at the point $$$1$$$ and the destination point of the path is the point $$$L$$$. The speed of the train is $$$1$$$ length unit per minute (i.e. at the first minute the train is at the point $$$1$$$, at the second minute — at the point $$$2$$$ and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by $$$v$$$ (i.e. the first lantern is at the point $$$v$$$, the second is at the point $$$2v$$$ and so on).There is also exactly one standing train which occupies all the points from $$$l$$$ to $$$r$$$ inclusive.Vova can see the lantern at the point $$$p$$$ if $$$p$$$ is divisible by $$$v$$$ and there is no standing train at this position ($$$p \not\in [l; r]$$$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $$$t$$$ different conferences, so you should answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of queries. Then $$$t$$$ lines follow. The $$$i$$$-th line contains four integers $$$L_i, v_i, l_i, r_i$$$ ($$$1 \le L, v \le 10^9$$$, $$$1 \le l \le r \le L$$$) — destination point of the $$$i$$$-th path, the period of the lantern appearance and the segment occupied by the standing train.

Print $$$t$$$ lines. The $$$i$$$-th line should contain one integer — the answer for the $$$i$$$-th query.

NoteFor the first example query, the answer is $$$3$$$. There are lanterns at positions $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$ and $$$10$$$, but Vova didn't see the lanterns at positions $$$4$$$ and $$$6$$$ because of the standing train.For the second example query, the answer is $$$0$$$ because the only lantern is at the point $$$51$$$ and there is also a standing train at this point.For the third example query, the answer is $$$1134$$$ because there are $$$1234$$$ lanterns, but Vova didn't see the lanterns from the position $$$100$$$ to the position $$$199$$$ inclusive.For the fourth example query, the answer is $$$0$$$ because the standing train covers the whole path.

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


Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $$$100^{500}$$$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $$$i$$$-th attack is performed at the beginning of the $$$a_i$$$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $$$1$$$ damage during each of the next $$$k$$$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).For example, suppose $$$k = 4$$$, and Monocarp stabs the dragon during the seconds $$$2$$$, $$$4$$$ and $$$10$$$. Then the poison effect is applied at the start of the $$$2$$$-nd second and deals $$$1$$$ damage during the $$$2$$$-nd and $$$3$$$-rd seconds; then, at the beginning of the $$$4$$$-th second, the poison effect is reapplied, so it deals exactly $$$1$$$ damage during the seconds $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$; then, during the $$$10$$$-th second, the poison effect is applied again, and it deals $$$1$$$ damage during the seconds $$$10$$$, $$$11$$$, $$$12$$$ and $$$13$$$. In total, the dragon receives $$$10$$$ damage.Monocarp knows that the dragon has $$$h$$$ hit points, and if he deals at least $$$h$$$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $$$k$$$ (the number of seconds the poison effect lasts) that is enough to deal at least $$$h$$$ damage to the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$h$$$ ($$$1 \le n \le 100; 1 \le h \le 10^{18}$$$) — the number of Monocarp's attacks and the amount of damage that needs to be dealt. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9; a_i < a_{i + 1}$$$), where $$$a_i$$$ is the second when the $$$i$$$-th attack is performed.

For each test case, print a single integer — the minimum value of the parameter $$$k$$$, such that Monocarp will cause at least $$$h$$$ damage to the dragon.

NoteIn the first example, for $$$k=3$$$, damage is dealt in seconds $$$[1, 2, 3, 5, 6, 7]$$$.In the second example, for $$$k=4$$$, damage is dealt in seconds $$$[2, 3, 4, 5, 6, 7, 10, 11, 12, 13]$$$.In the third example, for $$$k=1$$$, damage is dealt in seconds $$$[1, 2, 4, 5, 7]$$$.

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

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

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

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

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

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val m = readLong()
        val arr = new Array[Long](n)
        for (i <- 1 to n) {
            arr(i-1) = readLong()
        }
        quickSort(arr)

        def check(kk: Long): Boolean = {
            var dmg = 0L
            for (i <- (0 until n).reverse) {
                if (i == n-1) {
                    dmg += kk
                } else {
                    if (arr(i) + kk < 0)
                        dmg += arr(i+1) - arr(i)
                    else
                        dmg += min(arr(i+1), arr(i)+kk) - arr(i)
                }
            }
            if (dmg >= m)
                return true
            else
                return false
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(st))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(st, mid)
            else
                return bs(mid, en)
        }
        writer.println(bs(1, m))
    }
    writer.flush()
}


Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n × n matrix А: there is a number on the intersection of the і-th row and j-th column that describes the result of the collision of the і-th and the j-th car:    - 1: if this pair of cars never collided.  - 1 occurs only on the main diagonal of the matrix.  0: if no car turned over during the collision.  1: if only the i-th car turned over during the collision.  2: if only the j-th car turned over during the collision.  3: if both cars turned over during the collision. Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?

The first line contains integer n (1 ≤ n ≤ 100) — the number of cars. Each of the next n lines contains n space-separated integers that determine matrix A.  It is guaranteed that on the main diagonal there are  - 1, and  - 1 doesn't appear anywhere else in the matrix. It is guaranteed that the input is correct, that is, if Aij = 1, then Aji = 2, if Aij = 3, then Aji = 3, and if Aij = 0, then Aji = 0.

Print the number of good cars and in the next line print their space-separated indices in the increasing order.

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

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

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


Adilbek was assigned to a special project. For Adilbek it means that he has $$$n$$$ days to run a special program and provide its results. But there is a problem: the program needs to run for $$$d$$$ days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends $$$x$$$ ($$$x$$$ is a non-negative integer) days optimizing the program, he will make the program run in $$$\left\lceil \frac{d}{x + 1} \right\rceil$$$ days ($$$\left\lceil a \right\rceil$$$ is the ceiling function: $$$\left\lceil 2.4 \right\rceil = 3$$$, $$$\left\lceil 2 \right\rceil = 2$$$). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to $$$x + \left\lceil \frac{d}{x + 1} \right\rceil$$$.Will Adilbek be able to provide the generated results in no more than $$$n$$$ days?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. The next $$$T$$$ lines contain test cases – one per line. Each line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le d \le 10^9$$$) — the number of days before the deadline and the number of days the program runs.

Print $$$T$$$ answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in $$$n$$$ days or NO (case insensitive) otherwise.

NoteIn the first test case, Adilbek decides not to optimize the program at all, since $$$d \le n$$$.In the second test case, Adilbek can spend $$$1$$$ day optimizing the program and it will run $$$\left\lceil \frac{5}{2} \right\rceil = 3$$$ days. In total, he will spend $$$4$$$ days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program $$$2$$$ days, it'll still work $$$\left\lceil \frac{11}{2+1} \right\rceil = 4$$$ days.

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