User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≤ i, j ≤ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.

The first line contains an integer n (1 ≤ n ≤ 300) — the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn — the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≤ i < j ≤ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≤ i ≤ n, Ai, i = 0 holds.

In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.

NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4).   A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val matrix = (0 until n).map(i => in.next().zipWithIndex.filter(t => t._1 == '1').map(_._2).toSet + i)
    .filter(_.size > 1)
  val marked = Array.ofDim[Boolean](matrix.length)
  val result = data.clone()
  matrix.indices.foreach {
    case i if marked(i) =>
    case i =>
      marked(i) = true
      var found = true
      var set = matrix(i)
      while (found) {
        found = false
        (i + 1 until matrix.length).filter(j => !marked(j)).foreach { j =>
          val joined = set ++ matrix(j)
          if (joined.size < set.size + matrix(j).size) {
            set = joined
            marked(j) = true
            found = true
          }
        }
      }
      val list = set.toList
      val values = list.map(data).sorted
      val indices = list.sorted
      indices.zip(values).foreach {
        case(j, v) => result(j) = v
      }
  }
  println(result.mkString(" "))
}

import scala.collection.mutable

object B500 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    val n = readInt
    val p = readInts(n).map(_ - 1)
    val graph = Array.fill(n) { read.toArray.map(_ == '1') }
    for (k <- 0 until n; i <- 0 until n; j <- 0 until n
         if graph(i)(k) && graph(k)(j)) {
      graph(i)(j) = true
    }

    case class Ele(number: Int, pos: Int) extends Ordered[Ele] {
      def compare(that: Ele) = -this.number.compareTo(that.number)
    }
    val pq = mutable.PriorityQueue.empty[Ele] // number, pos
    for (idx <- 0 until n) {
      pq.enqueue((idx + 1 until n).map { _idx =>
        Ele(p(_idx), _idx)
      }: _*)
      while (pq.nonEmpty && pq.head.number < p(idx)) {
        val top = pq.dequeue()
        if (graph(idx)(top.pos)) {
          val tmp = p(idx)
          p(idx) = top.number
          p(top.pos) = tmp
        }
      }
      pq.clear()
    }

    out.println(p.map(_ + 1).mkString(" "))
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)
  val ps = readInts(n)
  val as = Array.fill(n)(readLine.toCharArray.map(_ == '1'))
  val pos = ps.zipWithIndex.toMap

  val res = Array.fill(n)(0)

  val range = 0 until n
  for (i <- range) as(i)(i) = true
  for (k <- range)
    for (i <- range) if (as(i)(k))
      for (j <- range) if (as(k)(j)) as(i)(j) = true

  for (p <- 1 to n) {
    var i = 0
    var found = false
    while (!found) {
      if (res(i) == 0 && as(pos(p))(i)) {
        res(i) = p
        found = true
      } else i += 1
    }
  }

  println(res.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val matrix = (1 to n).map(_ => in.next().zipWithIndex.filter(t => t._1 == '1').map(_._2).toSet).filter(_.size > 1)
  val marked = Array.ofDim[Boolean](matrix.length)
  val result = data.clone()
  matrix.indices.foreach {
    case i if marked(i) =>
    case i =>
      marked(i) = true
      var found = true
      var set = matrix(i)
      while (found) {
        found = false
        (i + 1 until matrix.length).filter(j => !marked(j)).foreach { j =>
          val joined = set ++ matrix(j)
          if (joined.size < set.size + matrix(j).size) {
            set = joined
            marked(j) = true
            found = true
          }
        }
      }
      val list = set.toList
      val values = list.map(data).sorted
      val indices = list.sorted
      indices.zip(values).foreach {
        case(j, v) => result(j) = v
      }
  }
  println(result.mkString(" "))
}


When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a $$$2 \times n$$$ grid where each row is a permutation of the numbers $$$1,2,3,\ldots,n$$$.The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo $$$10^9+7$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 4 \cdot 10^5$$$). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers $$$1,2,3,\ldots,n$$$ and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo $$$10^9+7$$$. The answer for each test case should be on a separate line.

NoteThe two possible puzzle configurations for example $$$1$$$ are:  $$$[1,4,2,3]$$$ in the first row and $$$[3,2,1,4]$$$ in the second;  $$$[3,2,1,4]$$$ in the first row and $$$[1,4,2,3]$$$ in the second.

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

  val Mod = 1000000007
  val t   = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)
    val bn = readLine().split(" ").map(_.toInt)

    val colors = Array.fill(n + 1)(0)

    val adjacent = {
      val temp = Array.fill(n + 1)(0)
      (0 until n).foreach { i => temp(an(i)) = bn(i) }
      temp
    }

    @annotation.tailrec
    def dfs(ai: Int): Unit = {
      colors(ai) = 1
      val aj = adjacent(ai)
      if (colors(aj) == 0) dfs(aj)
    }

    val ans = (1 to n).foldLeft(1) {
      case (count, ai) if colors(ai) == 0 =>
        dfs(ai)
        (count << 1) % Mod
      case (count, _)                     => count
    }

    println(ans)
  }
}

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

  val Mod = 1000000007
  val t   = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)
    val bn = readLine().split(" ").map(_.toInt)

    val ans = {
      val is   = Array.fill(n)(0)
      val ai2i = an.zipWithIndex.toMap

      @annotation.tailrec
      def go(count: Int): Int =
        is.zipWithIndex.collectFirst { case (0, i) => i } match {
          case None    => count
          case Some(i) =>
            @annotation.tailrec
            def path(j: Int, count: Int = 0): Int = {
              is(j) = 1

              val bj = bn(j)
              val k  = ai2i(bj)

              if (i == k) count
              else path(k, count + 1)
            }

            go((2 * path(i)) % Mod)
        }

      go(1)
    }

    println(ans)
  }
}

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

  val Mod = 1000000007
  val t   = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)
    val bn = readLine().split(" ").map(_.toInt)

    val ans = {
      val is   = Array.fill(n)(0)
      val ai2i = an.zipWithIndex.toMap

      @annotation.tailrec
      def go(count: Int): Int =
        is.zipWithIndex.collectFirst { case (0, i) => i } match {
          case None    => count
          case Some(i) =>
            @annotation.tailrec
            def path(j: Int, count: Int = 0): Int = {
              is(i) = 1

              val bj = bn(j)
              val k  = ai2i(bj)

              if (i == k) count
              else path(k, count + 1)
            }

            go((2 * path(i)) % Mod)
        }

      go(1)
    }

    println(ans)
  }
}


YouKn0wWho has an integer sequence $$$a_1, a_2, \ldots, a_n$$$. He will perform the following operation until the sequence becomes empty: select an index $$$i$$$ such that $$$1 \le i \le |a|$$$ and $$$a_i$$$ is not divisible by $$$(i + 1)$$$, and erase this element from the sequence. Here $$$|a|$$$ is the length of sequence $$$a$$$ at the moment of operation. Note that the sequence $$$a$$$ changes and the next operation is performed on this changed sequence.For example, if $$$a=[3,5,4,5]$$$, then he can select $$$i = 2$$$, because $$$a_2 = 5$$$ is not divisible by $$$i+1 = 3$$$. After this operation the sequence is $$$[3,4,5]$$$.Help YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$)  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if it is possible to erase the whole sequence using the aforementioned operation, print "NO" (without quotes) otherwise. You can print each letter in any register (upper or lower).

NoteIn the first test case, YouKn0wWho can perform the following operations (the erased elements are underlined): $$$[1, \underline{2}, 3] \rightarrow [\underline{1}, 3] \rightarrow [\underline{3}] \rightarrow [\,].$$$In the second test case, it is impossible to erase the sequence as $$$i$$$ can only be $$$1$$$, and when $$$i=1$$$, $$$a_1 = 2$$$ is divisible by $$$i + 1 = 2$$$.

object C extends App {

  def divisibleConfusion(an: IndexedSeq[Int]): Boolean = {
    val n = an.length

    @annotation.tailrec
    def go(index: Int): Boolean =
      if (index == n) true
      else {
        val ai = an(index)
        index.to(0, -1).exists { j => ai % (j + 2) != 0 } && go(index + 1)
      }

    go(0)
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val an = nextInts(n)

    divisibleConfusion(an) match {
      case true  => out.println("YES")
      case false => out.println("NO")
    }

  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

object C extends App {

  def divisibleConfusion(an: IndexedSeq[Int]): Boolean = {
    val n = an.length

    @annotation.tailrec
    def go(index: Int, removed: Int): Boolean =
      if (index == n) true
      else {
        val ai = an(index)

        val canBeRemoved = index.to(index - removed, -1).exists { index =>
          ai % (index + 2) != 0
        }

        canBeRemoved && go(index + 1, removed + 1)
      }

    go(0, 0)
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val an = nextInts(n)

    divisibleConfusion(an) match {
      case true  => out.println("YES")
      case false => out.println("NO")
    }

  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

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

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

    case class pair(var minl: Int, var maxl:  Int, var minr: Int, var maxr:  Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return minl.compareTo(that.minl)
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        var ans = "YES"
        for (i <- 1 to n) {
            var flag = false
            var m = readInt()
            var k = 2
            while (k <= i+1 && !flag && ans == "YES") {
                if (m % k != 0)
                    flag = true
                k += 1
            }
            if (!flag)
                ans = "NO"
        }
        writer.println(ans)
    }
    writer.flush()
}


A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:  Employee A is the immediate manager of employee B  Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?

The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.  It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.

Print a single integer denoting the minimum number of groups that will be formed in the party.

NoteFor the first example, three groups are sufficient, for example:   Employee 1  Employees 2 and 4  Employees 3 and 5

object Main {

  val MAX = 2222
  val adj = new Array[List[Int]](2222)

  def getHeight(u: Int, pu: Int, h: Int): Int = {
    1 + (for (v <- adj(u)) yield if (v != pu) getHeight(v,u,h+1) else 0).foldRight(0)(Math.max)
  }

  def main(args: Array[String]) {
    val n = readInt()
    for (i <- 1 to n) adj(i) = Nil
    var roots: List[Int] = Nil
    for (i <- 1 to n) {
      val pi = readInt()
      if (pi != -1) {
        adj(i) = pi :: adj(i)
        adj(pi) = i :: adj(pi)
      } else
        roots = i :: roots
    }

    val ans = (for (r <- roots) yield getHeight(r,0,0)).foldRight(0)(Math.max)
    println(ans)
  }

}

object Party {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val n=in.readLine().toInt
    val arr=Array.ofDim[Int](n)
    for(i<-Range(0,n)){
      val x=in.readLine().toInt
      arr(i)= if(x>0) x-1 else -1
    }
    var maxD=1
    for(i<- 0 until n){
      var j=i
      var curD=1
      while (arr(j)!= -1){
        curD+=1
        j=arr(j)
      }
      maxD=math.max(maxD,curD)
    }
    println(maxD)
  }
}

import java.io.InputStream

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    runOn(System.in)
//    runOn(new StringBufferInputStream("5\n-1\n1\n2\n1\n-1\n"))
  }

  def runOn(is: InputStream): Unit = {
    val tokens = tokensFrom(is).map(_.toInt)

    val numberOfPeople = tokens.next()
    val managers = Array.fill(numberOfPeople)(tokens.next() - 1)

    val depths = managers.indices.map(depthOf(managers, _))
    val maxDepth = depths.max

    val result = maxDepth + 1
    println(result)
  }

  @tailrec
  private def depthOf(managers: Array[Int], targetIndex: Int, currentCount: Int = 0): Int = {
    val targetManagerIndex = managers(targetIndex)
    if (targetManagerIndex < 0) {
      currentCount
    } else {
      depthOf(managers, targetManagerIndex, currentCount + 1)
    }
  }

  private def tokensFrom(is: InputStream) = {
    val reader = new java.io.BufferedReader(new java.io.InputStreamReader(is))
    Iterator.continually(reader.readLine()).flatMap(_.split(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map(_ => in.next().toInt - 1)
  println(data.foldLeft(0){
    case(acc, el) =>
      var i = 1
      var c = el
      while (c >= 0) {
        i += 1
        c = data(c)
      }
      Math.max(acc, i)
  })
}

object A115 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(readInts(1)).map(_(0))
    val vis = Array.fill(n)(false)
    var res = 1
    for(i <- 0 until n if !vis(i)) {
      if(in(i) == -1)
        vis(i) = true
      else {
        var j = i
        var curr = 1
        while(in(j) != -1) {
          j = in(j) - 1
          curr += 1
        }
        res = math.max(res, curr)
      }
    }
    println(res)
  }

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

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

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

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

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

}

import java.io.InputStream

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    runOn(System.in)
//    runOn(new StringBufferInputStream("5\n-1\n1\n2\n1\n-1\n"))
  }

  def runOn(is: InputStream): Unit = {
    val tokens = tokensFrom(is).map(_.toInt)

    val numberOfPeople = tokens.next()
    val managers = Array.fill(numberOfPeople)(tokens.next() - 1)

    val depths = managers.indices.map(depthOf(managers, _))
    val maxDepth = depths.max

    val result = Math.min(3, maxDepth + 1)

    println(result)
  }

  @tailrec
  private def depthOf(managers: Array[Int], targetIndex: Int, currentCount: Int = 0): Int = {
    val targetManagerIndex = managers(targetIndex)
    if (targetManagerIndex < 0) {
      currentCount
    } else {
      depthOf(managers, targetManagerIndex, currentCount + 1)
    }
  }

  private def tokensFrom(is: InputStream) = {
    val reader = new java.io.BufferedReader(new java.io.InputStreamReader(is))
    Iterator.continually(reader.readLine()).flatMap(_.split(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map(_ => in.next().toInt - 1)
  println(data.foldLeft(0){
    case(acc, el) =>
      var i = 1
      var c = el
      while (c >= 0) {
        i += 1
        c = data(c)
      }
      Math.max(acc, i)
  })
  println(data)

}


You are given $$$n$$$ arrays that can have different sizes. You also have a table with $$$w$$$ columns and $$$n$$$ rows. The $$$i$$$-th array is placed horizontally in the $$$i$$$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.You need to find the maximum sum of the integers in the $$$j$$$-th column for each $$$j$$$ from $$$1$$$ to $$$w$$$ independently.  Optimal placements for columns $$$1$$$, $$$2$$$ and $$$3$$$ are shown on the pictures from left to right. Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.

The first line contains two integers $$$n$$$ ($$$1 \le n \le 10^{6}$$$) and $$$w$$$ ($$$1 \le w \le 10^{6}$$$) — the number of arrays and the width of the table. Each of the next $$$n$$$ lines consists of an integer $$$l_{i}$$$ ($$$1 \le l_{i} \le w$$$), the length of the $$$i$$$-th array, followed by $$$l_{i}$$$ integers $$$a_{i1}, a_{i2}, \ldots, a_{il_i}$$$ ($$$-10^{9} \le a_{ij} \le 10^{9}$$$) — the elements of the array. The total length of the arrays does no exceed $$$10^{6}$$$.

Print $$$w$$$ integers, the $$$i$$$-th of them should be the maximum sum for column $$$i$$$.

NoteIllustration for the first example is in the statement.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

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

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 = 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) { i =>
      f(i)
    }
  }
  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 Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, W = ni()
    val ans = Array.ofDim[Long](W + 1)

    // [l, r)
    def add(l: Int, r: Int, a: Int): Unit = {
      debug(s"add($l, $r, $a)")
      ans(l) += a
      ans(r) -= a
    }

    val INF = -1e9.toInt - 10
    REP(N) { _ =>
      val l = ni()
      val t = new SegmentTree(l + 2, INF)(max) // 両サイドに0を追加
      t.update(0, 0)
      t.update(l + 1, 0)
      REP(l) { i =>
        val a = ni()
        t.update(i + 1, a)
      }

      def calc1(i: Int): Int = {
        val a = max(0, i - (W - l) + 1)
        val b = min(l + 2, i + 2)
        t.query(a, b)
      }

      // [0, l+2)の部分があるか
      if (l < W - l) {
        // [0, l)
        REP(l) { i =>
          add(i, i + 1, calc1(i))
        }

        // [l, w-l)
        if (l < W - l) {
          add(l, W - l, t.query(0, l + 2))
        }

        // [w-l, w)
        TO(W - l, W - 1) { i =>
          add(i, i + 1, calc1(i))
        }
      } else {
        REP(W) { i =>
          add(i, i + 1, calc1(i))
        }
      }

      debug(ans)
    }

    REP(W) { i =>
      ans(i + 1) += ans(i)
    }

    out.println(ans.take(W).mkString(" "))
  }

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

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

    /**
      * [a, b)
      */
    def query(a: Int, b: Int): Int = {
      assert(a < n && b <= n)

      var res: Int = zero
      var left = a + N
      var right = b - 1 + N

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

      res
    }
  }
}


The Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are n gems in the Shuseki Islands in total, and the i-th gem is located on island pi.Mr. Kitayuta has just arrived at island 0. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process:   First, he will jump from island 0 to island d.  After that, he will continue jumping according to the following rule. Let l be the length of the previous jump, that is, if his previous jump was from island prev to island cur, let l = cur - prev. He will perform a jump of length l - 1, l or l + 1 to the east. That is, he will jump to island (cur + l - 1), (cur + l) or (cur + l + 1) (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length 0 when l = 1. If there is no valid destination, he will stop jumping. Mr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect.

The first line of the input contains two space-separated integers n and d (1 ≤ n, d ≤ 30000), denoting the number of the gems in the Shuseki Islands and the length of the Mr. Kitayuta's first jump, respectively. The next n lines describe the location of the gems. The i-th of them (1 ≤ i ≤ n) contains a integer pi (d ≤ p1 ≤ p2 ≤ ... ≤ pn ≤ 30000), denoting the number of the island that contains the i-th gem.

Print the maximum number of gems that Mr. Kitayuta can collect.

NoteIn the first sample, the optimal route is 0  →  10 (+1 gem)  →  19  →  27 (+2 gems)  → ...In the second sample, the optimal route is 0  →  8  →  15  →  21 →  28 (+1 gem)  →  36 (+1 gem)  →  45 (+1 gem)  →  55 (+1 gem)  →  66 (+1 gem)  →  78 (+1 gem)  → ...In the third sample, the optimal route is 0  →  7  →  13  →  18 (+1 gem)  →  24 (+2 gems)  →  30 (+1 gem)  → ...

object Solution extends App {
  val data = scala.io.Source.stdin.getLines()
  val Array(n, d) = data.next().split(" ").map(_.toInt)
  val M = 30001
  val nn = 250
  val gem = Array.ofDim[Int](M)
  val dp = Array.fill[Int](M, nn * 2){ -1}
  val tasks = Range(0, n).foreach{i => gem(data.next().toInt) += 1}
  var i = d

  def solve(i: Int, j: Int): Int = {
    val jj = j - (d - nn)
    if (i >= M) 0
    else if (dp(i)(jj) != -1) dp(i)(jj)
    else {
      dp(i)(jj) = 0
      dp(i)(jj) = gem(i) + (if (j == 1) Math.max(solve(i + j, j), solve(i + j + 1, j + 1)) else
        Math.max(solve(i + j - 1, j - 1), Math.max(solve(i + j, j), solve(i + j + 1, j + 1))))
      dp(i)(jj)
    }
  }

  println(solve(d, d))
}


Let $$$f(i)$$$ denote the minimum positive integer $$$x$$$ such that $$$x$$$ is not a divisor of $$$i$$$.Compute $$$\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$. In other words, compute $$$f(1)+f(2)+\dots+f(n)$$$ modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 10^4$$$), the number of test cases. Then $$$t$$$ cases follow. The only line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 10^{16}$$$).

For each test case, output a single integer $$$ans$$$, where $$$ans=\sum_{i=1}^n f(i)$$$ modulo $$$10^9+7$$$.

NoteIn the fourth test case $$$n=4$$$, so $$$ans=f(1)+f(2)+f(3)+f(4)$$$.  $$$1$$$ is a divisor of $$$1$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$1$$$. Thus, $$$f(1)=2$$$.  $$$1$$$ and $$$2$$$ are divisors of $$$2$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$2$$$. Thus, $$$f(2)=3$$$.  $$$1$$$ is a divisor of $$$3$$$ but $$$2$$$ isn't, so $$$2$$$ is the minimum positive integer that isn't a divisor of $$$3$$$. Thus, $$$f(3)=2$$$.  $$$1$$$ and $$$2$$$ are divisors of $$$4$$$ but $$$3$$$ isn't, so $$$3$$$ is the minimum positive integer that isn't a divisor of $$$4$$$. Thus, $$$f(4)=3$$$. Therefore, $$$ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=10$$$.

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

  @annotation.tailrec
  def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)

  def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b

  val Mod = (1e9 + 7).toLong
  val t   = readInt()

  (0 until t).foreach { _ =>
    val n = readLong()

    val ans = {
      @annotation.tailrec
      def go(y: Long, lcmx: Long = 1L, result: Long = 0L): Long =
        if (lcmx > n) result
        else {
          val lcmy  = lcm(lcmx, y)
          val count = n / lcmx - n / lcmy
          go(y + 1, lcmy, (result + y * count % Mod) % Mod)
        }

      go(2L)
    }

    println(ans)
  }
}


You and your friend are participating in a TV show "Run For Your Prize".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?

The first line contains one integer n (1 ≤ n ≤ 105) — the number of prizes. The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 106 - 1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.

Print one integer — the minimum number of seconds it will take to collect all prizes.

NoteIn the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.

object B extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)
  val friend = 1000000

  var max = 0
  for (a <- as) {
    val m = Math.min(a - 1, friend - a)
    if (m > max) max = m
  }

  println(max)
}

object B extends App {
  val l = 1000000
  val n = scala.io.StdIn.readInt()
  val m = scala.io.StdIn.readLine().split(" ").foldLeft(0)((m, w) => {
    val i = w.toInt
    m max ((i - 1) min (l - i))
  })

  println(m)
}

object CF938B extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val a = Seq.fill[Int](n)(sc.nextInt)
  val you = a filter (_ <= Math.pow(10,6) / 2)
  val friend =  a filter (_ > Math.pow(10,6) / 2)
  println(Math.max(if(you isEmpty) 0 else (you max) - 1, if(friend isEmpty) 0 else Math.pow(10,6).toInt - (friend min)))
}


Tsumugi brought $$$n$$$ delicious sweets to the Light Music Club. They are numbered from $$$1$$$ to $$$n$$$, where the $$$i$$$-th sweet has a sugar concentration described by an integer $$$a_i$$$.Yui loves sweets, but she can eat at most $$$m$$$ sweets each day for health reasons.Days are $$$1$$$-indexed (numbered $$$1, 2, 3, \ldots$$$). Eating the sweet $$$i$$$ at the $$$d$$$-th day will cause a sugar penalty of $$$(d \cdot a_i)$$$, as sweets become more sugary with time. A sweet can be eaten at most once.The total sugar penalty will be the sum of the individual penalties of each sweet eaten.Suppose that Yui chooses exactly $$$k$$$ sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?Since Yui is an undecided girl, she wants you to answer this question for every value of $$$k$$$ between $$$1$$$ and $$$n$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 200\ 000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 200\ 000$$$).

You have to output $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ on a single line, separed by spaces, where $$$x_k$$$ is the minimum total sugar penalty Yui can get if she eats exactly $$$k$$$ sweets.

NoteLet's analyze the answer for $$$k = 5$$$ in the first example. Here is one of the possible ways to eat $$$5$$$ sweets that minimize total sugar penalty:  Day $$$1$$$: sweets $$$1$$$ and $$$4$$$  Day $$$2$$$: sweets $$$5$$$ and $$$3$$$  Day $$$3$$$ : sweet $$$6$$$ Total penalty is $$$1 \cdot a_1 + 1 \cdot a_4 + 2 \cdot a_5 + 2 \cdot a_3 + 3 \cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30$$$. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats $$$5$$$ sweets, hence $$$x_5 = 30$$$.

object C1253 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    var tests = 1 // readInt
    while (tests > 0) {
      val Array(n, m) = readInts(2)
      val a = readInts(n).sorted
      var res = 0L
      val dp = Array.fill(n)(0L)
      for (i <- 0 until n) {
        dp(i) = a(i) + (if (i - m >= 0) dp(i - m) else 0)
      }
//      out.println(dp.mkString(" "))
      for (idx <- 0 until n) {
        res += dp(idx)
//        var i = idx
//        while (i >= 0 && idx < n) {
//          res += a(i)
//          i -= m
//        }
        out.print(s"$res ")
      }
      out.println("")
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

  val n, m = nextInt
  val as = nextLongs(n).sorted
  val pen1, pen2 = Array.fill(m)(0L)
  val res = Array.fill(n)(0L)

  var sum = 0L
  for (i <- 0 until m) {
    sum += as(i)
    pen1(i) = as(i)
    pen2(i) = as(i)
    res(i) = sum
  }

  for (i <- m until n) {
    val mod = i % m
    sum += pen1(mod) + as(i)
    pen2(mod) += pen1(mod)
    pen1(mod) += as(i)
    pen2(mod) += as(i)
    res(i) = sum
  }

  out.println(res.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
  }
}

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

  val n, m = nextInt
  val as = nextLongs(n).sorted
  val pen1 = Array.fill(m)(0L)
  val res = Array.fill(n)(0L)

  var sum = 0L
  for (i <- 0 until m) {
    sum += as(i)
    pen1(i) = as(i)
    res(i) = sum
  }

  for (i <- m until n) {
    val mod = i % m
    sum += pen1(mod) + as(i)
    pen1(mod) += as(i)
    res(i) = sum
  }

  out.println(res.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
  }
}

object C1253 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    var tests = 1 // readInt
    while (tests > 0) {
      val Array(n, m) = readInts(2)
      val a = readInts(n).sorted
      var res = 0L
      val dp = Array.fill(n)(0)
      for (i <- 0 until n) {
        dp(i) = a(i) + (if (i - m >= 0) dp(i - m) else 0)
      }
//      out.println(dp.mkString(" "))
      for (idx <- 0 until n) {
        res += dp(idx)
//        var i = idx
//        while (i >= 0 && idx < n) {
//          res += a(i)
//          i -= m
//        }
        out.print(s"$res ")
      }
      out.println("")
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


A piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations — choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.

The first line contains two integers n and k (1 ≤ n ≤ 105; 0 ≤ k ≤ 109) — the number of elements in the array and the number of operations you are allowed to perform, correspondingly. The third line contains a sequence of n integers a1, a2, ..., an (|ai| ≤ 109) — the initial array. The numbers in the lines are separated by single spaces.

In a single line print two numbers — the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.

NoteIn the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6, 4, 4, 0, 4, where number 4 occurs 3 times.In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5, 5, 5, if we increase each by one, we get 6, 6, 6. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3, 2, 2, 2, 2, where number 2 occurs 4 times.

import java.util.Scanner

object C extends App {
  val sc = new Scanner(System.in)
  val n: Long = sc.nextLong
  val k: Long = sc.nextLong
  val initial: List[Long] = (for {i <- 1L to n} yield sc.nextLong).sortWith(_ < _).toList
  // TODO: Use foldl instead of foldr.
  val pairs = (initial :\ List[(Long, Long)]()) {
    case (next, Nil) => (next, 1L) :: Nil
    case (next, (c, n) :: xs) if next == c => (c, n + 1L) :: xs
    case (next, xs) => (next, 1L) :: xs
  }
  //println("pairs = ", pairs)
  val answers = ((0L, 0L, -0x40000000L, k, 0L, pairs) /: pairs) {
    case ((record, rec_i, prev, left0, sum0, initial0), (next, count)) =>
      //println("loop1: ", record, rec_i, prev, left0, sum0, initial0.head, next, count)
      val left1 = left0 - sum0 * (next - prev)
      val pay_whole = Stream.iterate((initial0, left1, sum0 + count)) {
	case ((c_i, n_i)::inits, left, sum) =>
	  //println("loop2: ", record, rec_i, prev, left0, sum0, initial0.head, next, count, c_i, n_i, left, sum)
	  val diff = next - c_i
	  (inits, left + diff * n_i, sum - n_i)
      }
      // (item array, operations left, sum)
      val (next_array, left2, sum2) =
	pay_whole.zip(pay_whole.tail).find {
	  case (_, (xs, left, sum)) => left >= 0L} match {
	  case Some((((c_i, n_i)::inits, left, sum), _)) =>
	    //println("loop3: ", record, rec_i, prev, left0, sum0, initial0.head, next, count, c_i, n_i, left, sum)
	    val diff = next - c_i
	    if (diff == 0 || left >= 0) {  // happens on the start of the loop.
	      ((c_i, n_i)::inits, left, sum)
	    } else {
	      val to_erase = (-left + diff - 1) / diff
	      if (to_erase < n_i) {
		((c_i, n_i - to_erase)::inits, left + diff * to_erase, sum - to_erase)
	      } else {
		(inits, left + diff * n_i, sum - n_i)
	      }
	    }
	}
      assert (left2 >= 0L, {println("assert broken")})
      val (new_record:Long, new_rec_i:Long) =
	if (record < sum2) (sum2, next) else (record, rec_i)
      (new_record, new_rec_i, next, left2, sum2, next_array)
  }
  printf("%d %d\n", answers._1, answers._2)
}

object Olymp{
  def main(args: Array[String]): Unit = {
    val Array(n, k) = readLine split (' ') map (_ toInt)
    val p = (readLine split (' ') map (_ toLong)) sorted
    var l = 0
    var balance: Long = 0
    var cnt = 1
    var num = p(0)
    for(r <- 1 until n){
      balance += (r-l) * (p(r)-p(r-1))
      while(balance > k){
        balance -= (p(r)-p(l))
        l += 1
      }
      if (r-l+1 > cnt){
        cnt = r-l+1
        num = p(r)
      }
    }
    println(cnt+" "+num)
  }
}

object Olymp{
  def main(args: Array[String]): Unit = {
    val Array(n, k) = readLine split (' ') map (_ toInt)
    val p = (readLine split (' ') map (_ toInt)) sorted
    var l = 0
    var balance = 0
    var cnt = 1
    var num = p(0)
    for(r <- 1 until n){
      balance += (r-l) * (p(r)-p(r-1))
      while(balance > k){
        balance -= (p(r)-p(l))
        l += 1
      }
      if (r-l+1 > cnt){
        cnt = r-l+1
        num = p(r)
      }
    }
    println(cnt+" "+num)
  }
}


A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then:   first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group.  friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.

For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.

NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.

object _1729D extends CodeForcesApp {
  override def solve() = repeat() {
    val n = nextInt()
    val xs, ys = IndexedSeq.fill(n)(nextInt())
    val debt = (xs.zip(ys)).map({case (x, y) => y - x}).sorted

    var i = 0
    var j = n-1
    var ans = 0
    while(j > i) {
      if (debt(i) + debt(j) >= 0) {
        j -= 1
        ans += 1
      }
      i += 1
    }

    out.println(ans)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  import java.io._
  var in = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: String, res: => A): A = {out.println(query); out.flush(); res}

  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def illegal(msg: String = "can't happen") = throw new IllegalStateException(msg)

  def main(args: Array[String]): Unit = try solve() finally out.flush()
  def solve(): Any
}


Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart.Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.

The first line contains integer m (1 ≤ m ≤ 105) — the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 ≤ qi ≤ 105).  The third line contains integer n (1 ≤ n ≤ 105) — the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ 104) — the items' prices. The numbers in the lines are separated by single spaces.

In a single line print a single integer — the answer to the problem.

NoteIn the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  in.next()
  val q = in.next().split(' ').map(_.toInt).min
  in.next()
  val data = in.next().split(' ').map(_.toInt).sorted.reverse
  println(data.grouped(q + 2).map(_.take(q).sum).sum)
}


Polycarp has prepared $$$n$$$ competitive programming problems. The topic of the $$$i$$$-th problem is $$$a_i$$$, and some problems' topics may coincide.Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:  number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;  the total number of problems in all the contests should be maximized. Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems Polycarp has prepared. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) where $$$a_i$$$ is the topic of the $$$i$$$-th problem.

Print one integer — the maximum number of problems in the set of thematic contests.

NoteIn the first example the optimal sequence of contests is: $$$2$$$ problems of the topic $$$1$$$, $$$4$$$ problems of the topic $$$2$$$, $$$8$$$ problems of the topic $$$10$$$.In the second example the optimal sequence of contests is: $$$3$$$ problems of the topic $$$3$$$, $$$6$$$ problems of the topic $$$6$$$.In the third example you can take all the problems with the topic $$$1337$$$ (the number of such problems is $$$3$$$ so the answer is $$$3$$$) and host a single contest.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val C = mutable.Map[Int, Int]().withDefaultValue(0)

    rep(N) { i =>
      val a = A(i)
      C(a) += 1
    }

    val V = C.values.toArray
    radixSort(V)

    // 2^30はない
    val ans = map(min(V.length, 30), 1) { k =>
      val t = V.takeRight(k)
      rep(k) { i =>
        t(i) /= 1 << i
      }
      val x = t.min
      x.toLong * ((1 << k) - 1)
    }.max

    out.println(ans)
  }

  /**
    * 正の値のみのときだけ
    */
  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(as: Array[Int], n: Int): Array[Int] = {
    val n = as.length
    val xs = Array(as, new Array[Int](n))
    val b = Array.ofDim[Int](65537)

    def step(k: Int, x: Int): Unit = {
      rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }
      rep(65536, 1){ i => b(i) += b(i - 1) }
      rep(n){ i =>
        val j = xs(x)(i) >>> k & 0xffff
        xs(x ^ 1)(b(j)) = xs(x)(i)
        b(j) += 1
      }
    }

    step(0, 0)
    java.util.Arrays.fill(b, 0)
    step(16, 1)

    as
  }

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


You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills:  the matrix has a row with prime numbers only;  the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.

The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.

Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.

NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val lines = (1 to n).map(_ => in.next().split(' ').map(_.toInt))
  val max = lines.map(_.max).max

  def isPrime(a: Int) = a == 2 || (a != 1 && a % 2 != 0 && (3 until a by 2).forall(a % _ != 0))

  val nextPrime = Stream.from(max + 1 - max % 2, 2).find(isPrime).get
  val sieve = Array.ofDim[Boolean](nextPrime + 1)
  sieve(0) = true
  sieve(1) = true
  (2 until nextPrime).foreach{ j =>
    if (!sieve(j))
      (j * 2 until nextPrime by j).foreach(i => sieve(i) = true)
  }
  val set = scala.collection.immutable.TreeSet(sieve.indices.filterNot(sieve):_*)
  val smallLine = lines.foldLeft(Int.MaxValue){
    case(acc, line) => Math.min(acc, line.map(i => set.iteratorFrom(i).next() - i).sum)
  }
  val smallColumn = (0 until m).foldLeft(Int.MaxValue) {
    case(acc, i) => Math.min(acc, lines.map(_(i)).map(i => set.iteratorFrom(i).next() - i).sum)
  }

  println(Math.min(smallColumn, smallLine))
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._
import scala.collection.mutable.ArrayBuffer
import java.util.Arrays.binarySearch

object P271B extends App {

  object PrimeNumber {
    def apply(n: Int = 1000000): Array[Int] = sieve(n)

    def sieve(n: Int): Array[Int] = {
      val primes = new ArrayBuffer[Int]
      val isPrime = Array.fill(n + 1)(true)

      @tailrec
      def loop(i: Int): Unit = {

        @tailrec
        def innerLoop(j: Int): Unit = {
          if (j > n) ()
          else {
            isPrime(j) = false
            innerLoop(j + i)
          }
        }

        if (i > n) ()
        else {
          if (isPrime(i)) {
            primes += i
            innerLoop(i * 2)
          }
          loop(i + 1)
        }
      }

      loop(2)
      primes.toArray
    }
  }

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

  val Ps: Array[Int] = PrimeNumber(100003)

  val nextPrime: Int => Int = { x =>
    val i = binarySearch(Ps, x)
    if (i >= 0) x
    else Ps(-1 - i)
  }
  val numMove: Int => Int = { x => nextPrime(x) - x }

  val N, M = sc.nextInt
  val Matrix = List.fill(N, M)(numMove(sc.nextInt))
  val rowsAndCols = Matrix ++ Matrix.transpose
  val res = rowsAndCols.map(_.sum).min

  out.println(res)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._
import scala.collection.mutable.ArrayBuffer
import java.util.Arrays.binarySearch

object P271B extends App {

  object PrimeNumber {
    def apply(n: Int = 1000000): Array[Int] = sieve(n)

    def sieve(n: Int): Array[Int] = {
      val primes = new ArrayBuffer[Int]
      val isPrime = Array.fill(n + 1)(true)

      @tailrec
      def loop(i: Int): Unit = {

        @tailrec
        def innerLoop(j: Int): Unit = {
          if (j > n) ()
          else {
            isPrime(j) = false
            innerLoop(j + i)
          }
        }

        if (i > n) ()
        else {
          if (isPrime(i)) {
            primes += i
            innerLoop(i * 2)
          }
          loop(i + 1)
        }
      }

      loop(2)
      primes.toArray
    }
  }

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

  val Ps: Array[Int] = PrimeNumber(100003)

  val nextPrime: Int => Int = { x =>
    val i = binarySearch(Ps, x)
    if (i >= 0) x
    else Ps(-1 - i)
  }
  val numMove: Int => Int = { x => nextPrime(x) - x }

  val N, M = sc.nextInt
  val Matrix = Vector.fill(N, M)(numMove(sc.nextInt))
  val rowsAndCols = Matrix ++ Matrix.transpose
  val res = rowsAndCols.map(_.sum).min

  out.println(res)
  out.close
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object B
{
    def main(args: Array[String])
    {
        val MAXI = 200000
        val prePrimeBuffer = ArrayBuffer[Int]()
        val visit=new Array[Boolean](MAXI+1)
        prePrimeBuffer += 2
        for(i<-3 until MAXI by 2 if !visit(i))
        {
            prePrimeBuffer+=i
            var j=2
            while(i*j<=MAXI) {visit(i*j)=true;j+=1}
        }

        val prePrime = prePrimeBuffer toArray
        val Array(n,m) = readLine.split(" ").map(_.toInt)
        val mat = Array.ofDim[Int](n,m)

        for(i <- 0 until n)
        {
            mat(i) = readLine.split(" ").map(_.toInt)
        }
        val matT = mat.transpose
        //print(mat map (_ map ("%2d" format _) mkString " ") mkString "\n")

        def nextPrime(target:Int):Int={
            var i=0
            var j=prePrime.size-1
            while(i<j){
                val mid=(i+j)/2
                if(prePrime(mid)==target) return prePrime(mid)
                else if(prePrime(mid)<target) i=mid+1
                else j=mid
            }

            prePrime(i)
        }

        def slove(mm: Array[Array[Int]]): List[Int] =
        {
            val sz = mm.size
            val ans = for(i <- 0 until sz)
                    yield (mm(i).map((x) => (nextPrime(x) - x))).sum
            ans.toList
        }
        val aa = slove(mat)
        val bb = slove(matT)
        println(Array(aa.min,bb.min).min)
    }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val max=200000
    val ab=ArrayBuffer[Int]()
    val v=new Array[Boolean](max+1)
    ab+=2
    for(i<-3 until max by 2 if !v(i)){
        ab+=i
        var j=2
        while(i*j<=max) {v(i*j)=true;j+=1}
    }

    def next(target:Int):Int={
        var i=0
        var j=ab.size-1
        while(i<j){
            val mid=(i+j)/2
            if(ab(mid)==target) return ab(mid)
            else if(ab(mid)<target) i=mid+1
            else j=mid
        }

        ab(i)
    }

    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val mat=new Array[Array[Int]](n)

    for(i<-0 until n) mat(i)=readLine.split(" ").map(_.toInt).map(i=>next(i)-i)
    var min=(for(i<-0 until n) yield mat(i).sum).min
    min=math.min(min,(for(j<-0 until m) yield  (for(i<-0 until n) yield mat(i)(j)).sum).min)
    println(min)
}

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

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

  val Start = sc.nextInt

  def solve: Int = {
    @tailrec
    def loop(y: Int): Int =
      if (y.toString.groupBy(identity[Char]).size == 4) y
      else loop(y + 1)
    loop(Start + 1)
  }

  out.println(solve)
  out.close
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object B
{
    def main(args: Array[String])
    {
        val SIZE = 102400
        val sieve = Array.fill[Boolean](SIZE+5)(true)

        def prime_gen(x: Int): Unit =
        {
            if(sieve(x)) ((2 to SIZE/x) par) map {_ * x} map {sieve( _ ) = false}
            if(x+1 < SIZE) prime_gen(x+1)
        }

        def lower_bound(a: List[Int], l:Int, r:Int, v:Int): Int =
        {
            val mid = (l+r)>>1
            if(l>r) l
            else if(a(mid) < v) lower_bound(a, mid+1, r, v)
            else lower_bound(a, l, mid-1, v)
        }

        prime_gen(2)
        val prime_list = ((2 to SIZE) toList) filter {sieve(_)}
        val prime_list_len = prime_list.length

        val Array(n,m) = readLine.split(" ").map(_.toInt)
        val mat = Array.ofDim[Int](n,m)

        for(i <- 0 until n)
        {
            mat(i) = readLine.split(" ").map(_.toInt)
        }
        val matT = mat.transpose
        //print(mat map (_ map ("%2d" format _) mkString " ") mkString "\n")

        def nextPrime(v: Int): Int =
        {
            prime_list(lower_bound(prime_list,0,prime_list_len-1,v))
        }

        def slove(mm: Array[Array[Int]]): List[Int] =
        {
            val sz = mm.size
            val ans = ((1 until sz) par) map
                      {
                            mm(_) map
                            {
                                ((x) => (nextPrime(x) - x))
                            } sum
                      }
            ans.toList
        }

        val aa = slove(mat)
        val bb = slove(matT)
        println(Array(aa.min,bb.min).min)
    }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object B
{
    def main(args: Array[String])
    {
        val SIZE = 102400
		val sieve = Array.fill[Boolean](SIZE+5)(true)

		def prime_gen(x: Int): Unit =
		{
			if(sieve(x)) ((2 to SIZE/x) toList) map {_ * x} map {sieve( _ ) = false}
			if(x+1 < SIZE) prime_gen(x+1)
		}

		def upper_bound(a: List[Int], l:Int, r:Int, v:Int): Int =
		{
			val mid = (l+r)>>1
			if(l>r) l
			else if(a(mid) <= v) upper_bound(a, mid+1, r, v)
			else upper_bound(a, l, mid-1, v)
		}

		prime_gen(2)
		val prime_list = ((2 to SIZE) toList) filter {sieve(_)}
		val prime_list_len = prime_list.length

        val Array(n,m) = readLine.split(" ").map(_.toInt)
        val mat = Array.ofDim[Int](n,m)

        for(i <- 0 until n)
        {
            mat(i) = readLine.split(" ").map(_.toInt)
        }
        val matT = mat.transpose
        //print(mat map (_ map ("%2d" format _) mkString " ") mkString "\n")

		def nextPrime(v: Int): Int =
        {
			prime_list(upper_bound(prime_list,0,prime_list_len-1,v))
		}

        def slove(mm: Array[Array[Int]]): List[Int] =
        {
            val sz = mm.size
			val ans = for(i <- 0 until sz)
                    yield (mm(i).map((x) => (nextPrime(x) - x))).sum
            ans.toList
        }

        //println(nextPrime(3))

        val aa = slove(mat)
        val bb = slove(matT)
        println(Array(aa.min,bb.min).min)
    }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val max=100000
    val ab=ArrayBuffer[Int]()
    val v=new Array[Boolean](max+1)
    ab+=2
    for(i<-3 until max by 2 if !v(i)){
        ab+=i
        var j=2
        while(i*j<=max) {v(i*j)=true;j+=1}
    }

    def next(target:Int):Int={
        var i=0
        var j=ab.size-1
        while(i<j){
            val mid=(i+j)/2
            if(ab(mid)==target) return ab(mid)
            else if(ab(mid)<target) i=mid+1
            else j=mid
        }

        ab(i)
    }

    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val mat=new Array[Array[Int]](n)

    for(i<-0 until n) mat(i)=readLine.split(" ").map(_.toInt).map(i=>next(i)-i)
    var min=(for(i<-0 until n) yield mat(i).sum).min
    min=math.min(min,(for(j<-0 until m) yield  (for(i<-0 until n) yield mat(i)(j)).sum).min)
    println(min)
}


A string $$$s$$$ of length $$$n$$$ ($$$1 \le n \le 26$$$) is called alphabetical if it can be obtained using the following algorithm:  first, write an empty string to $$$s$$$ (i.e. perform the assignment $$$s$$$ := "");  then perform the next step $$$n$$$ times;  at the $$$i$$$-th step take $$$i$$$-th lowercase letter of the Latin alphabet and write it either to the left of the string $$$s$$$ or to the right of the string $$$s$$$ (i.e. perform the assignment $$$s$$$ := $$$c+s$$$ or $$$s$$$ := $$$s+c$$$, where $$$c$$$ is the $$$i$$$-th letter of the Latin alphabet). In other words, iterate over the $$$n$$$ first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string $$$s$$$ or append a letter to the right of the string $$$s$$$. Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".From the given string, determine if it is alphabetical.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is written on a separate line that contains one string $$$s$$$. String $$$s$$$ consists of lowercase letters of the Latin alphabet and has a length between $$$1$$$ and $$$26$$$, inclusive.

Output $$$t$$$ lines, each of them must contain the answer to the corresponding test case. Output YES if the given string $$$s$$$ is alphabetical and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer).

11
a
ba
ab
bac
ihfcbadeg
z
aa
ca
acb
xyz
ddcba

NoteThe example contains test cases from the main part of the condition.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()
    val n = s.length

    def go(i: Int, j: Int): Boolean =
      if (i == 0 && j == n - 1) true
      else if (i < 0 || j > n - 1) false
      else {
        val c = s(i) max s(j)

        if (i > 0 && s(i - 1) == c + 1) go(i - 1, j)
        else if (j < n - 1 && s(j + 1) == c + 1) go(i, j + 1)
        else false
      }

    val i = s.indexWhere(_ == 'a')

    go(i, i) match {
      case true => println("yes")
      case _    => println("no")
    }

  }
}