Ashish and Vivek play a game on a matrix consisting of $$$n$$$ rows and $$$m$$$ columns, where they take turns claiming cells. Unclaimed cells are represented by $$$0$$$, while claimed cells are represented by $$$1$$$. The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.

The first line consists of a single integer $$$t$$$ $$$(1 \le t \le 50)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — the number of rows and columns in the matrix. The following $$$n$$$ lines consist of $$$m$$$ integers each, the $$$j$$$-th integer on the $$$i$$$-th line denoting $$$a_{i,j}$$$ $$$(a_{i,j} \in \{0, 1\})$$$.

For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes).

NoteFor the first case: One possible scenario could be: Ashish claims cell $$$(1, 1)$$$, Vivek then claims cell $$$(2, 2)$$$. Ashish can neither claim cell $$$(1, 2)$$$, nor cell $$$(2, 1)$$$ as cells $$$(1, 1)$$$ and $$$(2, 2)$$$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $$$(1, 1)$$$, the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell $$$(2, 3)$$$, Vivek will have no moves left.

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val mn = readIntLine()
      val grid = (1 to mn.head).map(_ => readIntLine()).toList
      val min = Math.min(mn.head - calc(grid), mn.last - calc(grid.transpose))
      println(if (min % 2 == 0) "Vivek" else "Ashish")
    }
  }

  def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))

  def calcCols(grid: List[List[Int]]): Int = {
    val arr = Array.ofDim[Boolean](grid.head.length)
    grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))
    arr.count(i => i)
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

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

  for (_ <- 1 to nextInt) {
    val n, m = nextInt
    val xs = Array.fill(n)(nextInts(m))
    val ux = Array.fill(m)(false)
    val uy = Array.fill(n)(false)
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (xs(i)(j) == 1) {
          uy(i) = true
          ux(j) = true
        }
      }
    }

    val cx = m - ux.count(identity)
    val cy = n - uy.count(identity)
    val moves = Math.min(cx, cy)
    val res = if (moves % 2 == 1) "Ashish" else "Vivek"

    out.println(res)

    out.flush()
  }

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

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

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val (row, col) = (0 until n).foldLeft((List.fill(m)(0), List.empty[Int])) {
      case ((row, col), _) =>
        val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        (row.zip(a).map { case (p, q) => p + q }, a.sum :: col)
    }

    val free = row.count(_ == 0) min col.count(_ == 0)

    val ans =
      if (free % 2 == 0) "Vivek"
      else "Ashish"

    println(ans)
  }
}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val mn = readIntLine()
      val grid = (1 to mn.head).map(_ => readIntLine()).toList
      val min = Math.min(calc(grid), calc(grid.transpose))
      println(if (min % 2 == 0) "Vivek" else "Ashish")
    }
  }

  def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))

  def calcCols(grid: List[List[Int]]): Int = {
    val arr = Array.ofDim[Boolean](grid.head.length)
    grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))
    arr.count(i => i)
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val mn = readIntLine()
      val grid = (1 to mn.head).map(_ => readIntLine()).toList
      val min = Math.min(calc(grid), calcCols(grid))
      println(if (min % 2 == 0) "Vivek" else "Ashish")
    }
  }

  def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))

  def calcCols(grid: List[List[Int]]): Int = {
    val arr = Array.ofDim[Boolean](grid.head.length)
    grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))
    arr.count(i => i)
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}


Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$.    An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d < n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.

Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).

NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.

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, D, M = ni()
    val F = Array.fill[Boolean](N + 1, N + 1)(true)
    rep(N + 1) { i =>
      val l = abs(D - i)
      val r = abs(N - D - i)
      rep(l) { j =>
        F(i)(j) = false
      }
      rep(r) { j =>
        F(i)(N - j) = false
      }
    }

    rep(M) { _ =>
      val x, y = ni()
      out.println(if (F(y)(x)) "YES" else "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
  }
}

import scala.io.StdIn

object Problem1030B {
  def main(args: Array[String]): Unit = {
    val vals = StdIn.readLine().split(" ").map(_.toInt)
    val n = vals(0)
    val d = vals(1)
    val m = StdIn.readInt()
    val coords = for (i <- 0 until m) yield {
      val coords = StdIn.readLine().split(" ").map(_.toInt)
      (coords(0), coords(1))
    }
    print(solve(n, d, coords).mkString("\n"))
  }
  def solve(n: Int, d: Int, coords: Seq[(Int, Int)]): Seq[String] = {
    coords.map(coord => {
      val (x, y) = coord
      solve(n, d, x, y)
    }).map(if (_) {
      "YES"
    } else {
      "NO"
    })
  }

  def solve(n: Int, d: Int, x: Int, y: Int): Boolean = {
    if (x + y < d || x + y > 2 * n - d) {
      false
    } else if (x - y < -d || x - y > d) {
      false
    } else {
      true
    }
  }
}


Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them.The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points (x1, y1) and (x2, y2).Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the i-th mouse is equal to (vix, viy), that means that the x coordinate of the mouse increases by vix units per second, while the y coordinates increases by viy units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are strictly inside the mousetrap.Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of computer mice on the desk. The second line contains four integers x1, y1, x2 and y2 (0 ≤ x1 ≤ x2 ≤ 100 000), (0 ≤ y1 ≤ y2 ≤ 100 000) — the coordinates of the opposite corners of the mousetrap. The next n lines contain the information about mice. The i-th of these lines contains four integers rix, riy, vix and viy, (0 ≤ rix, riy ≤ 100 000,  - 100 000 ≤ vix, viy ≤ 100 000), where (rix, riy) is the initial position of the mouse, and (vix, viy) is its speed.

In the only line print minimum possible non-negative number t such that if Igor closes the mousetrap at t seconds from the beginning, then all the mice are strictly inside the mousetrap. If there is no such t, print -1. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6.  Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteHere is a picture of the first samplePoints A, B, C, D - start mice positions, segments are their paths.Then, at first time when all mice will be in rectangle it will be looks like this:Here is a picture of the second samplePoints A, D, B will never enter rectangle.

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (u1 - ru.toDouble) / vu
      val t2 = (u2 - ru.toDouble) / vu
      val lt = t1 max t2
      val et = (t1 min t2) max 0
      if (et <= lt) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      } else maxT = -1
      //      println(t1, t2, minT, maxT)
    } else if (ru <= u1.min(u2) || ru >= u1.max(u2)) maxT = -1 //standing outside

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT < maxT) {
    println(f"$minT%.7f")
  } else println("-1")
}

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (u1 - ru.toDouble) / vu
      val t2 = (u2 - ru.toDouble) / vu
      val lt = t1 max t2
      val et = (t1 min t2) max 0
      if (et <= lt) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      }
      //      println(t1, t2, minT, maxT)
    } else if (ru <= u1.min(u2) || ru >= u1.max(u2)) maxT = -1 //standing outside

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT < maxT) {
    println(f"$minT%.7f")
  } else println("-1")
}

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (ru.toDouble - u1).abs / vu
      val t2 = (ru.toDouble - u2).abs / vu
      val lt = t1 max t2 max 0
      val et = t1 min t2
      if (et < lt + eps) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      }
//      println(t1, t2, minT, maxT)
    }

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT <= maxT + eps) {
    println(f"$minT%.7f")
  } else println("-1")
}

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (ru.toDouble - u1).abs / vu
      val t2 = (ru.toDouble - u2).abs / vu
      val lt = t1 max t2 max 0
      val et = t1 min t2
      if (et < lt + eps) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      }
//      println(t1, t2, minT, maxT)
    }

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT < maxT + eps) {
    println(f"$minT%.7f")
  } else println("-1")
}

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (ru.toDouble - u1).abs / vu
      val t2 = (ru.toDouble - u2).abs / vu
      val lt = t1 max t2 max 0
      val et = t1 min t2
      if (et < lt + eps) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      }
//      println(t1, t2, minT, maxT)
    }

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT < maxT + eps) {
    println(f"${(minT + maxT) / 2}%.7f")
  } else println("-1")
}

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (u1 - ru.toDouble) / vu
      val t2 = (u2 - ru.toDouble) / vu
      val lt = t1 max t2
      val et = (t1 min t2) max 0
      if (et <= lt) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      }
      //      println(t1, t2, minT, maxT)
    } else if (ru < u1.min(u2) || ru > u1.max(u2)) maxT = -1 //standing outside

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT < maxT) {
    println(f"$minT%.7f")
  } else println("-1")
}

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (u1 - ru.toDouble) / vu
      val t2 = (u2 - ru.toDouble) / vu
      val lt = t1 max t2
      val et = (t1 min t2) max 0
      if (et <= lt + eps) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      }
      //      println(t1, t2, minT, maxT)
    } else if (ru < u1.min(u2) || ru > u1.max(u2)) maxT = -1 //standing outside

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT <= maxT + eps) {
    println(f"$minT%.7f")
  } else println("-1")
}

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (u1 - ru.toDouble) / vu
      val t2 = (u2 - ru.toDouble) / vu
      val lt = t1 max t2
      val et = t1 min t2
      if (et >= 0) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      }
//      println(t1, t2, minT, maxT)
    }

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT <= maxT + eps) {
    println(f"$minT%.7f")
  } else println("-1")
}

import io.StdIn.readLine

object C extends App {
  val n = readLine.toInt
  var minT = 0.0
  var maxT = Double.MaxValue
  val eps = 1e-7
  val Array(x1, y1, x2, y2) = readLine.split(' ').map(_.toInt)

  def check(ru: Int, vu: Int, u1: Int, u2: Int): Unit =
    if (vu != 0) {
      val t1 = (u1 - ru.toDouble) / vu
      val t2 = (u2 - ru.toDouble) / vu
      val lt = t1 max t2
      val et = t1 min t2
      if (et >= 0) {
        if (minT < et) minT = et
        if (maxT > lt) maxT = lt
      }
      //      println(t1, t2, minT, maxT)
    } else if (ru < u1.min(u2) || ru > u1.max(u2)) maxT = -1 //standing outside

  for (i <- 1 to n) {
    val Array(rx, ry, vx, vy) = readLine.split(' ').map(_.toInt)

    check(rx, vx, x1, x2)
    check(ry, vy, y1, y2)
  }

  if (minT <= maxT + eps) {
    println(f"$minT%.7f")
  } else println("-1")
}


The legend of the foundation of Vectorland talks of two integers $$$x$$$ and $$$y$$$. Centuries ago, the array king placed two markers at points $$$|x|$$$ and $$$|y|$$$ on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points $$$|x - y|$$$ and $$$|x + y|$$$ and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland.Here $$$|z|$$$ denotes the absolute value of $$$z$$$.Now, Jose is stuck on a question of his history exam: "What are the values of $$$x$$$ and $$$y$$$?" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. Now, he wants to know the number of unordered pairs formed by two different elements from these $$$n$$$ integers such that the legend could be true if $$$x$$$ and $$$y$$$ were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)  — the number of choices. The second line contains $$$n$$$ pairwise distinct integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the choices Jose is considering.

Print a single integer number — the number of unordered pairs $$$\{x, y\}$$$ formed by different numbers from Jose's choices that could make the legend true.

NoteConsider the first sample. For the pair $$$\{2, 5\}$$$, the situation looks as follows, with the Arrayland markers at $$$|2| = 2$$$ and $$$|5| = 5$$$, while the Vectorland markers are located at $$$|2 - 5| = 3$$$ and $$$|2 + 5| = 7$$$:  The legend is not true in this case, because the interval $$$[2, 3]$$$ is not conquered by Vectorland. For the pair $$$\{5, -3\}$$$ the situation looks as follows, with Arrayland consisting of the interval $$$[3, 5]$$$ and Vectorland consisting of the interval $$$[2, 8]$$$:  As Vectorland completely contains Arrayland, the legend is true. It can also be shown that the legend is true for the pair $$$\{2, -3\}$$$, for a total of two pairs.In the second sample, the only pair is $$$\{3, 6\}$$$, and the situation looks as follows:  Note that even though Arrayland and Vectorland share $$$3$$$ as endpoint, we still consider Arrayland to be completely inside of Vectorland.

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

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

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

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

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

  def solve(): Unit = {
    val N = ni()
    val A = Array.ofDim[Int](N)
    REP(N) { i =>
      A(i) = abs(ni())
    }
    sort(A)

    debug(A)

    var ans = 0L
    REP(N) { i =>
      val x = A(i)
      if (x != 0) {
        // x < y
        val cntY = upperBound(A, x * 2) - (i + 1)
        debug(s"x:$x cntY:$cntY")
        ans += cntY
      }
    }

    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    import scala.util.Sorting
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

  // 要はcountLe
  // a > x  [x-2, x-1, x, x, x, x+1] の 5
  def upperBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) > x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }
}

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

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

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

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

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

  def solve(): Unit = {
    val N = ni()
    val A = Array.ofDim[Int](N)
    REP(N) { i =>
      A(i) = abs(ni())
    }
    sort(A)

    debug(A)

    var ans = 0L
    REP(N) { i =>
      val x = A(i)
      if (x == 0) {
        ans += N - (i + 1)
      } else {
        // x < y
        val cntY = upperBound(A, x * 2) - (i + 1)
        debug(s"x:$x cntY:$cntY")
        ans += cntY
      }
    }

    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    import scala.util.Sorting
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

  // 要はcountLe
  // a > x  [x-2, x-1, x, x, x, x+1] の 5
  def upperBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) > x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }
}


Fox Ciel is playing a card game with her friend Jiro.Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.Now is Ciel's battle phase, Ciel can do the following operation many times:  Choose one of her cards X. This card mustn't be chosen before.  If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then:   If Y's position is Attack, then (X's strength)  ≥  (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength).  If Y's position is Defense, then (X's strength)  >  (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage.  Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of cards Jiro and Ciel have. Each of the next n lines contains a string position and an integer strength (0 ≤ strength ≤ 8000) — the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense. Each of the next m lines contains an integer strength (0 ≤ strength ≤ 8000) — the strength of Ciel's current card.

Output an integer: the maximal damage Jiro can get.

NoteIn the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.In the second test case, she should use the "1001" card to attack the "ATK 100" card, then use the "101" card to attack the "ATK 10" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.In the third test case note that she can destroy the "ATK 0" card by a card with strength equal to 0, but she can't destroy a "DEF 0" card with that card.

object D extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val ys = Array.ofDim[(Char, Int)](n)
  val xs = Array.ofDim[Int](m)

  for (i <- 0 until n) ys(i) = readString.split(" ") match {
    case Array("ATK", x) => ('a', x.toInt)
    case Array("DEF", x) => ('d', x.toInt)
  }

  val yas = ys.filter(_._1 == 'a').map(_._2).sorted
  val yds = ys.filter(_._1 == 'd').map(_._2).sorted

  for (i <- 0 until m) xs(i) = readString.toInt

  var points1 = 0
  val xs1 = xs.sorted
  var di = 0
  var ai = 0

  for (x <- xs1) {
     if (di < yds.length && x > yds(di)) {
       di += 1
     } else if (ai < yas.length && x >= yas(ai)) {
       points1 += x - yas(ai)
       ai += 1
     } else points1 += x
  }

  if (di < yds.length || ai < yas.length) points1 = 0

  var points2 = 0
  ai = 0

  for (x <- xs1.reverse) {
    if (ai < yas.length && x >= yas(ai)) {
       points2 += x - yas(ai)
       ai += 1
     }
  }

  println(points1 max points2)
}

object D extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val ys = Array.ofDim[(Char, Int)](n)
  val xs = Array.ofDim[Int](m)

  for (i <- 0 until n) ys(i) = readString.split(" ") match {
    case Array("ATK", x) => ('a', x.toInt)
    case Array("DEF", x) => ('d', x.toInt)
  }

  val yas = ys.filter(_._1 == 'a').map(_._2).sorted
  val yds = ys.filter(_._1 == 'd').map(_._2).sorted

  for (i <- 0 until m) xs(i) = readString.toInt

  var points1 = 0
  val xs1 = xs.sorted
  var di = 0
  var ai = 0

  for (x <- xs) {
     if (di < yds.length && x > yds(di)) {
       di += 1
     } else if (ai < yas.length && x >= yas(ai)) {
       points1 += x - yas(ai)
       ai += 1
     } else points1 += x
  }

  if (di < yds.length || ai < yas.length) points1 = 0

  var points2 = 0
  ai = 0

  for (x <- xs.reverse) {
    if (ai < yas.length && x >= yas(ai)) {
       points2 += x - yas(ai)
       ai += 1
     }
  }

  println(points1 max points2)
}


A function  is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≤ K·|x - y| holds for all . We'll deal with a more... discrete version of this term.For an array , we define it's Lipschitz constant  as follows:  if n < 2,   if n ≥ 2,  over all 1 ≤ i < j ≤ n In other words,  is the smallest non-negative integer such that |h[i] - h[j]| ≤ L·|i - j| holds for all 1 ≤ i, j ≤ n.You are given an array  of size n and q queries of the form [l, r]. For each query, consider the subarray ; determine the sum of Lipschitz constants of all subarrays of .

The first line of the input contains two space-separated integers n and q (2 ≤ n ≤ 100 000 and 1 ≤ q ≤ 100) — the number of elements in array  and the number of queries respectively. The second line contains n space-separated integers  (). The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1 ≤ li < ri ≤ n).

Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer — the sum of Lipschitz constants of all subarrays of .

NoteIn the first query of the first sample, the Lipschitz constants of subarrays of  with length at least 2 are:       The answer to the query is their sum.

object D{
  //import scala.collection.mutable.PriorityQueue
  import scala.collection.mutable.Stack
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,q)=(nextInt,nextInt)
    var h0=nextInt
    val dh=Array.ofDim[Long](n-1)
    for(i<-0 until n-1) {
      val h=nextInt
      dh(i)=math.abs(h-h0)
      h0=h
    }
    //get a,b
    val a,b=Array.ofDim[Int](n-1)
    val st=new Stack[Int]()
    a(0)= -1
    st.push(0)
    for(i<-1 until n-1){

      while(!st.isEmpty && dh(st.top)<dh(i)){
        st.pop

      }
      if(st.isEmpty){
        a(i)= -1

      }else if(dh(st.top)==dh(i)){
        a(i)=st.top
        st.pop
      }
      else{
        a(i)=st.top
      }
      st.push(i)
    }
    val st2=new Stack[Int]()
    b(n-2)=n-1
    st2.push(n-2)
    for(i<- n-3 to 0 by -1){
      while(!st2.isEmpty && dh(st2.top)<=dh(i)){
        st2.pop
      }
      if(st2.isEmpty){
        b(i)=n-1
      }else{
        b(i)=st2.top
      }
      st2.push(i)
    }

    for(i<-0 until q){
      val l=nextInt-1
      val r=nextInt-2
      var sum=0L
      for(i<-l to r){
        val a0=math.max(l-1,a(i))
        val b0=math.min(r+1,b(i))
        sum+=dh(i)*(i-a0)*(b0-i)
      }
      out.println(sum)
    }

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

object D{
  //import scala.collection.mutable.PriorityQueue
  import scala.collection.mutable.Stack
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,q)=(nextInt,nextInt)
    var h0=nextInt
    val dh=Array.ofDim[Int](n-1)
    for(i<-0 until n-1) {
      val h=nextInt
      dh(i)=math.abs(h-h0)
      h0=h
    }
    //get a,b
    val a,b=Array.ofDim[Int](n-1)
    val st=new Stack[Int]()
    a(0)= -1
    st.push(0)
    for(i<-1 until n-1){

      while(!st.isEmpty && dh(st.top)<dh(i)){
        st.pop

      }
      if(st.isEmpty){
        a(i)= -1

      }else if(dh(st.top)==dh(i)){
        a(i)=st.top
        st.pop
      }
      else{
        a(i)=st.top
      }
      st.push(i)
    }
    val st2=new Stack[Int]()
    b(n-2)=n-1
    st2.push(n-2)
    for(i<- n-3 to 0 by -1){
      while(!st2.isEmpty && dh(st2.top)<=dh(i)){
        st2.pop
      }
      if(st2.isEmpty){
        b(i)=n-1
      }else{
        b(i)=st2.top
      }
      st2.push(i)
    }

    for(i<-0 until q){
      val l=nextInt-1
      val r=nextInt-2
      var sum=0L
      for(i<-l to r){
        val a0=math.max(l-1,a(i))
        val b0=math.min(r+1,b(i))
        sum+=(i-a0)*(b0-i)*dh(i)
      }
      out.println(sum)
    }

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

object D{
  //import scala.collection.mutable.PriorityQueue
  import scala.collection.mutable.Stack
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,q)=(nextInt,nextInt)
    var h0=nextInt
    val dh=Array.ofDim[Long](n-1)
    for(i<-0 until n-1) {
      val h=nextInt
      dh(i)=math.abs(h-h0)
      h0=h
    }
    //get a,b
    val a,b=Array.ofDim[Int](n-1)
    val st=new Stack[Int]()
    a(0)= -1
    st.push(0)
    for(i<-1 until n-1){

      while(!st.isEmpty && dh(st.top)<dh(i)){
        st.pop

      }
      if(st.isEmpty){
        a(i)= -1

      }else if(dh(st.top)==dh(i)){
        a(i)=st.top
        st.pop
      }
      else{
        a(i)=st.top
      }
      st.push(i)
    }
    val st2=new Stack[Int]()
    b(n-2)=n-1
    st2.push(n-2)
    for(i<- n-3 to 0 by -1){
      while(!st2.isEmpty && dh(st2.top)<=dh(i)){
        st2.pop
      }
      if(st2.isEmpty){
        b(i)=n-1
      }else{
        b(i)=st2.top
      }
      st2.push(i)
    }

    for(i<-0 until q){
      val l=nextInt-1
      val r=nextInt-2
      var sum=0L
      for(i<-l to r){
        val a0=math.max(l-1,a(i))
        val b0=math.min(r+1,b(i))
        sum+=(i-a0)*(b0-i)*dh(i)
      }
      out.println(sum)
    }

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


Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

import scala.io.Source

object Solution extends App {
  def count(height: IndexedSeq[Int], i: Int): Int = {
    val left = (i - 1 to 0 by -1).find(j => height(j) > height(j + 1))
    val right = (i + 1 until height.length).find(j => height(j) > height(j - 1))
    if (left.isEmpty)
      right.getOrElse(n)
    else
      right.getOrElse(n) - 1 - left.get
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val height = in.next().split(' ').map(_.toInt)
//  println((0 until n).map(i => count(height, i)))
  println((0 until n).map(i => count(height, i)).max)
}

object Main
{
	def countareas(areas:Array[Int], a:Int):Int =
	{
		var i = a
		var j = a
		while(i > 0 && areas(i - 1) <= areas(i)) i -= 1
		while(j < areas.length - 1 && areas(j + 1) <= areas(j)) j += 1
		return j - i + 1
	}

	def main(args:Array[String])
	{
		readInt;
		val a = readLine.split(" ").map(i => i.toInt)
		println((0 until a.length).map(i => countareas(a, i)).max)
	}
}


Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.He has a special interest to create difficult problems for others to solve. This time, with many $$$1 \times 1 \times 1$$$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $$$n \times m$$$ matrix, such that in each cell $$$(i,j)$$$, there are $$$h_{i,j}$$$ bricks standing on the top of each other.However, Serval doesn't give you any $$$h_{i,j}$$$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $$$m$$$ columns, and in the $$$i$$$-th of them, the height is the maximum of $$$h_{1,i},h_{2,i},\dots,h_{n,i}$$$. It is similar for the left view, where there are $$$n$$$ columns. And in the top view, there is an $$$n \times m$$$ matrix $$$t_{i,j}$$$, where $$$t_{i,j}$$$ is $$$0$$$ or $$$1$$$. If $$$t_{i,j}$$$ equals $$$1$$$, that means $$$h_{i,j}>0$$$, otherwise, $$$h_{i,j}=0$$$.However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?

The first line contains three positive space-separated integers $$$n, m, h$$$ ($$$1\leq n, m, h \leq 100$$$) — the length, width and height. The second line contains $$$m$$$ non-negative space-separated integers $$$a_1,a_2,\dots,a_m$$$, where $$$a_i$$$ is the height in the $$$i$$$-th column from left to right of the front view ($$$0\leq a_i \leq h$$$). The third line contains $$$n$$$ non-negative space-separated integers $$$b_1,b_2,\dots,b_n$$$ ($$$0\leq b_j \leq h$$$), where $$$b_j$$$ is the height in the $$$j$$$-th column from left to right of the left view. Each of the following $$$n$$$ lines contains $$$m$$$ numbers, each is $$$0$$$ or $$$1$$$, representing the top view, where $$$j$$$-th number of $$$i$$$-th row is $$$1$$$ if $$$h_{i, j}>0$$$, and $$$0$$$ otherwise. It is guaranteed that there is at least one structure satisfying the input.

Output $$$n$$$ lines, each of them contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.

Note  The graph above illustrates the object in the first example.    The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of it.

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

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

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

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._

  case class Entry(ix: Int, v: Int, isFront: Boolean)
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    import java.util.Comparator
    val n, m, h = ni()
    val front = na(m)
    val left = na(n)
    val top = nm(n, m)
    val ans = Array.fill[Int](n, m)(-1)
    val E = Array.ofDim[Entry](n + m)
    REP(m) { i =>
      E(i) = Entry(i, front(i), isFront = true)
    }
    REP(n) { i =>
      E(m + i) = Entry(i, left(i), isFront = false)
    }
    sort(E, new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o1.v, o2.v)
    })

    debug(E.mkString(" "))

    REP(E.length) { ii =>
      val e = E(ii)
      if (e.v > 0) {
        if (E(ii).isFront) {
          val j = e.ix
          REP(n) { i =>
            if (ans(i)(j) == -1 && top(i)(j) == 1) {
              ans(i)(j) = e.v
            }
          }
        } else {
          val i = e.ix
          REP(m) { j =>
            if (ans(i)(j) == -1 && top(i)(j) == 1) {
              ans(i)(j) = e.v
            }
          }
        }
      }
    }
    debugDim(ans)

    REP(n) { i =>
      REP(m) { j =>
        if (ans(i)(j) == -1) ans(i)(j) = 0
      }
    }
    REP(n) { i =>
      out.println(ans(i).mkString(" "))
    }
  }
}

import scala.collection.mutable
import scala.io.StdIn

object CodeForces2 extends App {

  val Array(n, m, h) = readLine().split(" ").map(_.toInt)

  val front = readLine().split(" ").map(_.toInt)
  val left = readLine().split(" ").map(_.toInt)

  var i = 0
  var lines = mutable.Buffer[String]()
  while (i < n) {
    val line = readLine().split(" ").map(_.toInt)
    var j = 0
    while (j < line.length) {
      line(j) = line(j) * Math.min(front(j), left(i))
      j += 1
    }
    lines += line.mkString(" ")
    i += 1
  }

  lines.foreach(println)

  def println(x: Any): Unit = {
    Console.println(x)
    Console.flush()
  }

  def readLine(): String = StdIn.readLine()
}

import scala.io.StdIn

object Codeforces1153B {

  def getBrickHeights(n: Int, m: Int, maxHeight: Int, a: Seq[Int], b: Seq[Int], h: Seq[Seq[Int]]): Seq[Seq[Int]] = {
    (0 until n).map(i => {
      (0 until m).map(j => {
        val value = math.min(a(j), b(i))
        if (h(i)(j) == 1) value else 0
      })
    })
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m, maxHeight) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)
    val b = StdIn.readLine().trim.split(" ").map(_.toInt)
    val h = (1 to n).map(_ => StdIn.readLine().trim.split(" ").map(_.toInt).toSeq)
    val gridHeights = getBrickHeights(n, m, maxHeight, a, b, h)
    for (rowHeights <- gridHeights) {
      for (cell <- rowHeights) {
        print(cell + " ")
      }
      println()
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val in = io.Source.stdin.getLines()
    val Array(n, m, h) = in.next().split(" ").map(_.toInt)

    val front = in.next().split(" ").map(_.toInt)
    val left = in.next().split(" ").map(_.toInt)

    val heights = Array.ofDim[Int](n,m)
    (0 until n).foreach { i =>
      heights(i) = in.next().split(" ").map(_.toInt)
    }

    val answer = Array.ofDim[Int](n,m)

    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (heights(i)(j) == 0) {
          answer(i)(j) = 0
        } else {
          answer(i)(j) = Math.min(Math.max(heights(i)(j), left(i)), Math.max(heights(i)(j), front(j)))
        }
      }
    }

    for (i <- 0 until n) {
      println(answer(i).mkString(" "))
    }

  }
}


Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.You are to determine the total number of times Vasily takes the top card from the deck.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), where ai is the number written on the i-th from top card in the deck.

Print the total number of times Vasily takes the top card from the deck.

NoteIn the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards.

import scala.collection.mutable

object E extends App {

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

  class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val as = readInts(n)
  val max = as.max
  val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }

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

  val positionsByA = positionBuilders.map(_.result)

  val bit = new BIT(Array.fill(n){ 0 })
  for (i <- 0 until n) bit.update(i, 1)

  var res = 0L
  var pos = 0
  var a = 1

  while (a <= max) {
    val positions = positionsByA(a)
    if (positions.nonEmpty) {
      var nextP = pos
      if (positions.head >= pos) {
        nextP = positions.last
        res += bit.rangeQuery(pos, nextP)
      } else {
        for (p <- positions) {
          if (p < pos) nextP = p
        }
        res += bit.rangeQuery(pos, n - 1) + bit.query(nextP)
      }
      for (p <- positions) {
        bit.update(p, -1)
      }
      pos = nextP
    }
    a += 1
  }

  println(res)
}

import scala.collection.mutable

object E extends App {

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

  class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val as = readInts(n)
  val max = as.max
  val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }

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

  val positionsByA = positionBuilders.map(_.result)

  val bit = new BIT(Array.fill(n){ 0 })
  for (i <- 0 until n) bit.update(i, 1)

  var res = 0L
  var p = 0
  var a = 1

  while (a <= max) {
    val positions = positionsByA(a)
    if (positions.nonEmpty) {
      if (positions.head >= p) {
        val nextP = positions.last
        res += bit.rangeQuery(p, nextP)
        p = nextP
        for (pos <- positions) {
          bit.update(pos, -1)
        }
      } else {
        var nextP = p
        for (pos <- positions) {
          if (pos < p) nextP = pos
        }
        res += bit.rangeQuery(0, nextP)
        res += bit.rangeQuery(p, n - 1)
        p = nextP
        for (pos <- positions) {
          bit.update(pos, -1)
        }
      }
    }
    a += 1
  }

  println(res)
}

import scala.collection.mutable

object E extends App {

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

  class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val as = readInts(n)
  val max = as.max
  val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }

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

  val positionsByA = positionBuilders.map(_.result)

  val bit = new BIT(Array.fill(n){ 0 })
  for (i <- 0 until n) bit.update(i, 1)

  var res = 0L
  var pos = 0
  var a = 1

  while (a <= max) {
    val positions = positionsByA(a)
    if (positions.nonEmpty) {
      var nextP = pos
      if (positions.head >= pos) {
        nextP = positions.last
        res += bit.rangeQuery(pos, nextP)
      } else {
        for (pos <- positions) {
          if (pos < pos) nextP = pos
        }
        res += bit.rangeQuery(pos, n - 1) + bit.query(nextP)
      }
      for (pos <- positions) {
        bit.update(pos, -1)
      }
      pos = nextP
    }
    a += 1
  }

  println(res)
}


Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above.

The first line contains three space-separated integers n, s, l (1 ≤ n ≤ 105, 0 ≤ s ≤ 109, 1 ≤ l ≤ 105). The second line contains n integers ai separated by spaces ( - 109 ≤ ai ≤ 109).

Output the minimal number of strip pieces. If there are no ways to split the strip, output -1.

NoteFor the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.

object B extends App {

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

  case class SegTreeMin(as: Array[Int]) {

    val NEUTRAL = Int.MaxValue // neutral element in respect of operation used (min)

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) min t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      if (l > r) NEUTRAL
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        math.min(query(l, math.min(r, tm), v2, tl, tm),
          query(math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))
      }
    }

  }

  case class SegTreeMax(as: Array[Int]) {

    val NEUTRAL = Int.MinValue // neutral element in respect of operation used (max)

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) max t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      if (l > r) NEUTRAL
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        math.max(query(l, math.min(r, tm), v2, tl, tm),
          query(math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))
      }
    }

  }

  val Array(n, s, l) = readInts(3)
  val as = readInts(n)

  val stMin = SegTreeMin(as)
  val stMax = SegTreeMax(as)

  val solved = Array.fill(n + 1)(-1)
  solved(n) = 0

  def solve(left: Int): Int = {
    if (solved(left) >= 0) solved(left)
    else {
      var best = 1000000

      @annotation.tailrec
      def binSearch(low: Int, hi: Int): Int = {
        if (hi < low) low
        else {
          val mid = (low + hi) >>> 1
          if (stMax.query(left, mid) - stMin.query(left, mid) > s) binSearch(low, mid - 1)
          else binSearch(mid + 1, hi)
        }
      }

      val minRight = left + l - 1
      var right = binSearch(minRight, n - 1) - 1
      val limit = math.max(minRight, right - l)

      while (right >= limit) {
        val result = solve(right + 1) + 1
        if (result < best) {
          best = result
          right = -1
        } else right -= 1
      }
      solved(left) = best
      best
    }
  }

  val res = solve(0)

  println(if (res == 1000000) -1 else res)
}


Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \le s \le n \le 1000$$$) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.

Print "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home.

object Main {
  import java.io.PrintStream

  def main(args: Array[String]): Unit = {
    val s = new Main()
    val ps = new PrintStream(Console.out)
    Console.withOut(ps) {
      s.solve()
    }
    ps.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
  import scala.Console

  val MOD = 1000000007

  def solve(): Unit = {
    val N, S = ni()
    val A, B = na(N) map (_ == 1)

    def openABAfter = {
      S until N exists { i =>
        A(i) && B(i)
      }
    }

    val ok = A(0) && ((A(S - 1) || B(S - 1) && openABAfter))
    println(if (ok) "YES" else "NO")
  }

  class InputReader(reader: BufferedReader) {
    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(Console.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)(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
  }

  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 A extends App {

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

  val Array(n, s) = readInts(2)
  val as, bs = readInts(n)

  if (as(0) == 1 && as(s - 1) == 1) println("YES")
  else if (as(0) == 1 && bs(s - 1) == 1) {
    if ((s until n).exists(i => as(i) == 1 && bs(i) == 1)) println("YES")
    else println("NO")
  } else println("NO")

  Console.flush
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    //println(s"n a ${n} ${a}")

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)

    if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {
      println("NO")
    }
    else if (first(a - 1) == 1){
      println("YES")
    }
    else {
      var found = false
      (a - 1 until n).foreach{ mid =>
        if (first(mid) == 1 && second(mid) == 1) {
          found = true
        }
      }

      if (found) println("YES") else println("NO")
    }

  }
}

object A extends App {
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextDouble = in.nextDouble
    def nextString = in.next

    val Y = "YES"
    val N = "NO"

    var isOk:Boolean = false

    def solve = {
        var n = nextInt
        var loc = nextInt

        var s1 = (for (i <- 0 until n) yield nextInt).toArray
        var s2 = (for (i <- 0 until n) yield nextInt).toArray

        if (loc == 1) {
            isOk = true
        } else if (s1(loc - 1) == 0 && s2(loc - 1) == 0) {
            isOk = false
        } else if (s1(0) == 0 && loc > 1) {
            isOk = false
        } else {
            // for
            for (i <- 0 until n) {
                // println(i + "," + n + "," + loc)
                if (s1(i) == 1) {
                    if (i == loc - 1) {
                        isOk = true
                    } else if (s2(loc - 1) == 1 && i >= loc - 1 && s2(i) == 1) {
                        isOk = true
                    }
                }
            }
        }

        // println(s"$n, $loc, $s1")
    }

    solve
    println(if(isOk) Y else N)
}

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    println(first.mkString(" "))
    println(second.mkString(" "))

    if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)

    if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {
      println("NO")
    }
    else if (first(a - 1) == 0){
      println("YES")
    }
    else {
      var found = false
      (a - 1 until n).foreach{ mid =>
        if (first(mid) == 1 && second(mid) == 1) {
          found = true
        }
      }

      if (found) println("YES") else println("NO")
    }

  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.filter(_._1 >= 0).map(_._2)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.filter(_._1 >= 0).map(_._2)

    //println(first.mkString(" "))
    //println(second.mkString(" "))

    if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.filter(_._1 > 0).map(_._2)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.filter(_._1 > 0).map(_._2)

    //println(first.mkString(" "))
    //println(second.mkString(" "))

    if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    if (!first.contains(0) == 0 || (!first.contains(a - 1) == 0 && !second.contains(a - 1) == 0)) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

object A extends App {
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextDouble = in.nextDouble
    def nextString = in.next

    val Y = "YES"
    val N = "NO"

    var isOk:Boolean = false

    def solve = {
        var n = nextInt
        var loc = nextInt

        var s1 = (for (i <- 0 until n) yield nextInt).toArray
        var s2 = (for (i <- 0 until n) yield nextInt).toArray

        if (loc == 1) {
            isOk = true
        } else if (s1(0) == 0 && loc > 1) {
            isOk = false
        } else {
            // for
            for (i <- 0 until n) {
                // println(i + "," + n + "," + loc)
                if (s1(i) == 1) {
                    if (i == loc - 1) {
                        isOk = true
                    } else if (s2(loc - 1) == 1) {
                        isOk = true
                    }
                }
            }
        }

        // println(s"$n, $loc, $s1")
    }

    solve
    println(if(isOk) Y else N)
}

object A extends App {
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextDouble = in.nextDouble
    def nextString = in.next

    val Y = "YES"
    val N = "NO"

    var isOk:Boolean = false

    def solve = {
        var n = nextInt
        var loc = nextInt

        var s1 = (for (i <- 0 until n) yield nextInt).toArray
        var s2 = (for (i <- 0 until n) yield nextInt).toArray

        if (loc == 1) {
            isOk = true
        } else if (s1(0) == 0 && loc > 1) {
            isOk = false
        } else {
            // for
            for (i <- 0 until n) {
                // println(i + "," + n + "," + loc)
                if (s1(i) == 1) {
                    if (i == loc - 1) {
                        isOk = true
                    }
                }
                if (s2(loc - 1) == 1 && i >= loc - 1 && s2(i) == 1) {
                        isOk = true
                }
            }
        }

        // println(s"$n, $loc, $s1")
    }

    solve
    println(if(isOk) Y else N)
}


Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored A·B·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) × (B - 2) × (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 × 1 × 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B и C.Given number n, find the minimally possible and maximally possible number of stolen hay blocks.

The only line contains integer n from the problem's statement (1 ≤ n ≤ 109).

Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

NoteLet's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 × 4 × 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) × (4 - 2) × (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 × 3 × 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) × (3 - 2) × (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks.

import scala.annotation.tailrec
import scala.math._
object Main {

  val oo = Long.MaxValue / 2;

  def main(args: Array[String]): Unit = {
    def factorize(n: Long): List[Long] = {
      val range = 1L to sqrt(n).asInstanceOf[Long]
      range.foldLeft(List[Long]()) { (xs: List[Long], i: Long) =>
        if (n % i == 0) {
          if (i * i != n) i :: n / i :: xs
          else i :: xs
        } else xs
      }
    }

    def solve(n: Int): (Long, Long) = {
      var min = +oo
      var max = -oo
      val factors = factorize(n)
      for(factor <- factors) {
          val subFactors = factorize(factor)
          for(subFactor <- subFactors) {
            val num = (1 + n / factor) * (2 + subFactor) * (2 + factor/ subFactor);
            min = Math.min(min, num)
            max = Math.max(max, num)
          }
      }
      (min - n, max - n)
    }
    val n = readInt()
    val ans = solve(n)
    print(ans._1 + " " + ans._2)
  }
}