There are $$$n$$$ candies in a row, they are numbered from left to right from $$$1$$$ to $$$n$$$. The size of the $$$i$$$-th candy is $$$a_i$$$.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).Alice makes the first move. During the first move, she will eat $$$1$$$ candy (its size is $$$a_1$$$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if $$$n=11$$$ and $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, then:  move 1: Alice eats one candy of size $$$3$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3,5]$$$.  move 2: Alice ate $$$3$$$ on the previous move, which means Bob must eat $$$4$$$ or more. Bob eats one candy of size $$$5$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3]$$$.  move 3: Bob ate $$$5$$$ on the previous move, which means Alice must eat $$$6$$$ or more. Alice eats three candies with the total size of $$$1+4+1=6$$$ and the sequence of candies becomes $$$[5,9,2,6,5,3]$$$.  move 4: Alice ate $$$6$$$ on the previous move, which means Bob must eat $$$7$$$ or more. Bob eats two candies with the total size of $$$3+5=8$$$ and the sequence of candies becomes $$$[5,9,2,6]$$$.  move 5: Bob ate $$$8$$$ on the previous move, which means Alice must eat $$$9$$$ or more. Alice eats two candies with the total size of $$$5+9=14$$$ and the sequence of candies becomes $$$[2,6]$$$.  move 6 (the last): Alice ate $$$14$$$ on the previous move, which means Bob must eat $$$15$$$ or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers:  $$$a$$$ — the total size of all sweets eaten by Alice during the game;  $$$b$$$ — the total size of all sweets eaten by Bob during the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases in the input. The following are descriptions of the $$$t$$$ test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of candies. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of $$$n$$$ for all sets of input data in a test does not exceed $$$2\cdot10^5$$$.

For each set of input data print three integers — the number of moves in the game and the required values $$$a$$$ and $$$b$$$.

import scala.io.StdIn

object Test extends App {

  val s = StdIn.readLine().toInt
  (1 to s).foreach{_ =>
    StdIn.readLine()
    var arr = StdIn.readLine().split(" ").map(_.toInt)
    var i = 0
    var j = arr.length - 1
    var alice = 0
    var bob = 0
    alice = arr(i)
    i = 1
    var bob1 = true
    var counter = 1
    var beforeA = alice
    var beforeB = 0
    while (i <= j){
      counter = counter + 1
      if(bob1){
        var bob2 = 0
        while (bob2 <= beforeA && i <= j){
          bob2 = bob2 + arr(j)
          j = j - 1
        }
        beforeB = bob2
        bob = bob + bob2
        bob1 = false
      }else{
        var al2 = 0
        while (al2 <= beforeB && i <= j){
          al2 = al2 + arr(i)
          i = i +1
        }
        beforeA = al2
        alice = alice + al2
        bob1 = true
      }
    }
    println(s"$counter $alice $bob")

  }
}

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 C640B(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 C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

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

      var l = 0
      var h = n-1
      var switch = 0
      var prev = 0
      val ret = Array.fill[Int](2)(0)
      var cnt = 0
      while(l <= h) {
        var curr = 0
        while (curr <= prev && l <= h) {
          if(switch == 0) {curr += a(l); l += 1}
          else { curr += a(h); h -=1 }
        }
        ret(switch) += curr
        switch ^= 1
        prev = curr
        cnt += 1
      }
      out.println(s"$cnt ${ret(0)} ${ret(1)}")
    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val candies = io.read[Vector[Int]]

    @tailrec
    def solve(isAlice: Boolean, prev: Int, left: Int, right: Int, alice: Int, bob: Int, moves: Int): Seq[Int] = {
      val range = if (isAlice) left + 1 until right else right-1 until left by -1
      if (range.nonEmpty) {
        var sum, count = 0
        range.takeWhile({i =>
          count += 1
          sum += candies(i)
          sum <= prev
        })
        solve(
          isAlice = !isAlice,
          prev = sum,
          left = if (isAlice) left + count else left,
          right = if (!isAlice) right - count else right,
          alice = if (isAlice) alice + sum else alice,
          bob = if (!isAlice) bob + sum else bob,
          moves = moves + 1
        )
      } else {
        Seq(moves, alice, bob)
      }
    }

    val ans = solve(isAlice = true, prev = 0, left = -1, right = candies.length, alice = 0, bob = 0, moves = 0)

    io.writeAll(ans)
  }

}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

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

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

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

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

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

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

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

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

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

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

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

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

object ProblemD extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (i <- 1 to t) {
    val n = in.nextInt()
    val inArr = new Array[Int](n)
    for (j <- 0 until n) {
      inArr(j) = in.nextInt()
    }

    var aliceSum = inArr(0)
    var bobSum = 0
    var bobPrev = 0
    var prevAlliceSum = aliceSum
    var aliceTurn = false

    var left = 1
    var right = n - 1
    var count = 1

    while (left <= right) {
      count = count + 1
      if (aliceTurn) {
        var currentSum = 0
        while (currentSum <= bobPrev && left <= right) {
          currentSum = currentSum + inArr(left)
          left = left + 1
        }
        prevAlliceSum = currentSum
        aliceSum = aliceSum + currentSum
      } else {
        var currentSum = 0
        while (currentSum <= prevAlliceSum && left <= right) {
          currentSum = currentSum + inArr(right)
          right = right - 1
        }

        bobSum = bobSum + currentSum
        bobPrev = currentSum
      }
      aliceTurn = !aliceTurn
    }

    println(s"$count $aliceSum $bobSum")
  }

}


Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters.

The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times.

Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val Array(a, d) = in.next().split(" ").map(_.toDouble)
  val n = in.next().toInt
//  val distance = n * d + 0.5
  var count = 1
  val res: Array[String] = Array.ofDim(n)
  while (count <= n) {
    val distance = count * d
    val side = Math.floor(distance / a).toLong % 4
    val rel_distance = distance -  Math.floor(distance / a).toLong * a
    val y = if (side < 1)
      0
    else if (side < 2)
      rel_distance
    else if (side < 3)
      a
    else a - rel_distance
    val x =
      if (side < 1)
        rel_distance
      else if (side < 2)
        a
      else if (side < 3)
        a - rel_distance
      else
        0
    res(count - 1) = s"$x $y"
    count += 1
  }
  println(res.mkString("\n"))

}


The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.

The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 105) — the number of IP addresses and networks. The next n lines contain the IP addresses. It is guaranteed that all IP addresses are distinct.

In a single line print the IP address of the subnet mask in the format that is described in the statement, if the required subnet mask exists. Otherwise, print -1.

import collection.mutable

object C {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(x => x.toInt)
    var a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = readLine().split("\\.").map(x => x.toInt).fold(0)((x, y) => x * 256 + y)
    }
    val masks = 1 until 32 map {x => -1 << (32 - x)}
    var ans = 0
    for (r <- masks) {
      var d = new mutable.HashSet[Int]
      for (x <- a) {
        val v = x & r
        d add v
      }
      if (d.size == k && ans == 0) {
        ans = r
      }
    }
    if (ans == 0) {
      println(-1)
    } else {
      val res = (0 until 4).map(x => (ans >> (24 - 8 * x)) & 255).fold("")((x, y) => if (x == "") y else x + "." + y)
      println(res)
    }
  }
}

/*
C. Маска подсети
ограничение по времени на тест
4 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

В задаче используется упрощенная модель адресов в TCP/IP, внимательно прочтите условие.

Поликарп устроился на работу системным администратором. Как-то раз к нему в руки попали n IP-адресов. Каждый IP-адрес — это 32-битное число, представленное в виде четверки десятичных 8-битных чисел (без лидирующих нулей), записанных через точку. Например, запись 0.255.1.123 обозначает корректный IP-адрес, а записи 0.256.1.123 и 0.255.1.01 — нет. В данной задаче произвольная четверка 8-битных чисел является корректным IP-адресом.

Поработав администратором, Поликарп узнал, что, зная IP-адрес, можно, используя маску подсети, получить адрес сети, которой принадлежит этот IP-адрес.

Маска подсети — это IP-адрес, обладающий следующим свойством: если записать этот IP-адрес, как 32-битную строку, то он представим в виде «11...11000..000». Другими словами, в маске подсети сначала идет один или более единичный бит, а затем один или более нулевой бит (всего битов 32). Например, IP-адрес 2.0.0.0 не является корректной маской подсети, так как его 32-битная запись имеет вид 00000010000000000000000000000000.

Для получения адреса сети IP-адреса нужно выполнить операцию побитового «и» («and») IP-адреса и маски подсети. Например, если маска подсети 255.192.0.0, а IP-адрес 192.168.1.2, то адрес сети равен 192.128.0.0. При побитовом «и» в записи результата бит равен 1 тогда и только тогда, когда у обоих операндов соответствующие биты единичные.

Теперь Поликарп хочет найти все сети, которым принадлежат его IP-адреса. К сожалению, Поликарп потерял маску подсети. К счастью, Поликарп запомнил, что его IP-адреса принадлежали ровно k различным сетям. Помогите Поликарпу найти маску подсети, такую, что его IP-адреса будут принадлежать ровно k различным сетям. Если таких масок несколько, найдите ту, в битовой записи которой наименьшее количество единиц. Если таких масок не существует, сообщите об этом.
Входные данные

В первой строке записаны два целых числа n и k (1 ≤ k ≤ n ≤ 105) — количество IP-адресов и сетей. В следующих n строках записаны сами IP-адреса. Гарантируется, что все IP-адреса различны.
Выходные данные

В единственной строке выведите IP-адрес маски подсети, в формате описанном в условии, если требуемая маска подсети существует. Иначе выведите -1.
Примеры тестов
Входные данные

5 3
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3

Выходные данные

255.255.254.0

Входные данные

5 2
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3

Выходные данные

255.255.0.0

Входные данные

2 1
255.0.0.1
0.0.0.2

Выходные данные

-1
*/
import scala.collection.immutable.BitSet
import scala.collection.mutable.MutableList
import scala.collection.mutable.HashSet

object Task3 extends App {

  def masks: IndexedSeq[Long] = {
    val init = 0xFFFFFFFFL
    var z = init
    val res = init +: (for (p <- 0 until 31) yield {
      z -= math.pow(2, p).toLong
      z
    })
    res.reverse
  }

  def toBits(ip: String): Long = {
    def parts = ip.trim split '.'
    require(parts.size == 4)
    val res = parts.foldLeft(0L)((acc, part) => acc * 256 + (part.toInt))
    res
  }

  def toStr(ip: Option[Long]): String = ip match {
    case None => "-1"
    case Some(l) => {
      val seg1 = (l & 0xFF000000L) >> 24
      val seg2 = (l & 0x00FF0000L) >> 16
      val seg3 = (l & 0x0000FF00L) >> 8
      val seg4 = (l & 0x000000FFL)
      seg1 + "." + seg2 + "." + seg3 + "." + seg4
    }
  }

  def applyMask(mask: Long, ips: Seq[Long]): Seq[Long] = {
    val set = new HashSet[Long]
    ips map (ip => set += (ip & mask))
    set.toSeq
  }

  def distinctByNFirstBits(n: Int, ips: Seq[Long]): Int = {
    val t = ips map (_ >> (32 - n))
    t.distinct.size
  }

  def nFirstBits(n: Int): Long = masks(n - 1)

  def solveStr(k: Int, ipStrs: Seq[String]): String =
    toStr(solve(k, ipStrs map toBits))

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(k: Int, ips: Seq[Long]): Option[Long] =
    if (k > ips.size) None
    //    else masks.find(mask => applyMask(mask, ips).size == k)
    else (1 to 31) find (n => distinctByNFirstBits(n, ips) == k) map nFirstBits

  /*
  def bitStream(ones: Int): Stream[Long] = generateBits(0, 32, ones)

  def generateBits(curr: Long, remaining: Int, remainingOnes: Int): Stream[Long] = {
    val shifted = (curr << 1)
    if (remaining == 0) {
      assert(remainingOnes == 0)
      curr #:: Stream.empty
    } else if (remainingOnes == remaining) {
      generateBits(shifted + 1, remaining - 1, remainingOnes - 1)
    } else if (remainingOnes >= 1) {
      val v1 = generateBits(shifted + 1, remaining - 1, remainingOnes - 1)
      val v2 = generateBits(shifted + 0, remaining - 1, remainingOnes)
      Stream.concat(v1, v2)
    } else {
      generateBits(shifted, remaining - 1, remainingOnes)
    }
  }
*/
  val (n, k) = {
    val l = readLine split (' ') map (_.toInt)
    (l(0), l(1))
  }
  val ipStrs = for (i <- 0 until n) yield readLine

  val res = solveStr(k, ipStrs)
  println(res)
}

import io.Source
import java.io.PrintWriter

object CF291C {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    val a = {for (i <- 0 until n) yield {
      ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong
    }}.toArray
    var l = 0
    var r = 32
    var rVal = -1
    while (l + 1 < r) {
      val mid = (l + r) / 2
      val mask = ((1L << mid) - 1) << (32 - mid)
      val set = collection.mutable.HashSet[Long]()
      for (x <- a) {
        set += x & mask
      }
      if (set.size < k) {
        l = mid
      } else {
        r = mid
        rVal = set.size
      }
    }
    if (r == 32 || rVal != k) {
      out.println(-1)
    } else {
      val ans = ((1L << r) - 1) << (32 - r)
      out.print((ans >> 24) & 255)
      out.print(".")
      out.print((ans >> 16) & 255)
      out.print(".")
      out.print((ans >> 8) & 255)
      out.print(".")
      out.print((ans >> 0) & 255)
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

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

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

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

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

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

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

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

    def apply() = tokenIterator.next()

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

object C {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);
  def main(args: Array[String]) {
    var Array(n, k) = READ
    def toIp(i: Int):Long = math.pow(2, i).toLong-1 << 32-i;
    var masks = (1 to 31) map (i => (i-1, toIp(i)));
    var arr = Array.fill(31)(scala.collection.mutable.HashSet.empty[Long])
    for (i <- 0 until n) {
      val ip:Long = readLine() split("\\.") map (_.toLong) reduce(_<<8 | _);
      masks foreach {x => arr(x._1).add(x._2&ip)}
    }
    for (i <- 1 to 31; if arr(i-1).size == k){
      val ip = toIp(i)
      printf("%d.%d.%d.%d\n", ip >> 24, (ip & 0xff0000) >> 16, (ip & 0xff00) >> 8, ip&0xff)
      return;
    }
    println(-1);
  }
}

/*
C. Маска подсети
ограничение по времени на тест
4 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

В задаче используется упрощенная модель адресов в TCP/IP, внимательно прочтите условие.

Поликарп устроился на работу системным администратором. Как-то раз к нему в руки попали n IP-адресов. Каждый IP-адрес — это 32-битное число, представленное в виде четверки десятичных 8-битных чисел (без лидирующих нулей), записанных через точку. Например, запись 0.255.1.123 обозначает корректный IP-адрес, а записи 0.256.1.123 и 0.255.1.01 — нет. В данной задаче произвольная четверка 8-битных чисел является корректным IP-адресом.

Поработав администратором, Поликарп узнал, что, зная IP-адрес, можно, используя маску подсети, получить адрес сети, которой принадлежит этот IP-адрес.

Маска подсети — это IP-адрес, обладающий следующим свойством: если записать этот IP-адрес, как 32-битную строку, то он представим в виде «11...11000..000». Другими словами, в маске подсети сначала идет один или более единичный бит, а затем один или более нулевой бит (всего битов 32). Например, IP-адрес 2.0.0.0 не является корректной маской подсети, так как его 32-битная запись имеет вид 00000010000000000000000000000000.

Для получения адреса сети IP-адреса нужно выполнить операцию побитового «и» («and») IP-адреса и маски подсети. Например, если маска подсети 255.192.0.0, а IP-адрес 192.168.1.2, то адрес сети равен 192.128.0.0. При побитовом «и» в записи результата бит равен 1 тогда и только тогда, когда у обоих операндов соответствующие биты единичные.

Теперь Поликарп хочет найти все сети, которым принадлежат его IP-адреса. К сожалению, Поликарп потерял маску подсети. К счастью, Поликарп запомнил, что его IP-адреса принадлежали ровно k различным сетям. Помогите Поликарпу найти маску подсети, такую, что его IP-адреса будут принадлежать ровно k различным сетям. Если таких масок несколько, найдите ту, в битовой записи которой наименьшее количество единиц. Если таких масок не существует, сообщите об этом.
Входные данные

В первой строке записаны два целых числа n и k (1 ≤ k ≤ n ≤ 105) — количество IP-адресов и сетей. В следующих n строках записаны сами IP-адреса. Гарантируется, что все IP-адреса различны.
Выходные данные

В единственной строке выведите IP-адрес маски подсети, в формате описанном в условии, если требуемая маска подсети существует. Иначе выведите -1.
Примеры тестов
Входные данные

5 3
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3

Выходные данные

255.255.254.0

Входные данные

5 2
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3

Выходные данные

255.255.0.0

Входные данные

2 1
255.0.0.1
0.0.0.2

Выходные данные

-1
*/
import scala.collection.immutable.HashSet
import scala.collection.immutable.BitSet
import scala.collection.mutable.MutableList

object Task3 extends App {

  def masks: Seq[Long] = {
    val init = 0xFFFFFFFFL
    var z = init
    val res = init +: (for (p <- 0 until 31) yield {
      z -= math.pow(2, p).toLong
      z
    })
    res.reverse
  }

  def applyMask(mask: Long, ips: Seq[Long]): Set[Long] = {
    ips.foldLeft(new HashSet[Long]) { (set, ip) =>
      set + (ip & mask)
    }
  }

  def toBits(ip: String): Long = {
    def parts = ip.trim split '.'
    require(parts.size == 4)
    val res = parts.foldLeft(0L)((acc, part) => acc * 256 + (part.toInt))
    res
  }

  def toStr(ip: Option[Long]): String = ip match {
    case None => "-1"
    case Some(l) => {
      val seg1 = (l & 0xFF000000L) >> 24
      val seg2 = (l & 0x00FF0000L) >> 16
      val seg3 = (l & 0x0000FF00L) >> 8
      val seg4 = (l & 0x000000FFL)
      seg1 + "." + seg2 + "." + seg3 + "." + seg4
    }
  }

  def solveStr(k: Int, ipStrs: Seq[String]): String =
    toStr(solve(k, ipStrs map toBits))

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(k: Int, ips: Seq[Long]): Option[Long] =
    if (k > ips.size) None
    else if (k == ips.size) Some(0xFFFFFFFFL)
    else masks.find(mask => applyMask(mask, ips).size == k)

  /*
  def bitStream(ones: Int): Stream[Long] = generateBits(0, 32, ones)

  def generateBits(curr: Long, remaining: Int, remainingOnes: Int): Stream[Long] = {
    val shifted = (curr << 1)
    if (remaining == 0) {
      assert(remainingOnes == 0)
      curr #:: Stream.empty
    } else if (remainingOnes == remaining) {
      generateBits(shifted + 1, remaining - 1, remainingOnes - 1)
    } else if (remainingOnes >= 1) {
      val v1 = generateBits(shifted + 1, remaining - 1, remainingOnes - 1)
      val v2 = generateBits(shifted + 0, remaining - 1, remainingOnes)
      Stream.concat(v1, v2)
    } else {
      generateBits(shifted, remaining - 1, remainingOnes)
    }
  }
*/
  val (n, k) = {
    val l = readLine split (' ') map (_.toInt)
    (l(0), l(1))
  }
  val ipStrs = for (i <- 0 until n) yield readLine

  val res = solveStr(k, ipStrs)
  println(res)
}

import io.Source
import java.io.PrintWriter

object CF291C {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    val a = {for (i <- 0 until n) yield {
      ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong
    }}.toArray
    var l = 0
    var r = 33
    while (l + 1 < r) {
      val mid = (l + r) / 2
      val mask = ((1L << mid) - 1) << (32 - mid)
      val set = collection.mutable.HashSet[Long]()
      for (x <- a) {
        set += x & mask
      }
      if (set.size < k) {
        l = mid
      } else {
        r = mid
      }
    }
    if (l == 0 || r == 33) {
      out.println(-1)
    } else {
      val ans = ((1L << r) - 1) << (32 - r)
      out.print((ans >> 24) & 255)
      out.print(".")
      out.print((ans >> 16) & 255)
      out.print(".")
      out.print((ans >> 8) & 255)
      out.print(".")
      out.print((ans >> 0) & 255)
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

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

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

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

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

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

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

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

    def apply() = tokenIterator.next()

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

import io.Source
import java.io.PrintWriter

object CF291C {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    val a = {for (i <- 0 until n) yield {
      ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong
    }}.toArray
    var l = 0
    var r = 33
    var rVal = -1
    while (l + 1 < r) {
      val mid = (l + r) / 2
      val mask = ((1L << mid) - 1) << (32 - mid)
      val set = collection.mutable.HashSet[Long]()
      for (x <- a) {
        set += x & mask
      }
      if (set.size < k) {
        l = mid
      } else {
        r = mid
        rVal = set.size
      }
    }
    if (l == 0 || r == 33 || rVal != k) {
      out.println(-1)
    } else {
      val ans = ((1L << r) - 1) << (32 - r)
      out.print((ans >> 24) & 255)
      out.print(".")
      out.print((ans >> 16) & 255)
      out.print(".")
      out.print((ans >> 8) & 255)
      out.print(".")
      out.print((ans >> 0) & 255)
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

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

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

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

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

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

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

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

    def apply() = tokenIterator.next()

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

import io.Source
import java.io.PrintWriter

object CF291C {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    val a = {for (i <- 0 until n) yield {
      ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong
    }}.toArray
    var l = 0
    var r = 32
    var rVal = -1
    while (l + 1 < r) {
      val mid = (l + r) / 2
      val mask = ((1L << mid) - 1) << (32 - mid)
      val set = collection.mutable.HashSet[Long]()
      for (x <- a) {
        set += x & mask
      }
      if (set.size < k) {
        l = mid
      } else {
        r = mid
        rVal = set.size
      }
    }
    if (l == 0 || r == 32 || rVal != k) {
      out.println(-1)
    } else {
      val ans = ((1L << r) - 1) << (32 - r)
      out.print((ans >> 24) & 255)
      out.print(".")
      out.print((ans >> 16) & 255)
      out.print(".")
      out.print((ans >> 8) & 255)
      out.print(".")
      out.print((ans >> 0) & 255)
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

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

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

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

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

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

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

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

    def apply() = tokenIterator.next()

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


Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).Your task is to count the number of segments where Horace can "see an elephant".

The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.

Print the number of segments in the bears' wall where Horace can "see an elephant".

NoteThe picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.

import java.util.Scanner

object CubeWalls extends App {

	final val SEP = 1000000000	// arrays separator

	val scanner = new Scanner( System.in )

	val n = scanner.nextInt
	val w = scanner.nextInt
	val a = Array.ofDim[Int]( n )
	for( i <- a.indices )
		a( i ) = scanner.nextInt
	val b = Array.ofDim[Int]( w )
	for( i <- b.indices )
		b( i ) = scanner.nextInt

	val matches = if( w > 1 ) {
		// array with differences to have simple matching
		val ad = a.sliding( 2 ).map( e => e( 1 ) - e( 0 )).toArray
		val bd = b.sliding( 2 ).map( e => e( 1 ) - e( 0 )).toArray
		// join the arrays to use Z function
		val bdad = (bd :+ SEP) ++ ad
		val z = zf( bdad )
		z.count( _ == w - 1 )		// count matches, shorter by 1 because we match array with differences
	}
	else
		n

/*	simple but with O(n*w) - too slow
	val bi = b.zipWithIndex
	val bi = b.zipWithIndex
	val matches = ( 0 to lDiff ) count { i =>
		val hDiff = a( i ) - b( 0 )
		bi.forall( x => a( i + x._2 ) - x._1 == hDiff )
	}
*/
	println( matches )

	// Z algorithm, see http://codeforces.com/blog/entry/3107
	def zf( s: Array[Int] ) = {
		val n = s.length
		val z = Array.ofDim[Int]( n )
		z( 0 ) = 0
		var l = 0
		var r = 0
		for( i <- 1 until n ) {
			if( i > r ) {
				l = i
				r = i
				while( r < n && s( r - l ) == s( r ))
					r += 1
				z( i ) = r - l
				r -= 1
			}
			else {
				val k = i - l
				if( z( k ) < r - i + 1 )
					z( i ) = z( k )
				else {
					l = i
					while( r < n && s( r - l ) == s( r ))
						r += 1
					z( i ) = r - l
					r -= 1
				}
			}
		}
		z
	}
}

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

object D {

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

  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 prefixFunc(string: Array[Int]): Array[Int] = {
    val π = new Array[Int](string.length)
    π(0) = 0
    for (i <- 1 to string.length - 1) {
      var j = π(i - 1)
      while (j != 0 && string(j) != string(i)) {
        j = π(j - 1)
      }
      if (string(j) == string(i)) {
        π(i) = j + 1
      } else {
        π(i) = 0
      }
    }
    π
  }

  def kmp(t: Array[Int], s: Array[Int]): Unit = {
    val del = new Array[Int](1)
    del(0) = Int.MaxValue
    val p = prefixFunc(s ++ del ++ t)
    for (i <- s.length + 1 to p.length - 1) {
      if (p(i) == s.length) {
        ans += 1
      }
    }
  }

  def solve: Int = {
    val n = nextInt
    val w = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](w)
    if (w == 1) {
      out.println(n)
      return 1
    }
    val ua = new Array[Int](n - 1)
    val ub = new Array[Int](w - 1)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    for (j <- 0 until w) {
      b(j) = nextInt
    }
    for (i <- 0 until n - 1) {
      ua(i) = a(i + 1) - a(i)
    }
    for (i <- 0 until w - 1) {
      ub(i) = b(i + 1) - b(i)
    }

    kmp(ua, ub)
    out.println(ans)
    return 1
  }

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

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

object D {

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

  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 prefixFunc(string: String): Array[Int] = {
    val π = new Array[Int](string.length)
    π(0) = 0
    for (i <- 1 to string.length - 1) {
      var j = π(i - 1)
      while (j != 0 && string(j) != string(i)) {
        j = π(j - 1)
      }
      if (string(j) == string(i)) {
        π(i) = j + 1
      } else {
        π(i) = 0
      }
    }
    π
  }

  def kmp(t: String, s: String): Unit = {
    val p = prefixFunc(s + "#" + t)
    for (i <- s.length + 1 to p.length - 1) {
      if (p(i) == s.length) {
        ans += 1
      }
    }
  }

  def solve: Int = {
    val n = nextInt
    val w = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](w)
    val ua = new Array[Int](n)
    val ub = new Array[Int](w)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    for (j <- 0 until w) {
      b(j) = nextInt
    }
    ua(0) = 0
    for (i <- 1 until n) {
      ua(i) = a(i) - a(i - 1)
    }
    for (i <- 1 until w) {
      ub(i) = b(i) - b(i - 1)
    }
    ub(0) = 0
    if (w == 1) {
      out.println(n)
      return 1
    }
    val t = ua.mkString("")
    val s = ub.mkString("").substring(1)
    kmp(t, s)
    out.println(ans)
    return 1
  }

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


Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array $$$a$$$ of $$$n$$$ integers. You are also given an integer $$$k$$$. Lord Omkar wants you to do $$$k$$$ operations with this array.Define one operation as the following:   Set $$$d$$$ to be the maximum value of your array.  For every $$$i$$$ from $$$1$$$ to $$$n$$$, replace $$$a_{i}$$$ with $$$d-a_{i}$$$. The goal is to predict the contents in the array after $$$k$$$ operations. Please help Ray determine what the final sequence will look like!

Each test contains multiple test cases. The first line contains the number of cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}$$$) – the length of your array and the number of operations to perform. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(-10^9 \leq a_{i} \leq 10^9)$$$ – the initial contents of your array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each case, print the final version of array $$$a$$$ after $$$k$$$ operations described above.

NoteIn the first test case the array changes as follows:Initially, the array is $$$[-199, 192]$$$. $$$d = 192$$$.After the operation, the array becomes $$$[d-(-199), d-192] = [391, 0]$$$.

object CodeforcesRound1392B {

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

  //2 1
  //-199 192
  //192+199 0
  //0 -192-199

  //1 3 7
  //7-1  7-3  7-7
  //6    4    0
  //0    2    6
  //6    4    0

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(nl, k) = rll_long
    val n = nl.toInt
    val a = rll_int
    val upToIter = (2 - (k % 2)).toInt
    for (_ <- 0 until upToIter) {
      val max = a.max
      for (i <- 0 until n) {
        a(i) = max - a(i)
      }
    }
    val res = a.mkString(" ")
    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 B {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, k = nextLong
      val as = nextLongs(n.toInt)
      val min = as.min
      val max = as.max

      for (i <- as.indices) {
        as(i) = max - as(i)
      }

      val d = max - min
      if (k % 2 == 0) {
        for (i <- as.indices) {
          as(i) = d - as(i)
        }
      }

      out.println(as.mkString(" "))
    }

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


In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most $$$a$$$ hours, and he will have $$$b$$$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $$$k$$$ in $$$k$$$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most $$$a$$$ hours in total, and fully read several lecture notes tomorrow, spending at most $$$b$$$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?

The only line of input contains two integers $$$a$$$ and $$$b$$$ ($$$0 \leq a, b \leq 10^{9}$$$) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.

In the first line print a single integer $$$n$$$ ($$$0 \leq n \leq a$$$) — the number of lecture notes Lesha has to read in the first day. In the second line print $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq a$$$), the sum of all $$$p_i$$$ should not exceed $$$a$$$. In the third line print a single integer $$$m$$$ ($$$0 \leq m \leq b$$$) — the number of lecture notes Lesha has to read in the second day. In the fourth line print $$$m$$$ distinct integers $$$q_1, q_2, \ldots, q_m$$$ ($$$1 \leq q_i \leq b$$$), the sum of all $$$q_i$$$ should not exceed $$$b$$$. All integers $$$p_i$$$ and $$$q_i$$$ should be distinct. The sum $$$n + m$$$ should be largest possible.

NoteIn the first example Lesha can read the third note in $$$3$$$ hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending $$$3$$$ hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending $$$9$$$ hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending $$$12$$$ hours in total.

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 = {
    var a, b = ni()
    def calcN(sum: Long) = {
      var i = 0
      while(i.toLong * i  + i <= 2 * sum) {i += 1}
      i - 1
    }
    val n = calcN(a + b)
    val selected = mutable.Set[Int]()
    var last = n
    while(a > 0 && last > 0) {
      if (a > last) {
        selected += last
        a -= last
        last -= 1
      } else {
        selected += a
        a = 0
      }
    }

    out.println(selected.size)
    out.println(selected.mkString(" "))
    out.println(n - selected.size)
    val bs = ArrayBuffer[Int]()
    rep(n, 1) { i =>
      if (!selected.contains(i)) bs += i
    }
    out.println(bs.mkString(" "))
  }

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

import scala.collection.mutable

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(a0, b0) = readInts(2)

  def can(maxK: Int): Boolean = {
    var k = maxK
    var a = a0
    var b = b0
    while (k > 0 && a >= 0 && b >= 0) {
      if (a >= b) a -= k else b -= k
      k -= 1
    }
    a >= 0 && b >= 0
  }

  @annotation.tailrec
  def binSearch(low: Int, hi: Int): Int = {
    if (hi < low) hi
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(mid + 1, hi)
      else binSearch(low, mid - 1)
    }
  }

  val res = binSearch(0, 1000000)

  val asBuilder, bsBuilder = new mutable.ArrayBuilder.ofInt
  var k = res
  var a = a0
  var b = b0
  while (k > 0 && a >= 0 && b >= 0) {
    if (a >= b) {
      asBuilder += k
      a -= k
    } else {
      bsBuilder += k
      b -= k
    }
    k -= 1
  }

  val as = asBuilder.result().reverse
  val bs = bsBuilder.result().reverse

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(as.length)
  println(as.mkString(" "))
  println(bs.length)
  println(bs.mkString(" "))

  Console.flush
}

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 = {
    var a, b = ni()
    def calcN(sum: Int) = {
      var i = 0
      while(i * i  + i< 2 * sum) {i += 1}
      i
    }
    val n = calcN(a + b)
    val selected = mutable.Set[Int]()
    var last = n
    while(a > 0) {
      if (a > last) {
        selected += last
        a -= last
        last -= 1
      } else {
        selected += a
        a = 0
      }
    }

    out.println(selected.size)
    out.println(selected.mkString(" "))
    out.println(n - selected.size)
    val bs = ArrayBuffer[Int]()
    rep(n, 1) { i =>
      if (!selected.contains(i)) bs += i
    }
    out.println(bs.mkString(" "))
  }

  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 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 = {
    var a, b = ni()
    def calcN(sum: Long) = {
      var i = 0
      while(i.toLong * i  + i< 2 * sum) {i += 1}
      i
    }
    val n = calcN(a + b)
    val selected = mutable.Set[Int]()
    var last = n
    while(a > 0) {
      if (a > last) {
        selected += last
        a -= last
        last -= 1
      } else {
        selected += a
        a = 0
      }
    }

    out.println(selected.size)
    out.println(selected.mkString(" "))
    out.println(n - selected.size)
    val bs = ArrayBuffer[Int]()
    rep(n, 1) { i =>
      if (!selected.contains(i)) bs += i
    }
    out.println(bs.mkString(" "))
  }

  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 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 = {
    var a, b = ni()
    def calcN(sum: Long) = {
      var i = 0
      while(i.toLong * i  + i<= 2 * sum) {i += 1}
      i - 1
    }
    val n = calcN(a + b)
    val selected = mutable.Set[Int]()
    var last = n
    while(a > 0) {
      if (a > last) {
        selected += last
        a -= last
        last -= 1
      } else {
        selected += a
        a = 0
      }
    }

    out.println(selected.size)
    out.println(selected.mkString(" "))
    out.println(n - selected.size)
    val bs = ArrayBuffer[Int]()
    rep(n, 1) { i =>
      if (!selected.contains(i)) bs += i
    }
    out.println(bs.mkString(" "))
  }

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


Positive integer $$$x$$$ is called divisor of positive integer $$$y$$$, if $$$y$$$ is divisible by $$$x$$$ without remainder. For example, $$$1$$$ is a divisor of $$$7$$$ and $$$3$$$ is not divisor of $$$8$$$.We gave you an integer $$$d$$$ and asked you to find the smallest positive integer $$$a$$$, such that  $$$a$$$ has at least $$$4$$$ divisors;  difference between any two divisors of $$$a$$$ is at least $$$d$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 3000$$$) — the number of test cases. The first line of each test case contains a single integer $$$d$$$ ($$$1 \leq d \leq 10000$$$).

For each test case print one integer $$$a$$$ — the answer for this test case.

NoteIn the first test case, integer $$$6$$$ have following divisors: $$$[1, 2, 3, 6]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$1$$$. There is no smaller integer with at least $$$4$$$ divisors.In the second test case, integer $$$15$$$ have following divisors: $$$[1, 3, 5, 15]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$2$$$.The answer $$$12$$$ is INVALID because divisors are $$$[1, 2, 3, 4, 6, 12]$$$. And the difference between, for example, divisors $$$2$$$ and $$$3$$$ is less than $$$d=2$$$.

object Hemlo {
  import scala.io.{StdIn => in}
  import scala.util.control._
  val C = new Array[Boolean](30005)
  def sieve(): Unit = {
    for (i <- 1 until 30005)
      C(i) = false
    for (i <- 2 until 30005) {
      if (C(i) == false) {
        for (j <- 2 * i until 30005 by i)
          C(j) = true
      }
    }
  }
  def cube(c: Long): Long = {
    c * c * c
  }
  def main(args: Array[String]): Unit = {
    sieve()
    var t: Int = in.readInt()
    while (t > 0) {
      val n: Int = in.readInt()
      var m1, m2: Long = -1
      val loop = new Breaks
      loop.breakable {
        for (i <- n + 1 until 300005) {
          if (C(i) == false) {
            if (m1 == -1) {
              m1 = i
            } else if (m2 == -1 && i - m1 >= n) {
              m2 = i
              loop.break()
            }
          }
        }
      }
      var ans: Long = 0
      if (cube(m1) <= m1 * m2)
        ans = cube(m1)
      else ans = m1 * m2
      println(ans)
      t -= 1
    }
  }
}

object Hemlo {
  import scala.io.{StdIn => in}
  import scala.util.control._
  val C = new Array[Boolean](30005)
  def sieve(): Unit = {
    for (i <- 1 until 30005)
      C(i) = false
    for (i <- 2 until 30005) {
      if (C(i) == false) {
        for (j <- 2 * i until 30005 by i)
          C(j) = true
      }
    }
  }
  def cube(c: Int): Int = {
    c * c * c
  }
  def main(args: Array[String]): Unit = {
    sieve()
    var t: Int = in.readInt()
    while (t > 0) {
      val n: Int = in.readInt()
      var m1, m2: Int = -1
      val loop = new Breaks
      loop.breakable {
        for (i <- n + 1 until 300005) {
          if (C(i) == false) {
            if (m1 == -1) {
              m1 = i
            } else if (m2 == -1 && i - m1 >= n) {
              m2 = i
              loop.break()
            }
          }
        }
      }
      var ans: Int = 0
      if (cube(m1) <= m1 * m2)
        ans = cube(m1)
      else ans = m1 * m2
      println(ans)
      t -= 1
    }
  }
}


Arkady is playing Battleship. The rules of this game aren't really important.There is a field of $$$n \times n$$$ cells. There should be exactly one $$$k$$$-decker on the field, i. e. a ship that is $$$k$$$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$) — the size of the field and the size of the ship. The next $$$n$$$ lines contain the field. Each line contains $$$n$$$ characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship).

Output two integers — the row and the column of a cell that belongs to the maximum possible number of different locations of the ship. If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell.

NoteThe picture below shows the three possible locations of the ship that contain the cell $$$(3, 2)$$$ in the first sample.

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

  override def apply(io: IO): io.type = {
    val n, k = io.read[Int]

    val canHasShip = io.read[Vector, String](n)
        .map(row => row.map(_ == '.'))

    val result = Array.ofDim[Int](n, n)
    for {
      r <- 0 until n
      c <- 0 until n
      horizontal = (0 until k).forall(i => canHasShip(r).isDefinedAt(c + i) && canHasShip(r)(c + i))
        vertical = (0 until k).forall(i => canHasShip.isDefinedAt(r + i) && canHasShip(r + i)(c))
    } {
      if (horizontal) (0 until k).foreach(i => result(r)(c + i) += 1)
      if   (vertical) (0 until k).foreach(i => result(r + i)(c) += 1)
    }

    var maxX, maxY, maxC = -1

    for {
      r <- 0 until n
      c <- 0 until n
      if result(r)(c) > maxC
    } {
      maxC = result(r)(c)
      maxX = r+1
      maxY = c+1
    }

    io.write(s"$maxX $maxY")
  }
}
/****************************[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
      }
    }
  }
}


Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $$$n$$$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $$$d$$$ rubles, and one euro costs $$$e$$$ rubles.Recall that there exist the following dollar bills: $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, and the following euro bills — $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (note that, in this problem we do not consider the $$$500$$$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him — write a program that given integers $$$n$$$, $$$e$$$ and $$$d$$$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.

The first line of the input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^8$$$) — the initial sum in rubles Andrew has.  The second line of the input contains one integer $$$d$$$ ($$$30 \leq d \leq 100$$$) — the price of one dollar in rubles.  The third line of the input contains integer $$$e$$$ ($$$30 \leq e \leq 100$$$) — the price of one euro in rubles.

Output one integer — the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.

NoteIn the first example, we can buy just $$$1$$$ dollar because there is no $$$1$$$ euro bill.In the second example, optimal exchange is to buy $$$5$$$ euro and $$$1$$$ dollar.In the third example, optimal exchange is to buy $$$10$$$ dollars in one bill.

object A {

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

  val n = readLong
  val d, e = readInt

  var res = n % d

  for (i <- 1 to 1000) {
    for (j <- 1 to 1000) {
      val x = n % (5L * i * e) % (d * j)
      val y = n % (d * j) % (5L * i * e)
      if (x < res) res = x
      if (y < res) res = y
    }
  }

  println(res)
}

object A {

  def main(args: Array[String]): Unit = {}
  @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 n = readLong
  val d, e = readInt

  var res = n % d

  for (i <- 1 to 100000) {
    val x = n % (5L * i * e) % d
    if (x < res) res = x
  }

  println(res)
}

object A {

  def main(args: Array[String]): Unit = {}
  @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 n = readLong
  val d, e = readInt

  val res = math.min(n % d, n % (5 * e) % d)

  println(res)
}


Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.

You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.

Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.

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

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last - 1) == 0)
    println("Just a legend")
  else
    println(line.take(p(p.last - 1)))
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val s=readLine
    val n=s.length
    val dp=new Array[Int](n)

    for(i<-1 until n){
        var j=i
        while(j>0 && s(i)!=s(dp(j-1))) j=dp(j-1)
        dp(i)=if(j>0) dp(j-1)+1 else 0
    }

    val max=if(n>2) dp.slice(1,n-1).max else 0
    var j=dp(n-1)
    while(j>max) j=dp(j-1)
    println(if(j==0) "Just a legend" else s.substring(0,j))
}

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

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last) == 0)
    println("Just a legend")
  else
    println(line.take(p(p.last) - 1))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val first = line.head
  val last = line.last
  val lettersInit = Array.ofDim[Int](26)
  val lettersTail = Array.ofDim[Int](26)

  def isEqual(len: Int) = {
    (0 until len).forall(i => line(i) == line(line.length - 1 - len + i))
  }

  val candidates = (0 until line.length - 2).filter { i =>
      val j = line.length - 1 - i
      lettersInit(line(i) - 'a') += 1
      lettersTail(line(j) - 'a') += 1
//      println(line(i))
//      println(line(j))
      line(i) == last && line(j) == first && (lettersInit sameElements lettersTail)
  }

  candidates.find(i =>  isEqual(i) && line.indexOf(line.take(i + 1), 1) != line.length - 1 - i) match {
    case None => println("Just a legend")
    case Some(i) => println(line.take(i + 1))
  }
}

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

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last) == 0)
    println("Just a legend")
  else
    println(line.take(p(p.last)))
}

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

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)
  println(p.mkString(" "))

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last - 1) == 0)
    println("Just a legend")
  else
    println(line.take(p(p.last - 1)))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val first = line.head
  val last = line.last
  val lettersInit = Array.ofDim[Int](26)
  val lettersTail = Array.ofDim[Int](26)

  def isEqual(len: Int) = {
    (0 until len).forall(i => line(i) == line(line.length - 1 - len + i))
  }

  val candidates = (0 until line.length - 2).filter { i =>
      val j = line.length - 1 - i
      lettersInit(line(i) - 'a') += 1
      lettersTail(line(j) - 'a') += 1
//      println(line(i))
//      println(line(j))
      line(i) == last && line(j) == first && (lettersInit sameElements lettersTail) && isEqual(i)
  }

  candidates.find(i => line.indexOf(line.take(i + 1), 1) != line.length - 1 - i) match {
    case None => println("Just a legend")
    case Some(i) => println(line.take(i + 1))
  }
}

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

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last) < 2)
    println("Just a legend")
  else
    println(line.take(p(p.last) - 1))
}