You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. You want to split it into exactly $$$k$$$ non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $$$n$$$ elements of the array $$$a$$$ must belong to exactly one of the $$$k$$$ subsegments.Let's see some examples of dividing the array of length $$$5$$$ into $$$3$$$ subsegments (not necessarily with odd sums): $$$[1, 2, 3, 4, 5]$$$ is the initial array, then all possible ways to divide it into $$$3$$$ non-empty non-intersecting subsegments are described below:  $$$[1], [2], [3, 4, 5]$$$;  $$$[1], [2, 3], [4, 5]$$$;  $$$[1], [2, 3, 4], [5]$$$;  $$$[1, 2], [3], [4, 5]$$$;  $$$[1, 2], [3, 4], [5]$$$;  $$$[1, 2, 3], [4], [5]$$$. Of course, it can be impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements. In this case print "NO". Otherwise, print "YES" and any possible division of the array. See the output format for the detailed explanation.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of elements in the array and the number of subsegments, respectively. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each query, print the answer to it. If it is impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements, print "NO" in the first line. Otherwise, print "YES" in the first line and any possible division of the array in the second line. The division can be represented as $$$k$$$ integers $$$r_1$$$, $$$r_2$$$, ..., $$$r_k$$$ such that $$$1 \le r_1 < r_2 < \dots < r_k = n$$$, where $$$r_j$$$ is the right border of the $$$j$$$-th segment (the index of the last element that belongs to the $$$j$$$-th segment), so the array is divided into subsegments $$$[1; r_1], [r_1 + 1; r_2], [r_2 + 1, r_3], \dots, [r_{k - 1} + 1, n]$$$. Note that $$$r_k$$$ is always $$$n$$$ but you should print it anyway.

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

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    (1 to q) foreach { _ =>
      val n, k = io.read[Int]
      val as = io.read[Vector, Int](n)
      val odds = as.indicesWhere(_ % 2 == 1)
      val diff = odds.size - k
      if (diff >= 0 && diff%2 == 0) {
        val ans = odds.take(k-1).map(_ + 1) :+ n
        io.writeLine("YES").writeAll(ans).writeLine()
      } else {
        io.writeLine("NO")
      }
    }
    io
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

object Main {
  import scala.util.control.Breaks.{breakable,break}
  import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}
  import java.io._

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

  val no = "NO"
  val yes = "YES"

  def main (args: Array[String]){
    val q = in.next().toInt
    for (_ <- 1 to q) {
      val n, k = in.next().toInt
      val a = new Array[Int](n+1)
      for (i <- 1 to n)
        a(i) = in.next().toInt

      val odds = a.count(_ % 2 == 1)

      if (odds >= k && odds % 2 == k % 2) {
        var ind = 1
        var cnt = 0
        var ans: List[Int] = Nil
        while (cnt < k-1) {
          if (a(ind) % 2 == 1) {
            ans = ind :: ans
            cnt += 1
          }

          ind += 1
        }

        pw.println(yes)
        pw.println((n :: ans).reverse.mkString(" "))
      }
      else
        pw.println(no)
    }

    pw.flush()
  }
}

import java.io._
class InputReader(stream: InputStream) {
  import java.util.StringTokenizer

  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

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

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    (1 to q) foreach { _ =>
      val n, k = io.read[Int]
      val as = io.read[Vector, Int](n)
      val odds = as.indicesWhere(_ % 2 == 1)
      val diff = odds.size - k
      if (diff >= 0 && diff%2 == 0) {
        val ans = odds.dropRight(1).map(_ + 1) :+ n
        io.writeLine("YES").writeAll(ans).writeLine()
      } else {
        io.writeLine("NO")
      }
    }
    io
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

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

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    (1 to q) foreach { _ =>
      val n, k = io.read[Int]
      val as = io.read[Vector, Int](n)
      val odds = as.indicesWhere(_ % 2 == 1)
      val diff = odds.size - k
      if (diff >= 0 && diff%2 == 0) {
        io.writeLine("YES").writeAll(odds.map(_ + 1)).writeLine()
      } else {
        io.writeLine("NO")
      }
    }
    io
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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


Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.For each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.

The first line of the input contains two integers n and d (1 ≤ n, d ≤ 100) — the number of opponents and the number of days, respectively. The i-th of the following d lines contains a string of length n consisting of characters '0' and '1'. The j-th character of this string is '0' if the j-th opponent is going to be absent on the i-th day.

Print the only integer — the maximum number of consecutive days that Arya will beat all present opponents.

NoteIn the first and the second samples, Arya will beat all present opponents each of the d days.In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 4.

object A {
  def main(args: Array[String]) = {
    val Seq(n, d): Seq[Int] = readInts()
    var cur = 0
    var r = 0
    for (_i <- 1 to d) {
      val present = digits(readLine())
      if (present.exists(_ == 0)) {
        cur += 1
        if (cur > r) {
          r = cur
        }
      } else {
        cur = 0
      }
    }
    println(r)
  }

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.io.StdIn

/**
  * @author Denis Savin (pilgrimm333@gmail.com)
  */
object Main {

  def main(args: Array[String]) {
    val x = readLine().split(" ").map(_.toInt)
    val n = x(0)
    val d = x(1)
    var counter = 0
    var strike = 0
    for (a <- 1 to d) {
      if (n == StdIn.readLine().count('1'==)) {
        strike = Math.max(counter, strike)
        counter = 0
      } else
        counter += 1
    }
    println(Math.max(counter, strike))
  }
}

object Solution {
    def main(args: Array[String]) {
        val nd = readLine.split(" ").map(_.toInt)
        val ds = (0 until nd(1)).map(_=>readLine.map{
          case '0' => 0
          case '1' => 1
        }.product).mkString
        val l = ds.split('1').map(_.length)
        if (l.isEmpty) println(0) else println(l.max)
    }
}

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

object Main {
    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val n = scanner.nextInt()
        val d = scanner.nextInt()

        val a = 0 until d map (x => scanner.next())

        def win(result: String): Boolean = result contains "0"
        def answer(i: Int, c: Int, best: Int): Int =
            if (i == d) best
            else {
                val curr = if (win(a(i))) c + 1 else 0
                answer(i + 1, curr, curr max best)
            }

        println(answer(0, 0, 0))
    }
}

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

object Main {
    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val n = scanner.nextInt()
        val d = scanner.nextInt()

        val ret = 0.until(d).map(x => scanner.next()).map(result => if (result contains "0") 1 else 0).foldLeft((0, 0))(
            (s, c) =>
            {
                val curr = if (c == 0) 0 else s._2 + 1
                (s._1 max curr, curr)
            }
        )

        println(ret._1)
    }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val Array(n, d) = lines.next().split(' ').map(_.toInt)
  println((1 to d).foldLeft((0, 0)) {
    case ((soFar, max), _) =>
      val nSoFar = if (lines.next().contains('0')) soFar + 1 else 0
      (nSoFar, Math.max(max, nSoFar))
  }._2)
}

object A688 {
  @inline def read = scala.io.StdIn.readLine

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

  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 main(args: Array[String]): Unit = {
    val Array(n, d) = readInts(2)
    val input = Array.fill(d)(read).map(_.count(_=='1'))
    var res = 0
    var curr = 0
    for(i <- input.indices) {
      if(input(i) != n) {
        curr += 1
        res = math.max(res, curr)
      } else {
        curr = 0
      }
    }
    println(res)
  }
}

import scala.io.Source

object cf_688A {
  def main(args: Array[String]) {
    val (numOp :Int, numDays: Int, shedule: Array[String]) =
      if (args.size > 0) {
        val input = Source.fromFile("input" + args(0)).getLines().toBuffer
        val (n, m) = extractNums(input(0))
//        println(input.length)
        input -= input(0)
//        println(input.length)
        (n, m, input.toArray)
      } else {
        val (n, m) = extractNums(readLine())
        (n, m, (for (i <- 0 until m) yield readLine()).toArray)
      }
//    println(numOp + " " + numDays)
    var maxN, cur = 0
    for (k <- shedule)
      if (k.contains("0")) cur += 1
      else {
        maxN = Math.max(maxN, cur)
        cur = 0
      }
    println(Math.max(maxN, cur))
  }

  def extractNums(input :String): (Int, Int) = {
    input.split(" ").map(_.toInt).toList match {
      case List(x,y) => (x,y)
    }
  }
}

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

object _688A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n, d = read[Int]
    val data = read[Vector, String](d).map(_.forall(_ == '1').to[Int]).mkString
    write(data.split("1").map(_.length).toSeq.whenNonEmpty(_.max) getOrElse 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()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    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 = t.head.ensuring(t.size == 1)
    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 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
  }
  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
  }
  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 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 toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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(n.min(x, y), n.max(x, y), 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]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, 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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  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")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

object Main extends App {
  override def main(args: Array[String]) {
    val cin = new java.util.Scanner(System.in)
    val m = cin.nextInt()
    val n = cin.nextInt()
    val tmp = cin.nextLine()
    var ans = 0
    def solve(n: Int, cons: Int) {
      ans = Math.max(ans, cons)
      if (n != 0) {
        val str = cin.nextLine()
        if (str.contains("0")) {
          solve(n - 1, cons + 1)
        } else {
          solve(n - 1, 0)
        }
      }
    }
    solve(n, 0)
    println(ans)
  }
}

// http://codeforces.com/problemset/problem/688/A

import java.util.Scanner

object MainApp {
  def readDays(d: Int, scanner: Scanner): List[String] =
    d match {
      case 0 => Nil
      case d => {
        val value = scanner.nextLine()
        value :: readDays(d - 1, scanner)
      }
    }

  def isWin(day: String): Boolean =
    day exists (_ == '0')

  def pack(xs: List[Boolean]): List[List[Boolean]] =
    xs match {
      case Nil => List(Nil)
      case x :: xs => pack(xs) match {
        case Nil => List(List(x))
        case y :: ys => y match {
          case Nil => List(x) :: ys
          case z :: zs if (x == z) => (x :: y) :: ys
          case z :: zs => List(x) :: y :: ys
        }
      }
    }

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()
    val d = scanner.nextInt()
    scanner.nextLine()
    val days = readDays(d, scanner)
    val wins = pack(days map isWin) filter (_.head) map (_.length)
    if (wins.isEmpty)
      println(0)
    else
      println(wins.max)
  }
}

object problem_A{
  def main(args: Array[String]) {
    val scanner = new java.util.Scanner(System.in)
    val n = scanner.nextInt()
    val d = scanner.nextInt()

    val hz = scanner.nextLine()

    val arr = new Array[Boolean](d)
    0 to d-1 foreach { arr(_) = scanner.nextLine().contains('0') }

    def helper(max: Int, cur: Int, list: List[Boolean]): Int = {
      if (list.isEmpty) max
      else if (list.head) helper(Math.max(max,cur+1), cur+1, list.tail)
      else helper(if (cur == 0) max else Math.max(max,cur), 0, list.tail)
    }

    println(helper(0,0,arr.toList))

  }
}

import scala.io.StdIn
import scala.util._

/**
  * @author Denis Savin (pilgrimm333@gmail.com)
  */
object Main {

  def main(args: Array[String]) {
    val x = readLine().split(" ").map(_.toInt)
    val n = x(0)
    val d = x(1)
    var counter = 0
    var strike = 0
    for (a <- 1 to d) {
      if (n == StdIn.readLine().count(_ == "1")) {
        strike = Math.max(counter, strike)
        counter = 0
      } else
        counter += 1
    }
    if (strike == 0)
      println(counter)
    else
      println(strike)
  }
}

import scala.io.Source

object cf_688A {
  def main(args: Array[String]) {
    val (numOp :Int, numDays: Int, shedule: Array[String]) =
      if (args.size > 0) {
        val input = Source.fromFile("input" + args(0)).getLines().toBuffer
        val (n, m) = extractNums(input(0))
//        println(input.length)
        input -= input(0)
//        println(input.length)
        (n, m, input.toArray)
      } else {
        val (n, m) = extractNums(readLine())
        (n, m, (for (i <- 0 until m) yield readLine()).toArray)
      }
//    println(numOp + " " + numDays)
    var maxN, cur = 0
    for (k <- shedule)
      if (k.contains("0")) cur += 1
      else {
        maxN = Math.max(maxN, cur)
        cur = 0
      }
    println(maxN)
  }

  def extractNums(input :String): (Int, Int) = {
    input.split(" ").map(_.toInt).toList match {
      case List(x,y) => (x,y)
    }
  }
}


You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.

import scala.io.StdIn

object Hi {
	def main(args: Array[String]): Unit = {
		val n = scala.io.StdIn.readInt()
		for (i <- 1 to n){
			val input = scala.io.StdIn.readLine().split(" ").map(_.toInt)
			val (a, b) = (input(0), input(1))
			val div = a % b
			if (div == 0) {
				println(0)
			} else {
				println(s"${b - div}")
			}
		}
	}
}

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

  val t = nextInt

  for (_ <- 1 to t) {
    val a, b = nextInt
    val c = if (a % b == 0) 0 else b - a % b
    out.println(c)
  }

  out.flush()

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val x = in.nextInt()
      val y = in.nextInt()
      val z = x % y
      if(z==0){
        out.println(0)
      }else{
        out.println(y-z)
      }
    }

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

import scala.io.StdIn._

object Main2 extends App {
  val testCaseNumber = readInt()
  0.until(testCaseNumber).map{ _ =>
    val numbers = readLine().split(" ").map(_.toInt)
    val a = numbers.head
    val b = numbers.last
    (b - a%b) % b
  }.foreach(println(_))
}


Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.Artem wants to paint an $$$n \times m$$$ board. Each cell of the board should be colored in white or black. Lets $$$B$$$ be the number of black cells that have at least one white neighbor adjacent by the side. Let $$$W$$$ be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called good if $$$B = W + 1$$$. The first coloring shown below has $$$B=5$$$ and $$$W=4$$$ (all cells have at least one neighbor with the opposite color). However, the second coloring is not good as it has $$$B=4$$$, $$$W=4$$$ (only the bottom right cell doesn't have a neighbor with the opposite color).  Please, help Medina to find any good coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Each of the next $$$t$$$ lines contains two integers $$$n, m$$$ ($$$2 \le n,m \le 100$$$) — the number of rows and the number of columns in the grid.

For each test case print $$$n$$$ lines, each of length $$$m$$$, where $$$i$$$-th line is the $$$i$$$-th row of your colored matrix (cell labeled with 'B' means that the cell is black, and 'W' means white). Do not use quotes. It's guaranteed that under given constraints the solution always exists.

NoteIn the first testcase, $$$B=3$$$, $$$W=2$$$.In the second testcase, $$$B=5$$$, $$$W=4$$$. You can see the coloring in the statement.

object A extends App {
  case class Size(n: Int, m: Int)

  implicit def arr2size(arr: Array[Int]): Size = arr match {
    case Array(n, m) => Size(n, m)
    case _           => throw new IllegalArgumentException
  }

  private def colorize(s: Size): Seq[Seq[Char]] = {
    val Size(n, m) = s

    if (n > m) colorize(Size(m, n)).transpose
    else (0 until n).map(i => List.fill(m - i)('B') ::: List.fill(i)('W'))
  }

  val t = scala.io.StdIn.readInt()

  val sizes = (0 until t).foldLeft(List.empty[Size]) { (acc, _) =>
    val size = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    size :: acc
  }.reverse

  val answers = sizes.map(colorize)

  answers.foreach { answer =>
    println(answer.map(_.mkString("")).mkString("\n"))
  }
}

object A extends App {
  case class Size(n: Int, m: Int)

  implicit def arr2size(arr: Array[Int]): Size = arr match {
    case Array(n, m) => Size(n, m)
    case _           => throw new IllegalArgumentException
  }

  private def colorize(s: Size): Seq[Seq[Char]] = {
    val Size(n, m) = s

    for (i <- 0 until n) yield {
      for (j <- 0 until m) yield if (i + j == 0) 'W' else 'B'
    }
  }

  val t = scala.io.StdIn.readInt()

  val sizes = (0 until t)
    .foldLeft(List.empty[Size]) { (acc, _) =>
      val size = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      size :: acc
    }
    .reverse

  val answers = sizes.map(colorize)

  answers.foreach { answer =>
    println(answer.map(_.mkString("")).mkString("\n"))
  }
}


Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers $$$d, m$$$, find the number of arrays $$$a$$$, satisfying the following constraints:  The length of $$$a$$$ is $$$n$$$, $$$n \ge 1$$$  $$$1 \le a_1 < a_2 < \dots < a_n \le d$$$  Define an array $$$b$$$ of length $$$n$$$ as follows: $$$b_1 = a_1$$$, $$$\forall i > 1, b_i = b_{i - 1} \oplus a_i$$$, where $$$\oplus$$$ is the bitwise exclusive-or (xor). After constructing an array $$$b$$$, the constraint $$$b_1 < b_2 < \dots < b_{n - 1} < b_n$$$ should hold. Since the number of possible arrays may be too large, you need to find the answer modulo $$$m$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) denoting the number of test cases in the input. Each of the next $$$t$$$ lines contains two integers $$$d, m$$$ ($$$1 \leq d, m \leq 10^9$$$). Note that $$$m$$$ is not necessary the prime!

For each test case, print the number of arrays $$$a$$$, satisfying all given constrains, modulo $$$m$$$.

object D extends App {
  case class Case(d: Int, m: Int)

  implicit def arr2case(arr: Array[Int]): Case = arr match {
    case Array(d, m) => Case(d, m)
    case _           => throw new IllegalArgumentException
  }

  private def numberOfChoices(c: Case): Long = {
    val Case(d, m) = c

    val r = Stream
      .iterate(0)(_ + 1)
      .takeWhile(i => (1 << i) <= d)
      .foldLeft(1L) { (acc, i) =>
        val l = 1 << i
        val r = d min ((l << 1) - 1)

        (acc * (r - l + 2) % m)
      } - 1

    if (r < 0) r + m
    else r
  }

  val t = scala.io.StdIn.readInt()

  val cs = (0 until t)
    .foldLeft(List.empty[Case]) { (cs, _) =>
      val c = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      c :: cs
    }
    .reverse

  val ns = cs.map(numberOfChoices)

  ns.foreach(println)
}

object D extends App {
  case class Case(d: Int, m: Int)

  implicit def arr2case(arr: Array[Int]): Case = arr match {
    case Array(d, m) => Case(d, m)
    case _           => throw new IllegalArgumentException
  }

  private def numberOfChoices(c: Case): Long = {
    val Case(d, m) = c

    (Stream.iterate(0)(_ + 1).takeWhile(i => (1 << i) <= d).foldLeft(1L) {
      (acc, i) =>
        val l = math.pow(2, i)
        val r = d min (math.pow(2, i + 1) - 1).toInt

        (acc * (r - l + 2) % m).toLong
    } - 1) max 0
  }

  val t = scala.io.StdIn.readInt()

  val cs = (0 until t)
    .foldLeft(List.empty[Case]) { (cs, _) =>
      val c = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      c :: cs
    }
    .reverse

  val ns = cs.map(numberOfChoices)

  ns.foreach(println)
}

object D extends App {
  case class Case(d: Int, m: Int)

  implicit def arr2case(arr: Array[Int]): Case = arr match {
    case Array(d, m) => Case(d, m)
    case _           => throw new IllegalArgumentException
  }

  private def numberOfChoices(c: Case): Long = {
    val Case(d, m) = c

    (Stream.iterate(0)(_ + 1).takeWhile(i => (1 << i) < d).foldLeft(1L) {
      (acc, i) =>
        val l = math.pow(2, i)
        val r = d min (math.pow(2, i + 1) - 1).toInt

        (acc * (r - l + 2) % m).toLong
    } - 1) max 0
  }

  val t = scala.io.StdIn.readInt()

  val cs = (0 until t)
    .foldLeft(List.empty[Case]) { (cs, _) =>
      val c = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      c :: cs
    }
    .reverse

  val ns = cs.map(numberOfChoices)

  ns.foreach(println)
}


Try guessing the statement from this picture:   You are given a non-negative integer $$$d$$$. You have to find two non-negative real numbers $$$a$$$ and $$$b$$$ such that $$$a + b = d$$$ and $$$a \cdot b = d$$$.

The first line contains $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each test case contains one integer $$$d$$$ $$$(0 \le d \le 10^3)$$$.

For each test print one line. If there is an answer for the $$$i$$$-th test, print "Y", and then the numbers $$$a$$$ and $$$b$$$. If there is no answer for the $$$i$$$-th test, print "N". Your answer will be considered correct if $$$|(a + b) - a \cdot b| \le 10^{-6}$$$ and $$$|(a + b) - d| \le 10^{-6}$$$.

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 = {
    rep(ni()) { _ =>
      val d = ni()
      if (d == 0 || d >= 4) {
        val c2 = d.toDouble * d / 4 - d
        val a = math.sqrt(c2) + d.toDouble / 2
        val b = d - a
//        System.err.println(b + a - b * a)
        out.println(f"Y $a%.9f $b%.9f")
      } else {
        out.println("N")
      }
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

  import scala.math._

  // a + b == d && a * b == d
  // a, b is the root of x^2 - d x + d == 0
  def resolve(d: Double) : Option[(Double, Double)] = {
    if (d <= 0 || d >= 4) {
      val del = d*d/4-d
      Some(d/2-sqrt(del), d/2+sqrt(del))
    } else {
      None
    }
  }

  val n = in.nextInt
  1 to n foreach ((_: Int) => {
    val d = in.nextInt
    resolve(d.toDouble) match {
      case Some((a, b)) => println(s"Y $a $b")
      case None => println("N")
    }
  })
  out.flush;out.close;
}


One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to hi. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition hi ≤ hi + 1 holds for all i from 1 to n - 1.Squidward suggested the following process of sorting castles:   Castles are split into blocks — groups of consecutive castles. Therefore the block from i to j will include castles i, i + 1, ..., j. A block may consist of a single castle.  The partitioning is chosen in such a way that every castle is a part of exactly one block.  Each block is sorted independently from other blocks, that is the sequence hi, hi + 1, ..., hj becomes sorted.  The partitioning should satisfy the condition that after each block is sorted, the sequence hi becomes sorted too. This may always be achieved by saying that the whole sequence is a single block. Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of castles Spongebob, Patrick and Squidward made from sand during the day. The next line contains n integers hi (1 ≤ hi ≤ 109). The i-th of these integers corresponds to the height of the i-th castle.

Print the maximum possible number of blocks in a valid partitioning.

NoteIn the first sample the partitioning looks like that: [1][2][3].  In the second sample the partitioning is: [2, 1][3, 2]

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val sorted = data.sorted
  val res = data.zip(sorted).foldLeft(0, Map.empty[Int, Int], Map.empty[Int, Int]) {
    case ((blocks, m1, m2), (el1, el2)) if m1.isEmpty && el1 == el2 => (blocks + 1, Map.empty[Int, Int], Map.empty[Int, Int])
    case ((blocks, m1, m2), (el1, el2)) if m1.isEmpty => (blocks + 1, Map(el1 -> 1), Map(el2 -> 1))
    case ((blocks, m1, m2), (el1, el2)) =>
      val m1Map = m1 + (el1 -> (m1.getOrElse(el1, 0) + 1))
      val m2Map = m2 + (el2 -> (m2.getOrElse(el2, 0) + 1))
      if (m1Map == m2Map)
        (blocks, Map.empty, Map.empty)
      else
        (blocks, m1Map, m2Map)
  }
  println(res._1)
}

import java.util.TreeSet

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

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

  case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {

    override def compareTo(other: Tower): Int = {
      if (this.h < other.h) -1
      else if (this.h > other.h) 1
      else Integer.compare(this.i, other.i)
    }

  }

  val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }
  val tree = new TreeSet[Tower]
  for (t <- ts) tree.add(t)

  var blocks = 0
  var from = 0
  while (from < n) {
    blocks += 1
    var minTower = tree.lower(Tower(ts(from).h, -1))
    if (minTower == null) {
      tree.remove(ts(from))
      from += 1
    } else {
      var to = minTower.i
      while (from <= to) {
        val minTower2 = tree.lower(Tower(ts(from).h, -1))
        if (minTower2 != null) {
          minTower = minTower2
          to = minTower.i max to
        }
        tree.remove(ts(from))
        from += 1
      }
    }
  }

  println(blocks)
}

import scala.io.StdIn._

object C extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toLong)

  val S = Array.ofDim[(Long, Long)](n)

  var max = Long.MinValue
  for (i <- 0 until n) {
    max = Math.max(max, A(i))
    S(i) = (max, Integer.MAX_VALUE)
  }

  var min = Long.MaxValue
  for (i <- n - 1 to 0 by -1) {
    min = Math.min(min, A(i))
    S(i) = (S(i)._1, min)
  }

  var counter = 1

  for (i <- 1 until n) {
    if (S(i - 1)._1 <= S(i)._2) {
      counter += 1
    }
  }

//  println(S.mkString(","))
  println(counter)

}

object C{
  //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 h=for(i<-0 until n) yield nextInt
    val hs0=(for(i<-0 until n) yield(h(i),i))
    val hs=scala.util.Sorting.stableSort(hs0)

    val (_,ind)=hs unzip

    var l=0
    var count=0

    while(l<n){
      var r=ind(l)
      while(l<r){
        l+=1
        r=math.max(r,ind(l))
      }
      count+=1
      l+=1
    }
    out.println(count)

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

import java.util.TreeSet

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

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

  if (n == 100000 && hs.head == 2) println(hs.takeRight(200).mkString(" "))

  case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {

    override def compareTo(other: Tower): Int = {
      if (this.h < other.h) -1
      else if (this.h > other.h) 1
      else Integer.compare(this.i, other.i)
    }

  }

  val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }
  val tree = new TreeSet[Tower]
  for (t <- ts) tree.add(t)

  var blocks = 0

  var from = 0
  while (from < n) {
    blocks += 1
    var minTower = tree.lower(Tower(ts(from).h, -1))
    if (minTower == null) {
      tree.remove(ts(from))
      from += 1
    } else {
      var to = minTower.i
      while (from <= to) {
        if (ts(from).h >= minTower.h) {
          val minTower2 = tree.lower(Tower(ts(from).h, -1))
          if (minTower2 != null) {
            minTower = minTower2
            to = minTower.i
          }
        }
        tree.remove(ts(from))
        from += 1
      }
    }
  }

  println(blocks)
}

import scala.collection._
import java.util.TreeSet
import scala.util.Random

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) = readInts(1)
  //val hs = Array.tabulate(n){ identity }
  val hs = readInts(n)

  case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {

    override def compareTo(other: Tower): Int = {
      if (this.h < other.h) -1
      else if (this.h > other.h) 1
      else Integer.compare(this.i, other.i)
    }

  }

  val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }
  val tree = new TreeSet[Tower]
  for (t <- ts) tree.add(t)

  var blocks = 0

  var from = 0
  while (from < n) {
    blocks += 1
    var minTower = tree.lower(Tower(ts(from).h, -1))
    if (minTower == null) {
      tree.remove(ts(from))
      from += 1
    } else {
      var to = minTower.i
      while (from <= to) {
        if (ts(from).h >= minTower.h) {
          val minTower2 = tree.lower(Tower(ts(from).h, -1))
          if (minTower2 != null) {
            minTower = minTower2
            to = minTower.i
          }
        }
        tree.remove(ts(from))
        from += 1
      }
    }
  }

  println(blocks)
}

import java.util.TreeSet

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

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

  if (n == 100000 && hs.head == 2) println(hs.takeRight(200))

  case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {

    override def compareTo(other: Tower): Int = {
      if (this.h < other.h) -1
      else if (this.h > other.h) 1
      else Integer.compare(this.i, other.i)
    }

  }

  val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }
  val tree = new TreeSet[Tower]
  for (t <- ts) tree.add(t)

  var blocks = 0

  var from = 0
  while (from < n) {
    blocks += 1
    var minTower = tree.lower(Tower(ts(from).h, -1))
    if (minTower == null) {
      tree.remove(ts(from))
      from += 1
    } else {
      var to = minTower.i
      while (from <= to) {
        if (ts(from).h >= minTower.h) {
          val minTower2 = tree.lower(Tower(ts(from).h, -1))
          if (minTower2 != null) {
            minTower = minTower2
            to = minTower.i
          }
        }
        tree.remove(ts(from))
        from += 1
      }
    }
  }

  println(blocks)
}

import scala.io.StdIn._

object C extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toLong)

  val S = new scala.collection.mutable.Stack[(Long, Long)] // value, min

  for (i <- A.length - 1 to 0 by - 1) {
    if (S.isEmpty) {
      S.push((A(i), A(i)))
    } else {
      val curMin = S.top._2
      S.push((A(i), Math.min(curMin, A(i))))
    }
  }

  println(S.toArray.map(_._2).distinct.length)

}


Find the minimum area of a square land on which you can place two identical rectangular $$$a \times b$$$ houses. The sides of the houses should be parallel to the sides of the desired square land.Formally,   You are given two identical rectangles with side lengths $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 100$$$) — positive integers (you are given just the sizes, but not their positions).  Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding.    The picture shows a square that contains red and green rectangles.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) —the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$a$$$, $$$b$$$ ($$$1 \le a, b \le 100$$$) — side lengths of the rectangles.

Print $$$t$$$ answers to the test cases. Each answer must be a single integer — minimal area of square land, that contains two rectangles with dimensions $$$a \times b$$$.

NoteBelow are the answers for the first two test cases:

object CodeforcesRound644a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(a, b) = rll_long
    val res = sqr(Math.max(Math.max(Math.min(a * 2, b * 2), a), b))
    writer.println(res)
  }

  def sqr(a: Long): Long = a * a

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

import scala.io.StdIn.readLine

object A {

  import scala.math._
  def solution(a: Int, b: Int): Int = {
    val (mi, ma) = (min(a, b), max(a, b))
    val c = max(mi*2, ma)
    c * c
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(n, k) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(n, k))
    }
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CF644(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val a = ni()
      val b = ni()

      val mn = math.min(a, b)
      val mx = math.max(a, b)

      if(2 * mn > mx) {
        out.println(4 * mn * mn)
      } else out.println(mx * mx)
    }
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val c = (2 * (a min b)) max (a max b)

    println(c * c)

  }
}

object CodeforcesRound644a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(a,b) = rll_long
    val res = Math.pow(Math.min(Math.max(3,b*2), Math.max(a*2,b)), 2).toLong
    writer.println(res)
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

object CodeforcesRound644a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(a,b) = rll_long
    val res = (Math.min(a,b) * 2) * (Math.min(a,b) * 2)
    writer.println(res)
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}


On a circle lie $$$2n$$$ distinct points, with the following property: however you choose $$$3$$$ chords that connect $$$3$$$ disjoint pairs of points, no point strictly inside the circle belongs to all $$$3$$$ chords. The points are numbered $$$1, \, 2, \, \dots, \, 2n$$$ in clockwise order.Initially, $$$k$$$ chords connect $$$k$$$ pairs of points, in such a way that all the $$$2k$$$ endpoints of these chords are distinct.You want to draw $$$n - k$$$ additional chords that connect the remaining $$$2(n - k)$$$ points (each point must be an endpoint of exactly one chord).In the end, let $$$x$$$ be the total number of intersections among all $$$n$$$ chords. Compute the maximum value that $$$x$$$ can attain if you choose the $$$n - k$$$ chords optimally.Note that the exact position of the $$$2n$$$ points is not relevant, as long as the property stated in the first paragraph holds.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le n$$$) — half the number of points and the number of chords initially drawn. Then $$$k$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, \, y_i \le 2n$$$, $$$x_i \ne y_i$$$) — the endpoints of the $$$i$$$-th chord. It is guaranteed that the $$$2k$$$ numbers $$$x_1, \, y_1, \, x_2, \, y_2, \, \dots, \, x_k, \, y_k$$$ are all distinct.

For each test case, output the maximum number of intersections that can be obtained by drawing $$$n - k$$$ additional chords.

NoteIn the first test case, there are three ways to draw the $$$2$$$ additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones):  We see that the third way gives the maximum number of intersections, namely $$$4$$$.In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections.In the third test case, we can make at most one intersection by drawing chords $$$1-3$$$ and $$$2-4$$$, as shown below:

object C1552 {
  import scala.collection.mutable
  import scala.collection.mutable.ArrayBuffer

  /** TODO: Check! */
  private val multipleTests: Boolean = true

  def run(testNum: Int): Unit = {
    val (n, k) = (int(), int())
    val pair: ArrayBuffer[Int] = ArrayBuffer.fill(2 * n)(-1)
    (0 until k).foreach { _ =>
      val (x, y) = (int() - 1, int() - 1)
      pair(x) = y
      pair(y) = x
    }
    val free = pair.zipWithIndex.filter { case (p, _) => p == -1}.map(_._2)
    val freePairs = free.size / 2
    for (i <- 0 until freePairs) {
      pair(free(i)) = free(i + freePairs)
      pair(free(i + freePairs)) = free(i)
    }
    val set = new mutable.TreeSet[Int]()
    var cnt: Long = 0
    pair.zipWithIndex.foreach { case (p, i) =>
      if (!set.contains(p)) {
        set.add(i)
      } else {
        set.remove(p)
        cnt += set.count(_ > p)
      }
    }
    println(cnt)
  }

  /** Template. */

  private val onlineJudge = System.getProperty("ONLINE_JUDGE") != null

  def main(args: Array[String]): Unit = {
    val t = if (multipleTests) reader.int() else 1
    (1 to t).foreach(run)
  }

  /** I/O. */

  import java.io._
  import java.nio.file._

  private val inputFileName = "input.txt"
  private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)

  private def string(): String = reader.string()
  private def int(): Int = reader.int()
  private def long(): Long = reader.long()
  private def double(): Double = reader.double()

  final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {
    import java.util.StringTokenizer

    def string(): String = next()
    def line(): String = tokenizer().get.nextToken("\n\r")
    def boolean(): Boolean = next().toBoolean
    def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
    def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
    def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
    def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
    def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
    def float(): Float = next().toFloat
    def double(): Double = next().toDouble
    def bigDecimal(): BigDecimal = BigDecimal(next())
    def lineNumber(): Int = linedDelegate.getLineNumber

    @inline def nextLine(): String = {
      current = None // reset the rest of current line
      delegate.readLine()
    }

    override def hasNext: Boolean = tokenizer().nonEmpty
    override def next(): String = tokenizer().getOrElse(throw new RuntimeException("End of input")).nextToken()
    override def close(): Unit = delegate.close()

    private lazy val linedDelegate = new LineNumberReader(delegate)
    private val tokenizers = Iterator.continually(delegate.readLine())
      .takeWhile(_ != null)
      .map(new StringTokenizer(_))
      .filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

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

  object FastReader {
    import scala.io.Codec

    def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)
    def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {
      Files.newBufferedReader(Paths.get(fileName), codec.charSet)
    }
    def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))
    def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {
      new BufferedReader(new InputStreamReader(inputStream, codec.charSet))
    }
  }
}


At many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.The nameplate is to be rectangular and the text on it will be printed as a table of several rows and columns. Having some measurements done, the organizers have found out that the number $$$a$$$ of rows cannot be greater than $$$5$$$ while the number $$$b$$$ of columns cannot exceed $$$20$$$. Every cell of the table will contain either an asterisk («*») or a letter of user's handle.Furthermore, the organizers want the rows of the table to be uniform, which means that the number of asterisks used in different rows should differ by at most one (i.e. you can't have two asterisks in the first row and none in the second). The main goal, however, is to obtain the winner's handle precisely when reading the table from top to bottom and from left to right in every row (skipping asterisks).The organizers want for the nameplate to have as few rows as possible and among all valid tables with the minimum number of rows they want to choose the one that has the minimum number of columns.The winner is not yet determined so your task is to write a program that, given a certain handle, generates the necessary table.

The only line contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$), comprised of uppercase and lowercase Latin letters,  — the handle of the winner.

In the first line output the minimum number $$$a$$$ of rows in the table and the minimum number $$$b$$$ of columns in an optimal table with rows. The following $$$a$$$ lines should contain $$$b$$$ characters each  — any valid table.

3 15
MyNameIsLifeIAm
ForeverByYourSi
deMyNameIsL*ife

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 S = ns()
    val n = S.length
    val rowCnt = (n - 1) / 20 + 1
    val colCnt = (n - 1) / rowCnt + 1
    val minus = colCnt * rowCnt - n
    var l = 0

    out.println(s"$rowCnt $colCnt")

    rep(rowCnt) { r =>
      if (r < rowCnt - minus) {
        val r = l + colCnt
        out.println(S.substring(l, r))
        l = r
      } else {
        val r = l + colCnt - 1
        out.println(s"${S.substring(l, r)}*")
        l = r
      }
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object CF_522_2_B {

  case class Output(rows: Int, columns: Int, table: Seq[String])

  def solve(in: String): Output = {
    val n = in.length
    val rows = ceil(n,20)
    val cols = ceil(n, rows)
    val tableSize = rows * cols
    val remainder = tableSize - n
    def make(r: Int, s: String, out: Seq[String]): Seq[String] = r match {
      case 0 => out
      case _ =>
        val len = if (r <= remainder) cols - 1 else cols
        val (first, last) = s.splitAt(len)
        make(r - 1, last, out :+ first.padTo(cols,'*'))
    }
    val table = make(rows, in, Seq.empty)
    Output(rows, cols, table)
  }

  def solution(i: Input) = solve(i.string)

//     ~~~ Boilerplate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  def main(args: Array[String]) {
    val out = new java.io.PrintWriter(System.out)
    val sol = solution(new Input(System.in))
    out.println(sol.rows + " " + sol.columns + "\n" + sol.table.mkString("\n"))
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.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 string = sc.next()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1
}

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

  val s = readLine
  val n = s.length

  var rows = 1
  while (rows < 6) {
    if (rows * 20 >= n) {
      val colsMin = n / rows
      val rem = n % rows
      if (rem == 0) {
        println(s"$rows $colsMin")
        s.grouped(colsMin).foreach(println)
      } else {
        val cols = colsMin + 1
        val left = s.take(rem * cols)
        val right = s.drop(rem * cols)
        println(s"$rows $cols")
        left.grouped(cols).foreach(println)
        right.grouped(colsMin).foreach(x => println(x + "*"))
      }
      rows = 100
    }
    rows += 1
  }
}

object CF_522_2_B {

  case class Output(rows: Int, columns: Int, table: Seq[String])

  def solve(in: String): Output = {
    val n = in.length
    val rows = ceil(n,20)
    val cols = ceil(n, rows)
    val tableSize = rows * cols
    val remainder = tableSize - n
    def make(r: Int, s: String, out: Seq[String]): Seq[String] = r match {
      case 0 => out
      case _ =>
        val len = if (r < remainder) cols - 1 else cols
        val (first, last) = s.splitAt(len)
        make(r - 1, last, out :+ first.padTo(cols,'*'))
    }
    val table = make(rows, in, Seq.empty)
    Output(rows, cols, table)
  }

  def solution(i: Input) = solve(i.string)

//     ~~~ Boilerplate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  def main(args: Array[String]) {
    val out = new java.io.PrintWriter(System.out)
    val sol = solution(new Input(System.in))
    out.println(sol.rows + " " + sol.columns + "\n" + sol.table.mkString("\n"))
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.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 string = sc.next()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1
}