Recently, Masha was presented with a chessboard with a height of $$$n$$$ and a width of $$$m$$$.The rows on the chessboard are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. Therefore, each cell can be specified with the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number, and $$$y$$$ is the row number (do not mix up).Let us call a rectangle with coordinates $$$(a,b,c,d)$$$ a rectangle lower left point of which has coordinates $$$(a,b)$$$, and the upper right one — $$$(c,d)$$$.The chessboard is painted black and white as follows:   An example of a chessboard. Masha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat — they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled white paint on the rectangle $$$(x_1,y_1,x_2,y_2)$$$. Then after him Denis spilled black paint on the rectangle $$$(x_3,y_3,x_4,y_4)$$$.To spill paint of color $$$color$$$ onto a certain rectangle means that all the cells that belong to the given rectangle become $$$color$$$. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black).Masha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers!

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each of them is described in the following format: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^9$$$) — the size of the board. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1 \le x_2 \le m, 1 \le y_1 \le y_2 \le n$$$) — the coordinates of the rectangle, the white paint was spilled on. The third line contains four integers $$$x_3$$$, $$$y_3$$$, $$$x_4$$$, $$$y_4$$$ ($$$1 \le x_3 \le x_4 \le m, 1 \le y_3 \le y_4 \le n$$$) — the coordinates of the rectangle, the black paint was spilled on.

Output $$$t$$$ lines, each of which contains two numbers — the number of white and black cells after spilling paint, respectively.

NoteExplanation for examples:The first picture of each illustration shows how the field looked before the dyes were spilled. The second picture of each illustration shows how the field looked after Maxim spoiled white dye (the rectangle on which the dye was spilled is highlighted with red). The third picture in each illustration shows how the field looked after Denis spoiled black dye (the rectangle on which the dye was spilled is highlighted with red).In the first test, the paint on the field changed as follows:  In the second test, the paint on the field changed as follows:  In the third test, the paint on the field changed as follows:  In the fourth test, the paint on the field changed as follows:  In the fifth test, the paint on the field changed as follows:

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)

  case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)

  def solve(): Unit = {

    /**
      * @return (white, black)
      */
    def count(r: Rect): (Long, Long) = {
      val s = max(0, r.x2 - r.x1 + 1).toLong * max(0, r.y2 - r.y1 + 1)
      if (s == 0) (0, 0)
      else if (s % 2 == 0) (s / 2, s / 2)
      else {
        // 0 == white, 1 == black
        def tpe(x: Int, y: Int): Int = {
          if (y % 2 == 1) {
            if (x % 2 == 1) 0
            else 1
          } else {
            if (x % 2 == 1) 1
            else 0
          }
        }

        tpe(r.x1, r.y1) match {
          case 0 => (s / 2 + 1, s / 2)
          case 1 => (s / 2, s / 2 + 1)
        }
      }
    }

    rep(ni()) { _ =>
      val n, m = ni()
      val x1, y1, x2, y2 = ni()
      val x3, y3, x4, y4 = ni()

      val wRec = Rect(x1, y1, x2, y2)
      val bRec = Rect(x3, y3, x4, y4)

      val dupRec = {
        val l = max(x1, x3)
        val r = min(x2, x4)
        val b = max(y1, y3)
        val t = min(y2, y4)
        Rect(l, b, r, t)
      }

      val (bw, bb) = count(bRec)
      val (ww, wb) = count(wRec)
      val (dw, db) = count(dupRec)

      val s = n.toLong * m
      val b = s / 2 + bw - (wb - db)
      val w = s - b
      out.println(s"$w $b")
    }
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    rep(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    rep(n) { i =>
      rep(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

object C {

  case class Rect(x1: Long, y1: Long, x2: Long, y2: Long)

  def splitV1(r: Rect, x: Int) = {
    if (x >= r.x2 || x <= r.x1) {
      Array(r)
    } else {
      Array(r.copy(x2 = x), r.copy(x1=x))
    }
  }

  def splitH1(r: Rect, y: Int) = {
    if (y >= r.y2 || y <= r.y1) {
      Array(r)
    } else {
      Array(r.copy(y2 = y), r.copy(y1=y))
    }
  }

  def splitV(r: Array[Rect], x: Int) = {
    r.flatMap(r => splitV1(r, x))
  }

  def splitH(r: Array[Rect], y: Int) = {
    r.flatMap(r => splitH1(r, y))
  }

  def in(r: Rect, o: Rect) = {
    if (r.x2 <= o.x2 && r.x1 >= o.x1 && r.y2 <= o.y2 && r.y1 >= o.y1) true
    else false
  }

  def getWhites(r: Rect) = {
    val a = r.x2 - r.x1
    val b = r.y2 - r.y1
    val t = (a * b)
    if (t % 2 == 0) {
      t / 2
    } else {
      if ((r.x1 + r.y1) % 2 == 0) {
        t / 2 + 1
      } else {
        t / 2
      }
    }
  }

  def main(args: Array[String]) = {
    val scanner = new java.util.Scanner(System.in)
    val t = scanner.nextInt
    (0 until t).foreach{_ =>
      val (n, m) = (scanner.nextInt(), scanner.nextInt())
      val (x1,y1,x2,y2) = (scanner.nextInt(), scanner.nextInt(), scanner.nextInt(), scanner.nextInt())
      val (x3,y3,x4,y4) = (scanner.nextInt(), scanner.nextInt(), scanner.nextInt(), scanner.nextInt())
      var rects = Array(Rect(1, 1, m+1, n+1))
      rects = splitV(rects, x = x1)
      rects = splitV(rects, x = x2+1)
      rects = splitV(rects, x = x3)
      rects = splitV(rects, x = x4+1)
      rects = splitH(rects, y = y1)
      rects = splitH(rects, y = y2+1)
      rects = splitH(rects, y = y3)
      rects = splitH(rects, y = y4+1)
      val white = Rect(x1, y1, x2+1, y2+1)
      val black = Rect(x3, y3, x4+1, y4+1)
      val (w, b) = rects.map{r =>
        val s = (r.x2 - r.x1) * (r.y2 - r.y1)
        if (in(r, black)) {
          (0L, s)
        } else if (in(r, white)) {
          (s, 0L)
        } else {
          val w = getWhites(r)
          (w, s-w)
        }
      }.reduce((a, b) => (a._1 + b._1, a._2 + b._2))
      System.out.println(w + " " + b)
    }
  }
}

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)

  case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)

  def solve(): Unit = {

    /**
      * @return (white, black)
      */
    def count(r: Rect): (Long, Long) = {
      val s = (r.x2 - r.x1 + 1).toLong * (r.y2 - r.y1 + 1)
      if (s % 2 == 0) (s / 2, s / 2)
      else {
        // 0 == white, 1 == black
        def tpe(x: Int, y: Int): Int = {
          if (y % 2 == 1) {
            if (x % 2 == 1) 0
            else 1
          } else {
            if (x % 2 == 1) 1
            else 0
          }
        }

        tpe(r.x1, r.y1) match {
          case 0 => (s / 2 + 1, s / 2)
          case 1 => (s / 2, s / 2 + 1)
        }
      }
    }

    rep(ni()) { _ =>
      val n, m = ni()
      val x1, y1, x2, y2 = ni()
      val x3, y3, x4, y4 = ni()

      val wRec = Rect(x1, y1, x2, y2)
      val bRec = Rect(x3, y3, x4, y4)

      val dupRec = {
        val l = max(x1, x3)
        val r = min(x2, x4)
        val b = max(y1, y3)
        val t = min(y2, y4)
        Rect(l, b, r, t)
      }

      val (bw, bb) = count(bRec)
      val (ww, wb) = count(wRec)
      val (rw, rb) = count(dupRec)

      val s = n.toLong * m
      val b = s / 2 + bw - (wb - rb)
      val w = s - b
      out.println(s"$w $b")
    }
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    rep(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    rep(n) { i =>
      rep(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

  case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)

  def solve(): Unit = {

    /**
      * @return (white, black)
      */
    def count(r: Rect): (Long, Long) = {
      val s = (r.x2 - r.x1 + 1).toLong * (r.y2 - r.y1 + 1)
      if (s < 0) (0, 0)
      else if (s % 2 == 0) (s / 2, s / 2)
      else {
        // 0 == white, 1 == black
        def tpe(x: Int, y: Int): Int = {
          if (y % 2 == 1) {
            if (x % 2 == 1) 0
            else 1
          } else {
            if (x % 2 == 1) 1
            else 0
          }
        }

        tpe(r.x1, r.y1) match {
          case 0 => (s / 2 + 1, s / 2)
          case 1 => (s / 2, s / 2 + 1)
        }
      }
    }

    rep(ni()) { _ =>
      val n, m = ni()
      val x1, y1, x2, y2 = ni()
      val x3, y3, x4, y4 = ni()

      val wRec = Rect(x1, y1, x2, y2)
      val bRec = Rect(x3, y3, x4, y4)

      val dupRec = {
        val l = max(x1, x3)
        val r = min(x2, x4)
        val b = max(y1, y3)
        val t = min(y2, y4)
        Rect(l, b, r, t)
      }

      val (bw, bb) = count(bRec)
      val (ww, wb) = count(wRec)
      val (dw, db) = count(dupRec)

      val s = n.toLong * m
      val b = s / 2 + bw - (wb - db)
      val w = s - b
      out.println(s"$w $b")
    }
  }

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


Diamond Miner is a game that is similar to Gold Miner, but there are $$$n$$$ miners instead of $$$1$$$ in this game.The mining area can be described as a plane. The $$$n$$$ miners can be regarded as $$$n$$$ points on the y-axis. There are $$$n$$$ diamond mines in the mining area. We can regard them as $$$n$$$ points on the x-axis. For some reason, no miners or diamond mines can be at the origin (point $$$(0, 0)$$$). Every miner should mine exactly one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point $$$(a,b)$$$ uses his hook to mine a diamond mine at the point $$$(c,d)$$$, he will spend $$$\sqrt{(a-c)^2+(b-d)^2}$$$ energy to mine it (the distance between these points). The miners can't move or help each other.The object of this game is to minimize the sum of the energy that miners spend. Can you find this minimum?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of miners and mines. Each of the next $$$2n$$$ lines contains two space-separated integers $$$x$$$ ($$$-10^8 \le x \le 10^8$$$) and $$$y$$$ ($$$-10^8 \le y \le 10^8$$$), which represent the point $$$(x,y)$$$ to describe a miner's or a diamond mine's position. Either $$$x = 0$$$, meaning there is a miner at the point $$$(0, y)$$$, or $$$y = 0$$$, meaning there is a diamond mine at the point $$$(x, 0)$$$. There can be multiple miners or diamond mines at the same point. It is guaranteed that no point is at the origin. It is guaranteed that the number of points on the x-axis is equal to $$$n$$$ and the number of points on the y-axis is equal to $$$n$$$. It's guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, print a single real number — the minimal sum of energy that should be spent. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}$$$.

NoteIn the first test case, the miners are at $$$(0,1)$$$ and $$$(0,-1)$$$, while the diamond mines are at $$$(1,0)$$$ and $$$(-2,0)$$$. If you arrange the miners to get the diamond mines in the way, shown in the picture, you can get the sum of the energy $$$\sqrt2 + \sqrt5$$$.

import scala.annotation.tailrec
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.math.sqrt

object diamond_miner extends App {

    @tailrec def solve_case(cases_left: Int): Unit = {
        val n: Int = readInt
        var miners: Array[Long] = Array.fill(n){0L}
        var mines: Array[Long] = Array.fill(n){0L}
        var (i, j): (Int, Int) = (0, 0)

        @tailrec def get_pos(positions_left: Int): Unit = {
            val p: Array[Long] = readLine.split(' ').map(_.toLong)
            if(p(0) == 0) {
                miners(i) = p(1).abs
                i += 1
            }
            else {
                mines(j) = p(0).abs
                j += 1
            }

            if(positions_left > 0)
                get_pos(positions_left - 1)
        }

        get_pos(2 * n - 1)

        println(miners.sorted.zip(mines.sorted).map(x => sqrt(x._1 * x._1 + x._2 * x._2)).foldLeft(.0)(_ + _))

        if(cases_left > 0)
            solve_case(cases_left - 1)
    }

    val t: Int = readInt
    solve_case(t - 1)
}


There are $$$n$$$ piranhas with sizes $$$a_1, a_2, \ldots, a_n$$$ in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them.Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely:   The piranha $$$i$$$ can eat the piranha $$$i-1$$$ if the piranha $$$i-1$$$ exists and $$$a_{i - 1} < a_i$$$.  The piranha $$$i$$$ can eat the piranha $$$i+1$$$ if the piranha $$$i+1$$$ exists and $$$a_{i + 1} < a_i$$$. When the piranha $$$i$$$ eats some piranha, its size increases by one ($$$a_i$$$ becomes $$$a_i + 1$$$).Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas.Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them.For example, if $$$a = [5, 3, 4, 4, 5]$$$, then the third piranha can be dominant. Consider the sequence of its moves:   The piranha eats the second piranha and $$$a$$$ becomes $$$[5, \underline{5}, 4, 5]$$$ (the underlined piranha is our candidate).  The piranha eats the third piranha and $$$a$$$ becomes $$$[5, \underline{6}, 5]$$$.  The piranha eats the first piranha and $$$a$$$ becomes $$$[\underline{7}, 5]$$$.  The piranha eats the second piranha and $$$a$$$ becomes $$$[\underline{8}]$$$. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of piranhas in the aquarium. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the size of the $$$i$$$-th piranha. It is guaranteed that the sum of $$$n$$$ does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).

For each test case, print the answer: -1 if there are no dominant piranhas in the aquarium or index of any dominant piranha otherwise. If there are several answers, you can print any.

NoteThe first test case of the example is described in the problem statement.In the second test case of the example, there are no dominant piranhas in the aquarium.In the third test case of the example, the fourth piranha can firstly eat the piranha to the left and the aquarium becomes $$$[4, 4, 5, 4]$$$, then it can eat any other piranha in the aquarium.

//package codeforces.contests._1433

object DominantPiranha {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val n = io.StdIn.readInt()

      val digits = io.StdIn.readLine.split(" ").map(_.toInt)

      val max = digits.max

      val result = (0 until n).filter(digits(_) == max).find { i =>
        (i - 1 >= 0 && digits(i - 1) != max) || (i + 1 < n && digits(i + 1) != max)
      }.getOrElse(-2) + 1

      println {
        result
      }
    }
  }
}


As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.

The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.

Print a single number — the maximum size of a clique in a divisibility graph for set A.

NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.

import scala.collection._

object F 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 maxA = as.max

  val indexOf = Array.fill(maxA + 1){ -1 }
  for (i <- as.indices) indexOf(as(i)) = i

  val res = Array.fill(n){ 1 }

  for (i <- as.indices) {
    val a = as(i)
    val resI1 = res(i) + 1
    var aa = a + a
    while (aa <= maxA) {
      val j = indexOf(aa)
      if (j >= 0 && resI1 > res(j)) res(j) = resI1
      aa += a
    }
  }

  println(res.max)
}


Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle:  its vertices have integer coordinates,  the coordinates of vertices are non-negative, and  its vertices are not on a single line. He calls a point on the downtown's border (that is the border of the triangle) safe if he can reach this point from at least one point of the line $$$y = 0$$$ walking along some straight line, without crossing the interior of the triangle.  In the picture the downtown is marked with grey color. The first path is invalid because it does not go along a straight line. The second path is invalid because it intersects with the interior of the downtown. The third and fourth paths are correct. Find the total length of the unsafe parts of the downtown border. It can be proven that these parts are segments and their number is finite.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. Each test case contains three lines, each of them contains two integers $$$x_i$$$, $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^9$$$) — coordinates of the vertices of the downtown's border.

For each test case print a single number — the answer to the problem. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally let your answer be $$$a$$$, jury answer be $$$b$$$. Your answer will be considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}$$$.

NoteIn the picture, the downtowns of the first three test cases are illustrated. Triangles are enumerated according to the indices of test cases they belong to.  In the first two test cases, all points on the borders of the downtowns are safe, thus the answers are $$$0$$$.In the following picture unsafe points for the third test case are marked with black color:  In the fourth test case, all points on the border of the downtown are safe.

object Solution{
  def main(args: Array[String])={
    val T = scala.io.StdIn.readLine().toInt
    var p1 =  new Array[List[Int]](T)
    var p2 =  new Array[List[Int]](T)
    var p3 =  new Array[List[Int]](T)
    var results = new Array[Int](T)
    for(k <- 0 until T)
    {
        p1(k) = ((scala.io.StdIn.readLine().split(" ")).map(_.toInt)).toList
        p2(k) = ((scala.io.StdIn.readLine().split(" ")).map(_.toInt)).toList
        p3(k) = ((scala.io.StdIn.readLine().split(" ")).map(_.toInt)).toList
    }
    for (k <- 0 until T)
    {
      results(k) = 0
      if( p1(k)(1) == p2(k)(1) && p1(k)(1) > p3(k)(1))
      {
        results(k) = (p1(k)(0) - p2(k)(0)).abs
      }
      if( p1(k)(1) == p3(k)(1) && p1(k)(1) > p2(k)(1))
      {
        results(k) = (p1(k)(0) - p3(k)(0)).abs
      }
      if( p3(k)(1) == p2(k)(1) && p3(k)(1) > p1(k)(1))
      {
        results(k) = (p2(k)(0) - p3(k)(0)).abs
      }
    }
    for( k <- 0 until T)
    {
      println(results(k))
    }
  }
}


The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $$$s$$$, which can be represented as a binary string, in which the $$$i$$$-th symbol is '1' if students will write the contest in the $$$i$$$-th day and '0' if they will have a day off.At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $$$t$$$ (which can be described in the same format as schedule $$$s$$$). Since the number of days in the current may be different from number of days in schedule $$$t$$$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $$$t$$$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.Could you rearrange the schedule in the best possible way?

The first line contains string $$$s$$$ ($$$1 \leqslant |s| \leqslant 500\,000$$$), denoting the current project of the camp's schedule. The second line contains string $$$t$$$ ($$$1 \leqslant |t| \leqslant 500\,000$$$), denoting the optimal schedule according to Gleb. Strings $$$s$$$ and $$$t$$$ contain characters '0' and '1' only.

In the only line print the schedule having the largest number of substrings equal to $$$t$$$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $$$s$$$ and the number of ones should be equal to the number of ones in $$$s$$$. In case there multiple optimal schedules, print any of them.

NoteIn the first example there are two occurrences, one starting from first position and one starting from fourth position.In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $$$t$$$ wouldn't change.In the third example it's impossible to make even a single occurrence.

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

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

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

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

  def solve(): Unit = {
    val S, T = ns()
    val N = S.length
    val M = T.length

    var cs1 = S.count(_ == '1')
    var cs0 = N - cs1
    var ct1 = T.count(_ == '1')
    var ct0 = M - ct1

    debug(s"$ct1 $ct0")

    val kmp = new KMP(T)
    val pos = kmp.kmp(M)
    val ct1_2 = T.drop(pos).count(_ == '1')
    val ct0_2 = M - pos - ct1_2

    debug(s"$ct1_2 $ct0_2")

    var first = true
    var t = T
    while(cs1 >= ct1 && cs0 >= ct0) {
      out.print(t)
      cs1 -= ct1
      cs0 -= ct0

      if (first) {
        ct1 = ct1_2
        ct0 = ct0_2
        first = false
        t = T.drop(pos)
      }
    }
    REP(cs0) { _ =>
      out.print(0)
    }
    REP(cs1) { _ =>
      out.print(1)
    }
    out.println()

  }

  class KMP(word: String) {
    val kmp: Array[Int] = Array.ofDim[Int](word.length + 1)
    2 to word.length foreach { i =>
      // kmp(i-1)以下しか参照されないからOK
      kmp(i) = longestSuffix(kmp(i - 1), word(i - 1))
    }

    debug(kmp)

    def findFirst(text: String): Int = {
      var j = 0
      REP(text.length) { i =>
        j = longestSuffix(j, text(i))
        if (j == word.length) return i - word.length + 1
      }
      -1
    }

    def longestSuffix(matched: Int, c: Char): Int = {
      var j = matched
      var continues = true
      while(continues) {
        if (word(j) == c) {
          j += 1
          continues = false
        } else if (j == 0) continues = false
        else j = kmp(j)
      }
      j
    }
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugNum(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 = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

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

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

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

  def solve(): Unit = {
    val S, T = ns()
    val N = S.length
    val M = T.length
    val cntS1 = S.count(_ == '1')
    val cntS0 = N - cntS1
    val cntT1 = T.count(_ == '1')
    val cntT0 = M - cntT1

    val r1 = if (cntT1 == 0) 1e9.toInt else cntS1 / cntT1
    val r0 = if (cntT0 == 0) 1e9.toInt else cntS0 / cntT0
    val ts = min(N / M, min(r1, r0))
    debug(s"ts $ts")
    val one = cntS1 - cntT1 * ts
    REP(N - ts * M - one) { _ =>
      out.print(0)
    }
    REP(one) { _ =>
      out.print(1)
    }
    REP(ts) { _ =>
      out.print(T)
    }
    out.println()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugNum(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 = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

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

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

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

  def solve(): Unit = {
    val S, T = ns()
    val N = S.length
    val M = T.length

    var cs1 = S.count(_ == '1')
    var cs0 = N - cs1
    val ct1 = T.count(_ == '1')
    val ct0 = M - ct1

    while(cs1 >= ct1 && cs0 >= ct0) {
      out.print(T)
      cs1 -= ct1
      cs0 -= ct0
    }
    REP(cs0) { _ =>
      out.print(0)
    }
    REP(cs1) { _ =>
      out.print(1)
    }
    out.println()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugNum(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 = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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


Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.On that night, Sengoku constructed a permutation p1, p2, ..., pn of integers from 1 to n inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with n meteorids, colours of which being integer sequences a1, a2, ..., an and b1, b2, ..., bn respectively. Meteoroids' colours were also between 1 and n inclusive, and the two sequences were not identical, that is, at least one i (1 ≤ i ≤ n) exists, such that ai ≠ bi holds.Well, she almost had it all — each of the sequences a and b matched exactly n - 1 elements in Sengoku's permutation. In other words, there is exactly one i (1 ≤ i ≤ n) such that ai ≠ pi, and exactly one j (1 ≤ j ≤ n) such that bj ≠ pj.For now, Sengoku is able to recover the actual colour sequences a and b through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.

The first line of input contains a positive integer n (2 ≤ n ≤ 1 000) — the length of Sengoku's permutation, being the length of both meteor outbursts at the same time. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the sequence of colours in the first meteor outburst. The third line contains n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ n) — the sequence of colours in the second meteor outburst. At least one i (1 ≤ i ≤ n) exists, such that ai ≠ bi holds.

Output n space-separated integers p1, p2, ..., pn, denoting a possible permutation Sengoku could have had. If there are more than one possible answer, output any one of them. Input guarantees that such permutation exists.

NoteIn the first sample, both 1, 2, 5, 4, 3 and 1, 2, 3, 4, 5 are acceptable outputs.In the second sample, 5, 4, 2, 3, 1 is the only permutation to satisfy the constraints.

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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

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

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

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

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

    override def toString = s"MultiHashSet($map)"
  }

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

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

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

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

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

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

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def test(ans: Array[Int], a: Array[Int]): Boolean = {
    var diff = 0
    for (i <- 0 until ans.length) {
      if (ans(i) != a(i)) {
        diff += 1
      }
    }
    diff == 1
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    val set = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      b(i) = nextInt
      set += (i + 1)
    }
    val ans = new Array[Int](n)
    for (i <- 0 until n) {
      if (a(i) == b(i)) {
        ans(i) = a(i)
        set -= (ans(i))
      }
    }
    val firstPos = ans.indexOf(0)
    val remains = set.iterator.toList
    if (set.size == 1) {
      ans(firstPos) = remains.head
    } else if (set.size == 2) {
      ans(firstPos) = remains.head
      val lastPos = ans.lastIndexOf(0)
      ans(lastPos) = remains.last
      if (test(ans, a) && test(ans, b)) {
      } else {
        ans(firstPos) = remains.last
        ans(lastPos) = remains.head
      }
    }
    ans.foreach(x => print(s"$x "))
    return 0
  }
}

object EightOneFourB {
  def checkIfAllElementPresent(seq: Seq[Int]): Boolean = {
    val list = (1 to seq.size + 1).toArray.map(_ => 0)
    list(0) = 1
    seq.foreach(p => list(p) = 1)
    list.filter(_ == 0).size == 0
  }

  def findTheMissingElement(seq: Seq[Int]): Option[Int] = {
    val list = (1 to seq.size + 1).toArray.map(_ => 0)
    list(0) = 1
    seq.foreach(p => list(p) = 1)
    val result = list.zipWithIndex.filter(p => p._1 == 0)
    if (result.size > 0) Some(result.head._2) else None
  }

  def main(args: Array[String]): Unit = {
    val input = readLine()
    val stringA = readLine().toString.split(" ").map(_.toInt)
    val stringB = readLine().toString.split(" ").map(_.toInt)
    val missingAElement = findTheMissingElement(stringA)
    val missingBElement = findTheMissingElement(stringB)

    val permutations = stringA.zip(stringB).zipWithIndex
      .filter {
        case ((a, b), index) => {
          a != b
        }
      }
      .flatMap {
        case ((a, b), index) => {
          List(stringA.patch(index, List(missingAElement.getOrElse(a)), 1)
            , stringB.patch(index, List(missingBElement.getOrElse(b)), 1))
        }
      }

    println(permutations
      .filter(checkIfAllElementPresent(_))
      .filter(stringA.zip(_).filter(p => p._1 != p._2).size <= 1)
      .filter(stringB.zip(_).filter(p => p._1 != p._2).size <= 1)
      .head.mkString(" "))
  }
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  type Lin3st = List[(Int,Int,Int)]
  /*  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
      (a,b) match {
        case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
        case (Nil, Nil) => Nil
      }
    } // перекодено
   def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
   val t = b.splitAt(idx)
   t._1 ++ List(byWhat) ++ t._2.tail
  } //перекодено*/
def repl(b:Linst,e:Int,idx:Int):Linst = b.foldRight[(Linst,Int)](Nil,b.length-1)((i,T) => ((if(T._2 == idx) e else i) :: T._1,T._2 - 1))._1
def findDrop(b:Linst) = nats.filter(v => !b.contains(v)).head
def dupExists(d:Linst, e: Int, p:Int) = d.foldLeft[(Boolean,Int)]((false,0))((T,i) => (if(T._1)true else i == e && p != T._2,T._2 + 1))._1
/*  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
 b match {
   case Nil => false
   case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
   case a :: tail => existsDup(tail, num, pos, currPos + 1)
 }
}//перекодено
def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
   val nats = Stream.from(1,1).take(a.length).toList
   val drop = nats.filter(v => !a.contains(v)).head
   replace(a, drop, pos - 1)
 } // перекодено
 def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
   val nats = Stream.from(1,1).take(a.length).toList
   val drop = nats.filter(v => !a.contains(v)).head
   if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)
   else replace(a, drop, pos2 - 1)
 } // на очереди*/
def fixTransp2(a:Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) = repl(a,findDrop(a), if(dupExists(a,num1,pos1)) pos1 else pos2)
val n = StdIn.readLine().toInt
val nats = Stream.from(1,1).take(n).toList
val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
val diff = A.foldLeft[(Lin3st,Linst,Int)]((Nil,B,0))((T,i)=>(if(T._2.head != i)(i,T._2.head,T._3) :: T._1 else T._1,T._2.tail,T._3+1))._1
println((if(diff.length == 1) repl(A,findDrop(A),diff.head._3)
else if(diff.head._2 == diff.tail.head._2) fixTransp2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)
else fixTransp2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)).mkString(" "))
/*val AB = for(
 i <- nats;
 a <- A;
 b <- B
) yield (a,b,i)*/

/* val diff = findDifferences(A,B,1)
println(
diff.length match {
 case 1 => fixTransposition(A, diff.head._1, diff.head._3).mkString(" ")
 case 2 => {if(diff.head._2 == diff.tail.head._2)fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)
            else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)}.mkString(" ")

}
)*/
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
    (a,b) match {
      case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
      case (Nil, Nil) => Nil
    }
  }
  def printList(a: Linst):Any ={
    a match{
      case Nil => None
      case b::tail => print(b + " "); printList(tail)
    }
  }
  def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
    val t = b.splitAt(idx)
    t._1 ++ List(byWhat) ++ t._2.tail
  }
  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
    b match {
      case Nil => false
      case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
      case a :: tail => existsDup(tail, num, pos, currPos + 1)
    }
  }
  def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    replace(a, drop, pos - 1)
  }
  def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)
    else replace(a, drop, pos2 - 1)
  }
  val n = StdIn.readLine().toInt
  val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val diff = findDifferences(A,B,1)
  println()
  diff.length match {
    case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))
    case 2 => {if(diff.head._2 == diff.tail.head._2)printList(fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3))
               else printList(fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3))}

  }
}

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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

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

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

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

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

    override def toString = s"MultiHashSet($map)"
  }

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

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

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

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

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

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

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    val set = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      b(i) = nextInt
      set += (i + 1)
    }
    val ans = new Array[Int](n)
    for (i <- 0 until n) {
      if (a(i) == b(i)) {
        ans(i) = a(i)
        set -= (ans(i))
      }
    }
    if (set.size == 1) {
      ans(ans.indexOf(0)) = set.iterator.toList.head
    } else if (set.size == 2) {
      ans(ans.indexOf(0)) = set.iterator.toList.head
      ans(ans.lastIndexOf(0)) = set.iterator.toList.last
    } else {
      throw new RuntimeException()
    }
    ans.foreach(x => print(s"$x "))
    return 0
  }
}

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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

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

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

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

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

    override def toString = s"MultiHashSet($map)"
  }

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

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

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

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

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

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

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def test(ans: Array[Int], a: Array[Int]): Boolean = {
    var diff = 0
    for (i <- 0 until ans.length) {
      if (ans(i) != a(i)) {
        diff += 1
      }
    }
    diff == 1
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    val set = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      b(i) = nextInt
      set += (i + 1)
    }
    val ans = new Array[Int](n)
    for (i <- 0 until n) {
      if (a(i) == b(i)) {
        ans(i) = a(i)
        set -= (ans(i))
      }
    }
    val firstPos = ans.indexOf(0)
    val remains = set.iterator.toList
    if (set.size == 1) {
      ans(firstPos) = remains.head
    } else if (set.size == 2) {
      ans(firstPos) = remains.head
      val lastPos = ans.lastIndexOf(0)
      ans(lastPos) = remains.last
      if (test(ans, a) || test(ans, b)) {
        ans(firstPos) = remains.last
        ans(lastPos) = remains.head
      }
    }
    ans.foreach(x => print(s"$x "))
    return 0
  }
}

object EightOneFourB {
  def checkIfAllElementPresent(seq: Seq[Int]): Boolean = {
    val list = (1 to seq.size + 1).toArray.map(_ => 0)
    list(0) = 1
    seq.foreach(p => list(p) = 1)
    list.filter(_ == 0).size == 0
  }

  def findTheMissingElement(seq: Seq[Int]): Option[Int] = {
    val list = (1 to seq.size + 1).toArray.map(_ => 0)
    list(0) = 1
    seq.foreach(p => list(p) = 1)
    val result = list.zipWithIndex.filter(p => p._1 == 0)
    if (result.size > 0) Some(result.head._2) else None
  }

  def main(args: Array[String]): Unit = {
    val input = readLine()
    val stringA = readLine().toString.split(" ").map(_.toInt)
    val stringB = readLine().toString.split(" ").map(_.toInt)
    val missingAElement = findTheMissingElement(stringA)
    val missingBElement = findTheMissingElement(stringB)

    val permutations = stringA.zip(stringB).zipWithIndex
      .filter {
        case ((a, b), index) => {
          a != b
        }
      }
      .flatMap {
        case ((a, b), index) => {
          List(stringA.patch(index, List(missingAElement.getOrElse(a)), 1)
            , stringB.patch(index, List(missingBElement.getOrElse(b)), 1))
        }
      }

    println(permutations.filter(checkIfAllElementPresent(_)).head.mkString(" "))
  }
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
    (a,b) match {
      case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
      case (Nil, Nil) => Nil
    }
  }
  def printList(a: Linst):Any ={
    a match{
      case Nil => None
      case b::tail => print(b + " "); printList(tail)
    }
  }
  def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
    val t = b.splitAt(idx)
    t._1 ++ List(byWhat) ++ t._2.tail
  }
  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
    b match {
      case Nil => false
      case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
      case a :: tail => existsDup(tail, num, pos, currPos + 1)
    }
  }
  def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    replace(a, drop, pos - 1)
  }
  def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)
    else replace(a, drop, pos2 - 1)
  }
  def check(a: Linst, p: Linst, i1: Int):Boolean ={
    if( a.isEmpty) i1 == 1
    else if(a.head != p.head) check(a.tail, p.tail, i1 + 1)
    else check(a.tail, p.tail, i1 + 1)
  }
  val n = StdIn.readLine().toInt
  val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val diff = findDifferences(A,B,1)
  println()
  diff.length match {
    case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))
    case 2 => printList({
      val v1 = fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)
      if(check(A,v1,0) && check(B,v1,0)) v1 else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)
    })
  }
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
    (a,b) match {
      case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
      case (Nil, Nil) => Nil
    }
  }
  def printList(a: Linst):Any ={
    a match{
      case Nil => None
      case b::tail => print(b + " "); printList(tail)
    }
  }
  def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
    val t = b.splitAt(idx)
    t._1 ++ List(byWhat) ++ t._2.tail
  }
  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
    b match {
      case Nil => false
      case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
      case a :: tail => existsDup(tail, num, pos, currPos + 1)
    }
  }
  def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    replace(a, drop, pos - 1)
  }
  def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    if (num1 == drop) replace(a, drop, pos1 - 1)
    else replace(a, drop, pos2 - 1)
  }
  def check(a: Linst, p: Linst, i1: Int):Boolean ={
    if( a.isEmpty) i1 == 1
    else if(a.head != p.head) check(a.tail, p.tail, i1 + 1)
    else check(a.tail, p.tail, i1 + 1)
  }
  val n = StdIn.readLine().toInt
  val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val diff = findDifferences(A,B,1)
  println()
  diff.length match {
    case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))
    case 2 => printList({
      val v1 = fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)
      if(check(A,v1,0) && check(B,v1,0)) v1 else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)
    })
  }
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
    (a,b) match {
      case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
      case (Nil, Nil) => Nil
    }
  }
  def printList(a: Linst):Any ={
    a match{
      case Nil => None
      case b::tail => print(b + " "); printList(tail)
    }
  }
  def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
    val t = b.splitAt(idx)
    t._1 ++ List(byWhat) ++ t._2.tail
  }
  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
    b match {
      case Nil => false
      case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
      case a :: tail => existsDup(tail, num, pos, currPos + 1)
    }
  }
  def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    replace(a, drop, pos - 1)
  }
  def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)
    else replace(a, drop, pos2 - 1)
  }
  val n = StdIn.readLine().toInt
  val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val diff = findDifferences(A,B,1)
  println()
  diff.length match {
    case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))
    case 2 => printList(fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3))
  }
}


You are given a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.A substring of string $$$s$$$ is a continuous segment of letters from $$$s$$$. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it.Let's call some string of length $$$n$$$ diverse if and only if there is no letter to appear strictly more than $$$\frac n 2$$$ times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.Your task is to find any diverse substring of string $$$s$$$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the length of string $$$s$$$. The second line is the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.

Print "NO" if there is no diverse substring in the string $$$s$$$. Otherwise the first line should contain "YES". The second line should contain any diverse substring of string $$$s$$$.

NoteThe first example has lots of correct answers. Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to "No comments" answer.

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 S = ns(N)
    val cum  = Array.ofDim[Int](26, N + 1)
    rep(N) { i =>
      val c = S(i)
      rep(cum.length) { j =>
        cum(j)(i + 1) = cum(j)(i) + (if (c == 'a' + j) 1 else 0)
      }
    }

    def calc: Option[String] = {
      rep(N) { l =>
        l + 1 to N foreach { r =>
          var ok = true
          rep(26) { j =>
            val len = r - l
            val cnt = cum(j)(r) - cum(j)(l)
            ok &= cnt * 2 <= len
          }
          if (ok) return Some(S.slice(l, r).mkString)
        }
      }
      None
    }

    calc match {
      case Some(s) =>
        out.println("YES")
        out.println(s)

      case None =>
        out.println("NO")
    }
  }

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


ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.When ZS the Coder is at level k, he can :  Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k. Press the '' button. Let the number on the screen be x. After pressing this button, the number becomes . After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5.ZS the Coder needs your help in beating the game — he wants to reach level n + 1. In other words, he needs to press the '' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses.

The first and only line of the input contains a single integer n (1 ≤ n ≤ 100 000), denoting that ZS the Coder wants to reach level n + 1.

Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '' button at level i.  Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.

NoteIn the first sample case:On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14·1 = 16. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16·2 = 36. Then, ZS pressed the '' button, levelling up and changing the number into .After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46·3 = 144. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4.Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10·3 = 36, and when the '' button is pressed, the number becomes  and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution.In the second sample case:On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998·1 = 1018. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 109 + 44500000000·2 = 9·1010. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3.

//package merofeev.contests.codeforces.rnd372

import java.util.Scanner

/**
  * @author erofeev
  * @since 17.09.16
  */
object CSqrt {

  def nextNum(x: Long, k: Int): BigInt = {
    var nextNum = 1L
    var i = k.toLong
    val kksqr: Long = k * (k + 1).toLong
//    val pos1: BigInt = k * BigInt(k + 1).pow(2)
    val pos: BigInt = BigInt(kksqr).pow(2) //8100 = (k^2 * (k + 1)^2). we want 900 = k * (k+1)^2
    return pos
//    val posSquare: BigInt = pos / k //900
//    if ((pos1 % (k * k))  != 0 ) {
//      return pos
//    }
//    return pos1
    val nextKPow: Long = (k + 1) * (k + 1)
    while (true) {
      nextNum = i * i
      if (
      //        nextNum % k == 0 &&
        nextNum % nextKPow == 0
          && (nextNum - x) % k == 0) {
        return nextNum
      }
      i += 1
    }
    throw new IllegalStateException(k + "")
  }

  def main(args: Array[String]): Unit = {
                val need = new Scanner(System.in).nextInt()
//    val need = 1000
    var k = 1L
    while (k <= need) {
//      val nextX: BigInt = nextNum(x, k)
//      val steps: BigInt = (nextX - x) / k
//      println(k + " " + nextX + "=> " + steps + " steps " + (k + 1) + " lvl")
      if (k == 1) {
        println(2)
      } else {
        println(k * (k + 1) * (k + 1) - (k - 1))
      }
      k += 1
    }
  }
}

object C extends App {

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

  val Array(n) = readInts(1)
  var x = BigInt(2)

  val res = Array.ofDim[BigInt](n + 1)

  for (k <- 1L to n) {
    val k1 = k + 1
    val k1k1 = k1 * k1

    val y = k * k1k1 - x / k
    //val y = z / k
    res(k.toInt) = y
    x = k * k1
  }

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

  println(res.drop(1).mkString("\n"))

  Console.flush
}

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

object _716C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val ans = solve3(n+1)
    writeAll(ans)
  }

  def solve2(goal: Int): Seq[BigInt] = {
    var ans = mutable.ArrayBuffer.empty[BigInt]
    var display = 2L

    var n = 2
    while(n <= goal) {
      val ns = BigInt(n) * n

      val f = (Iterator.from(1) find {i =>
        val target = ns * i * i
        val pushes = target - display
        pushes >= 0 && pushes%(n-1) == 0
      }).get

      debug(n, f, display)

      ans += ((BigInt(f) * f * n * n) - display)/(n-1)
      //debug(n, f, ans.last, display, f.toLong * n)
      display = f.toLong * n
      n += 1
    }
    ans
  }

  def solve3(goal: Int): Seq[BigInt] = {
    var ans = mutable.ArrayBuffer.empty[BigInt]
    var display = 2L

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

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

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

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

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

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

  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 = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

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

//package merofeev.contests.codeforces.rnd372

/**
  * @author erofeev
  * @since 17.09.16
  */
object CSqrt {

  def nextNum(x: Long, k: Int): Long = {
    var nextNum = 1L
    var i = k.toLong
    val kksqr: Long = k * (k + 1).toLong
    return kksqr * kksqr
    val nextKPow: Long = (k + 1) * (k + 1)
    while (true) {
      nextNum = i * i
      if (
      //        nextNum % k == 0 &&
        nextNum % nextKPow == 0
          && (nextNum - x) % k == 0) {
        return nextNum
      }
      i += 1
    }
    throw new IllegalStateException(k + "")
  }

  def main(args: Array[String]): Unit = {
    //        val need = new Scanner(System.in).nextInt()
    val need = 100
    var k = 1
    var x = 2L
    while (k <= need) {
      val nextX: Long = nextNum(x, k)
      val steps: Long = (nextX - x) / k
      //      println(k + " " + nextX + "=> " + steps + " steps " + (k + 1) + " lvl")
      println(steps)
      x = Math.sqrt(nextX).toLong
      k += 1
    }
  }
}

//package merofeev.contests.codeforces.rnd372

import java.util.Scanner

/**
  * @author erofeev
  * @since 17.09.16
  */
object CSqrt {

  def nextNum(x: Long, k: Int): BigInt = {
    var nextNum = 1L
    var i = k.toLong
    val kksqr: Long = k * (k + 1).toLong
    return BigInt(kksqr).pow(2)
    val nextKPow: Long = (k + 1) * (k + 1)
    while (true) {
      nextNum = i * i
      if (
      //        nextNum % k == 0 &&
        nextNum % nextKPow == 0
          && (nextNum - x) % k == 0) {
        return nextNum
      }
      i += 1
    }
    throw new IllegalStateException(k + "")
  }

  def main(args: Array[String]): Unit = {
            val need = new Scanner(System.in).nextInt()
//    val need = 1000000
    var k = 1
    var x = 2L
    while (k <= need) {
      val nextX: BigInt = nextNum(x, k)
      val steps: BigInt = (nextX - x) / k
//      val steps: Long = (nextX - x) / k
//      println(k + " " + nextX + "=> " + steps + " steps " + (k + 1) + " lvl")
            println(steps)
      x = k * (k + 1)
      k += 1
    }
  }
}

//package merofeev.contests.codeforces.rnd372

import java.util.Scanner

/**
  * @author erofeev
  * @since 17.09.16
  */
object CSqrt {

  def nextNum(x: Long, k: Int): BigInt = {
    var nextNum = 1L
    var i = k.toLong
    val kksqr: Long = k * (k + 1).toLong
//    val pos1: BigInt = k * BigInt(k + 1).pow(2)
    val pos: BigInt = BigInt(kksqr).pow(2) //8100 = (k^2 * (k + 1)^2). we want 900 = k * (k+1)^2
    return pos
//    val posSquare: BigInt = pos / k //900
//    if ((pos1 % (k * k))  != 0 ) {
//      return pos
//    }
//    return pos1
    val nextKPow: Long = (k + 1) * (k + 1)
    while (true) {
      nextNum = i * i
      if (
      //        nextNum % k == 0 &&
        nextNum % nextKPow == 0
          && (nextNum - x) % k == 0) {
        return nextNum
      }
      i += 1
    }
    throw new IllegalStateException(k + "")
  }

  def main(args: Array[String]): Unit = {
                val need = new Scanner(System.in).nextInt()
//    val need = 1000
    var k = 1
    var x = 2L
    while (k <= need) {
      val nextX: BigInt = nextNum(x, k)
      val steps: BigInt = (nextX - x) / k
//      println(k + " " + nextX + "=> " + steps + " steps " + (k + 1) + " lvl")
                  println(steps)
      x = k * (k + 1)
      k += 1
    }
  }
}


We get more and more news about DDoS-attacks of popular websites.Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds $$$100 \cdot t$$$, where $$$t$$$ — the number of seconds in this time segment. Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence $$$r_1, r_2, \dots, r_n$$$, where $$$r_i$$$ — the number of requests in the $$$i$$$-th second after boot. Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment $$$[1, n]$$$.

The first line contains $$$n$$$ ($$$1 \le n \le 5000$$$) — number of seconds since server has been booted. The second line contains sequence of integers $$$r_1, r_2, \dots, r_n$$$ ($$$0 \le r_i \le 5000$$$), $$$r_i$$$ — number of requests in the $$$i$$$-th second.

Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.

import java.io.FileInputStream
import scala.io.StdIn

object ProblemB extends App {
//  System.setIn(new FileInputStream("inputs/test01.in"))
  val n = StdIn.readLine().trim.toInt
  val r = StdIn.readLine().trim.split("\\s+").map(_.toInt)
  val ps = {val (b, c) = ((Vector.empty[Long], 0L) /: r) ((pr, cr) => (pr._1 :+ pr._2, pr._2 + cr)); b :+ c}
  var a = 0
  for (i <- 0.to(n); j <- i.to(n)) {
    val s = ps(j) - ps(i)
    val t = j - i
    if (s > 100L * t) a = math.max(a, t)
  }
  println(a)
}