Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.

The first line of the input contains a single integer n (3 ≤ n ≤ 100 000). Each of the next n lines contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.

Print three distinct integers on a single line — the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.

NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture.   Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border).

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Long](n)
  for (i <- 0 until n) {
    val Array(x, y) = readLongs(2)
    xs(i) = x
    ys(i) = y
  }

  def sqr(x: Double) = x * x
  def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))

  case class Point(x: Long, y: Long)

  def direction(uv: (Point, Point), w: Point) =
    (uv._2.x - uv._1.x) * (w.y - uv._1.y) - (w.x - uv._1.x) * (uv._2.y - uv._1.y)

  def area(i: Int, j: Int, k: Int) = {
    val al = Math.sqrt(dist(i, j))
    val bl = Math.sqrt(dist(j, k))
    val cl = Math.sqrt(dist(i, k))
    val s = (al + bl + cl) / 2d
    Math.sqrt(s * (s - al) * (s - bl) * (s - cl))
  }

  val a = 1
  var b = 2
  var ab = dist(a, b)
  for (i <- 3 to n) {
    val d2 = dist(a, i)
    if (d2 < ab) {
      b = i
      ab = d2
    }
  }

  var c = 0
  var abc = Double.PositiveInfinity
  val pA = Point(xs(a - 1), ys(a - 1))
  val pB = Point(xs(b - 1), ys(b - 1))
  val pAB = pA -> pB

  for (i <- 2 to n) if (i != b && direction(pAB, Point(xs(i - 1), ys(i - 1))) != 0) {
    val a2 = area(a, b, i)
    if (a2 < abc) {
      c = i
      abc = a2
    }
  }

  println(s"$a $b $c")
}

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

object CF2016_C_2 {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
    is = new ByteArrayInputStream(Test.t84.trim.getBytes("ISO-8859-1"))
    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val stars = new Array[(Long, Long)](n+1)

    for(i <- 1 to n) {
      val line = readLine()
      stars(i) = (line.long, line.long)
    }

    val x = stars(1)._1
    val y = stars(1)._2
    var distances = new Array[(Int, Double)](n-1)
    for(i <- 2 to n) {
      val xDif = (x - stars(i)._1).abs
      val yDif = (y - stars(i)._2).abs

      val xSq = xDif*xDif //overflow?
      val ySq = yDif*yDif
      val dist = (xSq + ySq)

      distances(i-2) = (i, dist)
      db(i + " -> " + dist)
    }

    distances = distances.sortWith(_._2 < _._2)
    db(distances.mkString(", "))

    var zerro = false
    def calcFun(s1:Int, s2:Int) :(Double, Double) = {
      val xDif = stars(s2)._1 - stars(s1)._1
      if (xDif == 0) {
        zerro = true
        return (0,0)
      }
      val a = (stars(s2)._2 - stars(s1)._2) / xDif
      val b = stars(s1)._2 - a * stars(s1)._1
      (a, b)
    }

    var secondInd = 1
    val fun = calcFun(1, distances(0)._1)
    db("fun = " + fun + " zerro=" + zerro)
    while (secondInd < distances.size &&
            belongs(fun, distances(secondInd)._1)) {
      secondInd+= 1
    }

    def belongs(fun:(Double, Double), st:Int):Boolean = {
      val star = stars(st)
      if (zerro && star._1 == x) {
        true
      } else {
	      val (a,b) = fun
	      val y = a*star._1 + b
	      val diff = (y - star._2).abs
	      db("func diff " + st + " -> " + diff)
	      return diff < 0.000000001
      }
    }

    println(1 + " " + distances(0)._1 + " " + distances(secondInd)._1)

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 0
0 2
2 0
2 2
1 1
"""

val sa2 = """
3
-1000000000 -1000000000
1000000000 1000000000
1000000000 999999999
"""

val t15 = """
10
13303280 387243789
30131431 723806809
404775998 670757742
-25996011 -398742031
25599613 633170449
38471092 890600029
-33017802 -539177851
-47620079 -831223391
1425218 149682549
-3745401 46270169
"""

val t49 = """
10
999999999 1
999999998 1
999999997 1
1000000000 1
999999996 1
999999995 1
999999994 1
999999992 1
999999993 1
0 0
"""

val t50 = """
4
0 1
0 2
0 3
7 7
"""

val t84 = """
3
1 2
2 1
2 3
"""
}

}

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

object CF2016_C {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
    is = new ByteArrayInputStream(Test.t50.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val stars = new Array[(Long, Long)](n+1)

    val ad = 1000000000
    for(i <- 1 to n) {
      val line = readLine()
      stars(i) = (line.long+ad, line.long+ad)
    }

    val x = stars(1)._1
    val y = stars(1)._2
    var distances = new Array[(Int, BigDecimal, BigDecimal)](n-1)
    for(i <- 2 to n) {
      val xDif = BigDecimal((x - stars(i)._1).abs)
      val yDif = BigDecimal((y - stars(i)._2).abs)

      val xSq = xDif*xDif
      val ySq = yDif*yDif
      val dist = (xSq + ySq)

//      val dist = Math.sqrt(xDif*xDif + yDif*yDif)
//      val xDifAbs = BigDecimal((x - stars(i)._1))
//      val relSin = (xDif*xDif)/dist * xDifAbs.signum
      val relSin = (xDif*xDif)/dist
      val alpha = relSin

      distances(i-2) = (i, dist, alpha)
      db(i + " -> " + dist)
    }

    distances = distances.sortWith(_._2 < _._2)
    db(distances.mkString(", "))

    var zerro = false
    def calcFun(s1:Int, s2:Int) :(BigDecimal, BigDecimal) = {
      if (stars(s2)._1 - stars(s1)._1 == 0) {
        zerro = true
        return (0,0)
      }
      val a = (BigDecimal(stars(s2)._2) - stars(s1)._2) / (stars(s2)._1 - stars(s1)._1)
      val b = (BigDecimal(stars(s1)._2)-ad) - a * (BigDecimal(stars(s1)._1) - ad)
      (a, b)
    }

    var secondInd = 1
    val alpha1 = distances(0)._3
    val coef = calcFun(1, 2)
    db("coef = " + coef)
//    while (secondInd < distances.size && check(alpha1,distances(secondInd)._3)) {
    while (secondInd < distances.size && check(alpha1,distances(secondInd)._3) &&
        (isZerro(distances(secondInd)._1) ||
            belongs(coef._1, coef._2, distances(secondInd)._1))) {
      secondInd+= 1
    }

    def isZerro(st:Int): Boolean = {
      if (zerro && stars(st)._1 == x) {
        true
      } else {
    	  false
      }
    }

    def check(v1:BigDecimal, v2:BigDecimal) = {
//      val diff = (v1 - v2).abs
//      diff < 0.00000000001
      v1 == v2
    }

    def belongs(a:BigDecimal, b:BigDecimal, st:Int):Boolean = {
      val y = a*(stars(st)._1-ad) + b
      val diff = (y - (stars(st)._2-ad)).abs
      db("func diff " + st + " -> " + diff)
      return diff < 0.000000001
    }

//    def area(a:BigDecimal, b:BigDecimal, c:BigDecimal) = {
//      s;
//    }

    def dist(v1:(Long,Long), v2:(Long,Long)) {
       val xDif = BigDecimal((v1._1 - v2._1).abs)
       val yDif = BigDecimal((v1._2 - v2._2).abs)
        val xSq = xDif*xDif
      val ySq = yDif*yDif
      val dist = (xSq + ySq)
    }

    println(1 + " " + distances(0)._1 + " " + distances(secondInd)._1)

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 0
0 2
2 0
2 2
1 1
"""

val sa2 = """
3
-1000000000 -1000000000
1000000000 1000000000
1000000000 1000000000
"""

val t15 = """
10
13303280 387243789
30131431 723806809
404775998 670757742
-25996011 -398742031
25599613 633170449
38471092 890600029
-33017802 -539177851
-47620079 -831223391
1425218 149682549
-3745401 46270169
"""

val t49 = """
10
999999999 1
999999998 1
999999997 1
1000000000 1
999999996 1
999999995 1
999999994 1
999999992 1
999999993 1
0 0
"""

val t50 = """
4
0 1
0 2
0 3
7 7
"""

val t84 = """
3
1 2
2 1
2 3
"""
}

}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Long](n)
  for (i <- 0 until n) {
    val Array(x, y) = readLongs(2)
    xs(i) = x
    ys(i) = y
  }

  def sqr(x: Double) = x * x
  def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))

  case class Point(x: BigInt, y: BigInt)

  def direction(uv: (Point, Point), w: Point) =
    (uv._2.x - uv._1.x) * (w.y - uv._1.y) - (w.x - uv._1.x) * (uv._2.y - uv._1.y)

  def area(i: Int, j: Int, k: Int) = {
    val al = Math.sqrt(dist(i, j))
    val bl = Math.sqrt(dist(j, k))
    val cl = Math.sqrt(dist(i, k))
    val s = (al + bl + cl) / 2d
    Math.sqrt(s * (s - al) * (s - bl) * (s - cl))
  }

  val a = 1
  var b = 2
  var ab = dist(a, b)
  for (i <- 3 to n) {
    val d2 = dist(a, i)
    if (d2 < ab) {
      b = i
      ab = d2
    }
  }

  var c = 0
  var abc = Double.PositiveInfinity
  val pA = Point(xs(a - 1), ys(a - 1))
  val pB = Point(xs(b - 1), ys(b - 1))
  val pAB = pA -> pB

  for (i <- 2 to n) if (i != b && direction(pAB, Point(xs(i - 1), ys(i - 1))) != 0) {
    val a2 = area(a, b, i)
    if (a2 < abc) {
      c = i
      abc = a2
    }
  }

  println(s"$a $b $c")
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Long](n)
  for (i <- 0 until n) {
    val Array(x, y) = readLongs(2)
    xs(i) = x
    ys(i) = y
  }

  def sqr(x: Double) = x * x
  def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))

  case class Point(x: BigInt, y: BigInt)

  def direction(uv: (Point, Point), w: Point) =
    (uv._2.x - uv._1.x) * (w.y - uv._1.y) - (w.x - uv._1.x) * (uv._2.y - uv._1.y)

  def area(i: Int, j: Int, k: Int) = {
    val al = Math.sqrt(dist(i, j))
    val bl = Math.sqrt(dist(j, k))
    val cl = Math.sqrt(dist(i, k))
    val s = (al + bl + cl) / 2d
    Math.sqrt(s * (s - al) * (s - bl) * (s - cl))
  }

  val a = 1
  var b = 2
  var ab = dist(a, b)
  for (i <- 3 to n) {
    val d2 = dist(a, i)
    if (d2 < ab) {
      b = i
      ab = d2
    }
  }

  var c = if (b == 2) 3 else 2
  var abc = area(a, b, c)
  val pA = Point(xs(a - 1), ys(a - 1))
  val pB = Point(xs(b - 1), ys(b - 1))
  val pAB = pA -> pB

  for (i <- 2 to n) if (i != b && direction(pAB, Point(xs(i - 1), ys(i - 1))) != 0) {
    val a2 = area(a, b, i)
    if (a2 > 0.1d && (a2 < abc || abc < 0.1d)) {
      c = i
      abc = a2
    }
  }

  println(s"$a $b $c")
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Long](n)
  for (i <- 0 until n) {
    val Array(x, y) = readLongs(2)
    xs(i) = x
    ys(i) = y
  }

  def sqr(x: Double) = x * x
  def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))

  def area(i: Int, j: Int, k: Int) = {
    val al = Math.sqrt(dist(i, j))
    val bl = Math.sqrt(dist(j, k))
    val cl = Math.sqrt(dist(i, k))
    val s = (al + bl + cl) / 2d
    Math.sqrt(s) * (s - al) * (s - bl) * (s - cl)
  }

  val a = 1
  var b = 2
  var ab = dist(a, b)
  for (i <- 3 to n) {
    val d2 = dist(a, i)
    if (d2 < ab) {
      b = i
      ab = d2
    }
  }

  var c = if (b == 2) 3 else 2
  var abc = area(a, b, c)

  for (i <- 2 to n) if (i != b) {
    val a2 = area(a, b, i)
    if (a2 > 0.1d && (a2 < abc || abc < 0.1d)) {
      c = i
      abc = a2
    }
  }

  println(s"$a $b $c")
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Long](n)
  for (i <- 0 until n) {
    val Array(x, y) = readLongs(2)
    xs(i) = x
    ys(i) = y
  }

  def sqr(x: Long) = x * x
  def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))

  def area(i: Int, j: Int, k: Int) = {
    val al = Math.sqrt(dist(i, j))
    val bl = Math.sqrt(dist(j, k))
    val cl = Math.sqrt(dist(i, k))
    val s = (al + bl + cl) / 2d
    Math.sqrt(s) * (s - al) * (s - bl) * (s - cl)
  }

  val a = 1
  var b = 2
  var ab = dist(a, b)
  for (i <- 3 to n) {
    val d2 = dist(a, i)
    if (d2 < ab) {
      b = i
      ab = d2
    }
  }

  var c = if (b == 2) 3 else 2
  var abc = area(a, b, c)

  for (i <- 2 to n) if (i != b) {
    val a2 = area(a, b, i)
    if (a2 > 0.1d && (a2 < abc || abc < 0.1d)) {
      c = i
      abc = a2
    }
  }

  println(s"$a $b $c")
}

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

object CF2016_C {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa2.trim.getBytes("ISO-8859-1"))
    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val stars = new Array[(Long, Long)](n+1)

    val ad = 1000000000
    for(i <- 1 to n) {
      val line = readLine()
      stars(i) = (line.long+ad, line.long+ad)
    }

    val x = stars(1)._1
    val y = stars(1)._2
    var distances = new Array[(Int, Double, Double)](n-1)
    for(i <- 2 to n) {
      val xDif = (x - stars(i)._1).abs
      val yDif = (y - stars(i)._2).abs

      val dist = Math.sqrt(xDif*xDif + yDif*yDif)
      val relSin = xDif/dist
      val alpha = relSin

      distances(i-2) = (i, dist, alpha)
      db(i + " -> " + dist)
    }

    distances = distances.sortWith(_._2 < _._2)
    db(distances.mkString(", "))

    var secondInd = 1
    val alpha1 = distances(0)._3
    while (secondInd < distances.size && alpha1 == distances(secondInd)._3) {
      secondInd+= 1
    }

    println(1 + " " + distances(0)._1 + " " + distances(secondInd)._1)

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 0
0 2
2 0
2 2
1 1
"""

val sa2 = """
3
-1000000000 -1000000000
1000000000 1000000000
1000000000 1000000000
"""

}

}

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

object CF2016_C {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
    is = new ByteArrayInputStream(Test.t15.trim.getBytes("ISO-8859-1"))
    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val stars = new Array[(Long, Long)](n+1)

    val ad = 1000000000
    for(i <- 1 to n) {
      val line = readLine()
      stars(i) = (line.long+ad, line.long+ad)
    }

    val x = stars(1)._1
    val y = stars(1)._2
    var distances = new Array[(Int, BigDecimal, BigDecimal)](n-1)
    for(i <- 2 to n) {
      val xDif = BigDecimal((x - stars(i)._1).abs)
      val yDif = BigDecimal((y - stars(i)._2).abs)

      val xSq = xDif*xDif
      val ySq = yDif*yDif
      val dist = (xSq + ySq)

//      val dist = Math.sqrt(xDif*xDif + yDif*yDif)
      val xDifAbs = BigDecimal((x - stars(i)._1))
      val relSin = (xDif*xDif)/dist * xDifAbs.signum
      val alpha = relSin

      distances(i-2) = (i, dist, alpha)
      db(i + " -> " + dist)
    }

    distances = distances.sortWith(_._2 < _._2)
    db(distances.mkString(", "))

    var zerro = false
    def calcFun(s1:Int, s2:Int) :(Double, Double) = {
      if (stars(s2)._1 - stars(s1)._1 == 0) {
        zerro = true
        return (0,0)
      }
      val a = (stars(s2)._2 - stars(s1)._2) / (stars(s2)._1 - stars(s1)._1)
      val b = stars(s1)._2 - a * stars(s1)._1 - ad*2
      (a, b)
    }

    var secondInd = 1
    val alpha1 = distances(0)._3
    val coef = calcFun(1, 2)
    db("coef = " + coef)
//    while (secondInd < distances.size && check(alpha1,distances(secondInd)._3)) {
    while (secondInd < distances.size && check(alpha1,distances(secondInd)._3) && (zerro || belongs(coef._1, coef._2, secondInd+1))) {
      secondInd+= 1
    }

    def check(v1:BigDecimal, v2:BigDecimal) = {
//      val diff = (v1 - v2).abs
//      diff < 0.00000000001
      v1 == v2
    }

    def belongs(a:Double, b:Double, st:Int):Boolean = {
      val y = a*stars(st)._1 + b
      return (y - stars(st)._2).abs < 0.000000001
    }

//    def area(a:BigDecimal, b:BigDecimal, c:BigDecimal) = {
//      s;
//    }

    def dist(v1:(Long,Long), v2:(Long,Long)) {
       val xDif = BigDecimal((v1._1 - v2._1).abs)
       val yDif = BigDecimal((v1._2 - v2._2).abs)
        val xSq = xDif*xDif
      val ySq = yDif*yDif
      val dist = (xSq + ySq)
    }

    println(1 + " " + distances(0)._1 + " " + distances(secondInd)._1)

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 0
0 2
2 0
2 2
1 1
"""

val sa2 = """
3
-1000000000 -1000000000
1000000000 1000000000
1000000000 1000000000
"""

val t15 = """
10
13303280 387243789
30131431 723806809
404775998 670757742
-25996011 -398742031
25599613 633170449
38471092 890600029
-33017802 -539177851
-47620079 -831223391
1425218 149682549
-3745401 46270169
"""

val t49 = """
10
999999999 1
999999998 1
999999997 1
1000000000 1
999999996 1
999999995 1
999999994 1
999999992 1
999999993 1
0 0
"""

val t84 = """
3
1 2
2 1
2 3
"""
}

}

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

object CF2016_C {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa2.trim.getBytes("ISO-8859-1"))
    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val stars = new Array[(Long, Long)](n+1)

    val ad = 1000000000
    for(i <- 1 to n) {
      val line = readLine()
      stars(i) = (line.long+ad, line.long+ad)
    }

    val x = stars(1)._1
    val y = stars(1)._2
    var distances = new Array[(Int, Double, Double)](n-1)
    for(i <- 2 to n) {
      val xDif = (x - stars(i)._1).abs
      val yDif = (y - stars(i)._2).abs

      val dist = Math.sqrt(xDif*xDif + yDif*yDif)
      val relSin = dist/(xDif+1)
      val alpha = Math.asin(relSin)

      distances(i-2) = (i, dist, alpha)
      db(i + " -> " + dist)
    }

    distances = distances.sortWith(_._2 < _._2)
    db(distances.mkString(", "))

    var secondInd = 1
    val alpha1 = distances(0)._3
    while (secondInd < distances.size && alpha1 == distances(secondInd)._3) {
      secondInd+= 1
    }

    println(1 + " " + distances(0)._1 + " " + distances(secondInd)._1)

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 0
0 2
2 0
2 2
1 1
"""

val sa2 = """
3
-1000000000 -1000000000
1000000000 1000000000
1000000000 1000000000
"""

}

}

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

object CF2016_C {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa2.trim.getBytes("ISO-8859-1"))
    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val stars = new Array[(Long, Long)](n+1)

    val ad = 1000000000
    for(i <- 1 to n) {
      val line = readLine()
      stars(i) = (line.long+ad, line.long+ad)
    }

    val x = stars(1)._1
    val y = stars(1)._2
    var distances = new Array[(Int, Double, Double)](n-1)
    for(i <- 2 to n) {
      val xDif = (x - stars(i)._1).abs
      val yDif = (y - stars(i)._2).abs

      val dist = Math.sqrt(xDif*xDif + yDif*yDif)
      val relSin = dist/xDif
      val alpha = Math.asin(relSin)

      distances(i-2) = (i, dist, alpha)
      db(i + " -> " + dist)
    }

    distances = distances.sortWith(_._2 < _._2)
    db(distances.mkString(", "))

    var secondInd = 1
    val alpha1 = distances(0)._3
    while (secondInd < distances.size && alpha1 == distances(secondInd)._3) {
      secondInd+= 1
    }

    println(1 + " " + distances(0)._1 + " " + distances(secondInd)._1)

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 0
0 2
2 0
2 2
1 1
"""

val sa2 = """
3
-1000000000 -1000000000
1000000000 1000000000
1000000000 1000000000
"""

}

}

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

object CF2016_C {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val stars = new Array[(Long, Long)](n+1)

    val ad = 1000000000
    for(i <- 1 to n) {
      val line = readLine()
      stars(i) = (line.long+ad, line.long+ad)
    }

    val x = stars(1)._1
    val y = stars(1)._2
    var distances = new Array[(Int, BigDecimal, BigDecimal)](n-1)
    for(i <- 2 to n) {
      val xDif = BigDecimal((x - stars(i)._1).abs)
      val yDif = BigDecimal((y - stars(i)._2).abs)

      val xSq = xDif*xDif
      val ySq = yDif*yDif
      val dist = (xSq + ySq)

//      val dist = Math.sqrt(xDif*xDif + yDif*yDif)
//      val xDifAbs = BigDecimal((x - stars(i)._1))
//      val relSin = (xDif*xDif)/dist * xDifAbs.signum
      val relSin = (xDif*xDif)/dist
      val alpha = relSin

      distances(i-2) = (i, dist, alpha)
      db(i + " -> " + dist)
    }

    distances = distances.sortWith(_._2 < _._2)
    db(distances.mkString(", "))

    var zerro = false
    def calcFun(s1:Int, s2:Int) :(BigDecimal, BigDecimal) = {
      if (stars(s2)._1 - stars(s1)._1 == 0) {
        zerro = true
        return (0,0)
      }
      val a = (BigDecimal(stars(s2)._2) - stars(s1)._2) / (stars(s2)._1 - stars(s1)._1)
      val b = (BigDecimal(stars(s1)._2)-ad) - a * (BigDecimal(stars(s1)._1) - ad)
      (a, b)
    }

    var secondInd = 1
    val alpha1 = distances(0)._3
    val coef = calcFun(1, 2)
    db("coef = " + coef)
//    while (secondInd < distances.size && check(alpha1,distances(secondInd)._3)) {
    while (secondInd < distances.size && check(alpha1,distances(secondInd)._3) &&
        (!zerro &&
            belongs(coef._1, coef._2, distances(secondInd)._1))) {
      secondInd+= 1
    }

    def check(v1:BigDecimal, v2:BigDecimal) = {
//      val diff = (v1 - v2).abs
//      diff < 0.00000000001
      v1 == v2
    }

    def belongs(a:BigDecimal, b:BigDecimal, st:Int):Boolean = {
      val y = a*(stars(st)._1-ad) + b
      val diff = (y - (stars(st)._2-ad)).abs
      db("func diff " + st + " -> " + diff)
      return diff < 0.000000001
    }

//    def area(a:BigDecimal, b:BigDecimal, c:BigDecimal) = {
//      s;
//    }

    def dist(v1:(Long,Long), v2:(Long,Long)) {
       val xDif = BigDecimal((v1._1 - v2._1).abs)
       val yDif = BigDecimal((v1._2 - v2._2).abs)
        val xSq = xDif*xDif
      val ySq = yDif*yDif
      val dist = (xSq + ySq)
    }

    println(1 + " " + distances(0)._1 + " " + distances(secondInd)._1)

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 0
0 2
2 0
2 2
1 1
"""

val sa2 = """
3
-1000000000 -1000000000
1000000000 1000000000
1000000000 1000000000
"""

val t15 = """
10
13303280 387243789
30131431 723806809
404775998 670757742
-25996011 -398742031
25599613 633170449
38471092 890600029
-33017802 -539177851
-47620079 -831223391
1425218 149682549
-3745401 46270169
"""

val t49 = """
10
999999999 1
999999998 1
999999997 1
1000000000 1
999999996 1
999999995 1
999999994 1
999999992 1
999999993 1
0 0
"""

val t84 = """
3
1 2
2 1
2 3
"""
}

}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Long](n)
  for (i <- 0 until n) {
    val Array(x, y) = readLongs(2)
    xs(i) = x
    ys(i) = y
  }

  def sqr(x: Long) = x * x
  def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))

  def area(i: Int, j: Int, k: Int) = {
    val al = Math.sqrt(dist(i, j))
    val bl = Math.sqrt(dist(j, k))
    val cl = Math.sqrt(dist(i, k))
    val s = (al + bl + cl) / 2d
    Math.sqrt(s) * (s - al) * (s - bl) * (s - cl)
  }

  val a = 1
  var b = 2
  var ab = dist(a, b)
  for (i <- 3 to n) {
    val d2 = dist(a, i)
    if (d2 < ab) {
      b = i
      ab = d2
    }
  }

  var c = if (b == 2) 3 else 2
  var abc = area(a, b, c)

  for (i <- 2 to n) if (i != b) {
    val a2 = area(a, b, i)
    if (a2 > 0.0000001d && (a2 < abc || abc < 0.0000001d)) {
      c = i
      abc = a2
    }
  }

  println(s"$a $b $c")
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Long](n)
  for (i <- 0 until n) {
    val Array(x, y) = readLongs(2)
    xs(i) = x
    ys(i) = y
  }

  def sqr(x: Long) = x * x
  def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))

  def area(i: Int, j: Int, k: Int) = {
    val al = Math.sqrt(dist(i, j))
    val bl = Math.sqrt(dist(j, k))
    val cl = Math.sqrt(dist(i, k))
    val s = (al + bl + cl) / 2d
    Math.sqrt(s) * (s - al) * (s - bl) * (s - cl)
  }

  val a = 1
  var b = 2
  var ab = dist(a, b)
  for (i <- 3 to n) {
    val d2 = dist(a, i)
    if (d2 < ab) {
      b = i
      ab = d2
    }
  }

  var c = if (b == 2) 3 else 2
  var abc = area(a, b, c)

  for (i <- 2 to n) if (i != b) {
    val a2 = area(a, b, i)
    if (a2 > 0.5d && (a2 < abc || abc < 0.5d)) {
      c = i
      abc = a2
    }
  }

  println(s"$a $b $c")
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Long](n)
  for (i <- 0 until n) {
    val Array(x, y) = readLongs(2)
    xs(i) = x
    ys(i) = y
  }

  def sqr(x: Double) = x * x
  def dist(i: Int, j: Int) = sqr(xs(i - 1) - xs(j - 1)) + sqr(ys(i - 1) - ys(j - 1))

  case class Point(x: Long, y: Long)

  def direction(uv: (Point, Point), w: Point) =
    (uv._2.x - uv._1.x) * (w.y - uv._1.y) - (w.x - uv._1.x) * (uv._2.y - uv._1.y)

  def area(i: Int, j: Int, k: Int) = {
    val al = Math.sqrt(dist(i, j))
    val bl = Math.sqrt(dist(j, k))
    val cl = Math.sqrt(dist(i, k))
    val s = (al + bl + cl) / 2d
    Math.sqrt(s * (s - al) * (s - bl) * (s - cl))
  }

  val a = 1
  var b = 2
  var ab = dist(a, b)
  for (i <- 3 to n) {
    val d2 = dist(a, i)
    if (d2 < ab) {
      b = i
      ab = d2
    }
  }

  var c = if (b == 2) 3 else 2
  var abc = area(a, b, c)
  val pA = Point(xs(a - 1), ys(a - 1))
  val pB = Point(xs(b - 1), ys(b - 1))
  val pAB = pA -> pB

  for (i <- 2 to n) if (i != b && direction(pAB, Point(xs(i - 1), ys(i - 1))) != 0) {
    val a2 = area(a, b, i)
    if (a2 > 0.1d && (a2 < abc || abc < 0.1d)) {
      c = i
      abc = a2
    }
  }

  println(s"$a $b $c")
}


The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).  If the wind blows to the east, the boat will move to (x + 1, y).  If the wind blows to the south, the boat will move to (x, y - 1).  If the wind blows to the west, the boat will move to (x - 1, y).  If the wind blows to the north, the boat will move to (x, y + 1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?

The first line contains five integers t, sx, sy, ex, ey (1 ≤ t ≤ 105,  - 109 ≤ sx, sy, ex, ey ≤ 109). The starting location and the ending location will be different. The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).

If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).

NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(t, x1, y1, x2, y2) = in.next().split(' ').map(_.toLong)
  val (tr, xr, yr) = in.next().foldLeft((0l, x1, y1)) {
    case ((time, x, y), _) if x == x2 && y == y2 => (time, x, y)
    case ((time, x, y), 'N') if y < y2 => (time + 1, x, y + 1)
    case ((time, x, y), 'S') if y > y2 => (time + 1, x, y - 1)
    case ((time, x, y), 'W') if x > x2 => (time + 1, x - 1, y)
    case ((time, x, y), 'E') if x < x2 => (time + 1, x + 1, y)
    case ((time, x, y), _) => (time + 1, x, y)
  }
  if (xr == x2 && yr == y2)
    println(tr)
  else
    println(-1)

}

object Solution {

  def main(args: Array[String]) {
    val si = io.Source.stdin.getLines
    val Array(n, s1, s2, e1, e2) = si.next.split(' ').map(_.toInt)
    val w = si.next.toArray

    var v = e2 - s2
    var vd = 'N'
    if (v < 0) {
      vd = 'S'
    }

    v = math.abs(v)

    var h = e1 - s1
    var hd = 'E'
    if (h < 0) {
      hd = 'W'
    }

    h = math.abs(h)

    var sec = -1

    (0 to w.length - 1) foreach {i =>
      if(v != 0 && w(i) == vd) v -= 1
      else if (h != 0 && w(i) == hd) h -= 1

      if(h == 0 && v == 0 && sec == -1) {
        sec = i + 1
      }
    }

    if (sec > n) sec == -1

    println(sec)

  }

}

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

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

    // If the wind blows to the east, the boat will move to (x + 1, y).
    // If the wind blows to the south, the boat will move to (x, y - 1).
    // If the wind blows to the west, the boat will move to (x - 1, y).
    // If the wind blows to the north, the boat will move to (x, y + 1).

  def solve(): Int = {
    val T, sx, sy, ex, ey = sc.nextInt
    sc.nextLine
    val Winds = sc.nextLine.toList
    val N = (ey - sy) max 0
    val S = (sy - ey) max 0
    val E = (ex - sx) max 0
    val W = (sx - ex) max 0

    @tailrec
    def loop(n: Int, s: Int, e: Int, w: Int, ws: List[Char]): Int = {
      if (n >= N && s >= S && e >= E && w >= W) {
        T - ws.size
      }
      else {
        (ws: @unchecked) match {
          case Nil => -1
          case 'N' :: xs => loop(n + 1, s, e, w, xs)
          case 'S' :: xs => loop(n, s + 1, e, w, xs)
          case 'E' :: xs => loop(n, s, e + 1, w, xs)
          case 'W' :: xs => loop(n, s, e, w + 1, xs)
        }
      }
    }

    loop(0, 0, 0, 0, Winds)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner

object Sail {

  def mv(x:Int, d:Int):Int = if(x==0 || x.signum==d.signum)x else x+d
  val M = Map('E' -> (1,0), 'W'->(-1,0), 'S'->(0,-1), 'N'->(0,1))
  def solveDist(s:Iterator[Char], dx:Int, dy:Int, acc: Int):Int = {
    if (dx.abs + dy.abs == 0)  acc
    else if (s.isEmpty) -1
     else {
       val t = M(s.next())
       solveDist(s,mv(dx,t._1), mv(dy,t._2), acc+1)
     }
  }
  def solve(s:Iterator[Char], sx:Int, sy:Int, ex:Int, ey:Int):Int = solveDist(s, sx-ex, sy-ey,0)

  def main(args: Array[String]) {
   val scan = new Scanner(System.in)
   scan.nextInt()
   val sx = scan.nextInt
   val sy = scan.nextInt
   val ex = scan.nextInt
   val ey = scan.nextInt
   val c = scan.next
   println(solve(c.iterator,sx,sy,ex,ey))
  }
}

import java.util.Scanner

object B {
  def main(args: Array[String]) {
      var scan = new Scanner(System.in)
      var t = scan.nextInt
      var sx = scan.nextInt
      var sy = scan.nextInt
      var ex = scan.nextInt
      var ey = scan.nextInt
      var dx = sx - ex
      var dy=sy-ey
      var s = scan.next
      var r=0
      if(dx==0 &&dy==0){
        println(r)
        return
      }
      for (c <- s) {
        if(c=='S' && dy>0)dy-=1
        if(c=='N' && dy<0)dy+=1
        if(c=='W' && dx>0)dx-=1
        if(c=='E' && dx<0)dx+=1
        r += 1
        if(dx==0 &&dy==0){
          println(r)
          return
        }

      }
      println(-1)
  }
}

object Main {
  val sdir: PartialFunction[Char, (Int, Int)] = { case 'S' => (0, -1) }
  val ndir: PartialFunction[Char, (Int, Int)] = { case 'N' => (0,  1) }
  val edir: PartialFunction[Char, (Int, Int)] = { case 'E' => ( 1, 0) }
  val wdir: PartialFunction[Char, (Int, Int)] = { case 'W' => (-1, 0) }
  val nop: PartialFunction[Char, (Int, Int)] = { case _ => (0, 0) }

  def main(args: Array[String]) {
    val op = readLine().split(" ").map(_.toInt)
    val a = readLine()
    val dir = ((op(3) - op(1)).signum, (op(4) - op(2)).signum) match {
      case (1, 1) => edir orElse ndir orElse nop
      case (1, 0) => edir orElse nop
      case (1, -1) => edir orElse sdir orElse nop
      case (-1, 1) => wdir orElse ndir orElse nop
      case (-1, 0) => wdir orElse nop
      case (-1, -1) => wdir orElse sdir orElse nop
      case (0, 1) => ndir orElse nop
      case (0, 0) => nop
      case (0, -1) => sdir orElse nop
    }
    val r = a.scanLeft(op(1), op(2)) { (pos, c) =>
      var nd = dir(c)
      (pos._1 + nd._1, pos._2 + nd._2)
    }
    val ho = r.zipWithIndex.find(_._1._1 == op(3)).map(_._2)
    val vo = r.zipWithIndex.find(_._1._2 == op(4)).map(_._2)
    (ho, vo) match {
      case (Some(h), Some(v)) => println(h.max(v))
      case _ => println("-1")
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(t, x1, y1, x2, y2) = in.next().split(' ').map(_.toInt)
  val (tr, xr, yr) = in.next().foldLeft((0, 0, 0)) {
    case ((time, x, y), _) if x == x2 && y == y2 => (time, x, y)
    case ((time, x, y), 'N') if y < y2 => (time + 1, x, y + 1)
    case ((time, x, y), 'S') if y > y2 => (time + 1, x, y - 1)
    case ((time, x, y), 'W') if x < x2 => (time + 1, x - 1, y)
    case ((time, x, y), 'E') if x < x2 => (time + 1, x + 1, y)
    case ((time, x, y), _) => (time + 1, x, y)
  }
  if (xr == x2 && yr == y2)
    println(tr)
  else
    println(-1)

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(t, x1, y1, x2, y2) = in.next().split(' ').map(_.toLong)
  val (tr, xr, yr) = in.next().foldLeft((0l, 0l, 0l)) {
    case ((time, x, y), _) if x == x2 && y == y2 => (time, x, y)
    case ((time, x, y), 'N') if y < y2 => (time + 1, x, y + 1)
    case ((time, x, y), 'S') if y > y2 => (time + 1, x, y - 1)
    case ((time, x, y), 'W') if x < x2 => (time + 1, x - 1, y)
    case ((time, x, y), 'E') if x < x2 => (time + 1, x + 1, y)
    case ((time, x, y), _) => (time + 1, x, y)
  }
  if (xr == x2 && yr == y2)
    println(tr)
  else
    println(-1)

}

object Solution {

  def main(args: Array[String]) {
    val si = io.Source.stdin.getLines
    val Array(n, s1, s2, e1, e2) = si.next.split(' ').map(_.toInt)
    val w = si.next.toArray

    var v = e2 - s2
    var vd = 'N'
    if (v < 0) {
      vd = 'S'
    }

    var h = e1 - s1
    var hd = 'E'
    if (h < 0) {
      hd = 'W'
    }

    var sec = -1

    (0 to w.length - 1) foreach {i =>
      if(v != 0 && w(i) == vd) v -= 1
      else if (h != 0 && w(i) == hd) h -= 1

      if(h == 0 && v == 0 && sec == -1) {
        sec = i + 1
      }
    }

    if (sec > n) sec == -1

    println(sec)

  }

}

object Solution {

  def main(args: Array[String]) {
    val si = io.Source.stdin.getLines
    val Array(n, s1, s2, e1, e2) = si.next.split(' ').map(_.toInt)
    val w = si.next.toArray

    var v = e2 - s2
    var vd = 'N'
    if (v < 0) {
      vd = 'S'
    }

    var h = e1 - s1
    var hd = 'E'
    if (h < 0) {
      hd = 'W'
    }

    var sec = -1

    (0 to w.length - 1) foreach {i =>
      if(w(i) == vd) v -= 1
      else if (w(i) == hd) h -= 1

      if(h == 0 && v == 0 && sec == -1) {
        sec = i + 1
      }
    }

    if (sec > n) sec == -1

    println(sec)

  }

}

object Main {
  val sdir: PartialFunction[Char, (Int, Int)] = { case 'S' => (0, -1) }
  val ndir: PartialFunction[Char, (Int, Int)] = { case 'N' => (0,  1) }
  val edir: PartialFunction[Char, (Int, Int)] = { case 'E' => ( 1, 0) }
  val wdir: PartialFunction[Char, (Int, Int)] = { case 'W' => (-1, 0) }
  val nop: PartialFunction[Char, (Int, Int)] = { case _ => (0, 0) }

  def main(args: Array[String]) {
    val op = readLine().split(" ").map(_.toInt)
    val a = readLine()
    val dir = ((op(3) - op(1)).signum, (op(4) - op(2)).signum) match {
      case (1, 1) => ndir orElse edir orElse nop
      case (1, 0) => ndir orElse nop
      case (1, -1) => ndir orElse wdir orElse nop
      case (-1, 1) => sdir orElse edir orElse nop
      case (-1, 0) => sdir orElse nop
      case (-1, -1) => sdir orElse wdir orElse nop
      case (0, 1) => edir orElse nop
      case (0, 0) => nop
      case (0, -1) => wdir orElse nop
    }
    val r = a.scanLeft(op(1), op(2)) { (pos, c) =>
      var nd = dir(c)
      (pos._1 + nd._1, pos._2 + nd._2)
    }
    val ho = r.zipWithIndex.find(_._1._1 == op(3)).map(_._2)
    val vo = r.zipWithIndex.find(_._1._2 == op(4)).map(_._2)
    (ho, vo) match {
      case (Some(h), Some(v)) => println(h.max(v))
      case _ => println("-1")
    }
  }
}


Hongcow likes solving puzzles.One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.

The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece. The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space. It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.

Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.

NoteFor the first sample, one example of a rectangle we can form is as follows 111222111222For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle: .......XX................

import java.io._
import scala.io.Source

import scala.annotation.tailrec

object ProblemB {
  def main(args: Array[String]): Unit = processStdInOut()

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val dims = lines.next().split(" ").map(_.toInt)
    val rowCount = dims(0)
    val colCount = dims(1)
    val emptyRow = "." * colCount
    var nonEmptyRow: Option[String] = None
    var inRectangle = false

    def doesRowHaveHoles(row: String): Boolean = {
      val (start, afterStart) = row.partition(_ == '.')
      val (pieces, end) = afterStart.partition(_ != '.')
      end.exists(_ != '.')
    }

    def isNextRowValid(i: Int): Boolean = {
      val row = lines.next()
      val isRowEmpty = row.forall(_ == '.')
      nonEmptyRow match {
        // First row not found yet...
        case None if isRowEmpty => true          // First row with parts of piece not found yet, so all fine
        case None => {
          nonEmptyRow = Some(row)
          inRectangle = true
          !doesRowHaveHoles(row)    // Don't allow a row with holes
        }

        // In rectangle:
        case Some(rowPatternToMatch) if inRectangle => if (isRowEmpty) {
          inRectangle = false  // an empty row means we are no longer in the rectangle
          true
        } else {
          row == rowPatternToMatch
        }

        // After rectangle:
        case _ => isRowEmpty  // All rows after the rectangular piece must be empty
      }
    }

    val validRows = (0 until rowCount).map(isNextRowValid)
    val soln = validRows.forall(isValid => isValid)
    bw.write(if (soln) "YES" else "NO")
    bw.newLine()
  }
}

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

object _745B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n, m = read[Int]

    val row = Array.ofDim[Int](n)
    val col = Array.ofDim[Int](m)

    row.indices foreach {r =>
      val line = read[String]
      line.indices foreach {c =>
        if (line(c) == 'X') {
          row(r) += 1
          col(c) += 1
        }
      }
    }

    val rr = row.toSet - 0
    val cc = col.toSet - 0
    val ans = rr.size == 1 && cc.size == 1

    write(ans.toEnglish)
  }
}
/****************************[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
      }
    }
  }
}


Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array.  The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.

Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val index = Array.ofDim[Int](n)
  val data = in.next().split(' ').map(_.toInt)
  data.indices.foreach { i =>
    index(data(i) - 1) = i
  }
  val m = in.next().toInt
  val res =  in.next().split(' ').map(_.toInt).foldLeft(0l, 0l) {
    case((left, right), i) =>
      (left + index(i - 1) + 1, right + n - index(i - 1))
  }

  println(s"${res._1} ${res._2}")
}

object Main {
  def main(args: Array[String]) {
    val n = readLong()
    val a = readLine().split(" ").map(_.toInt).zipWithIndex.sortBy(_._1).map(_._2.toLong)

    val m = readLong();
    val r = readLine().split(" ").map(_.toLong)
    val r1 = r.map(i => a(i.toInt - 1) + 1L).sum
    val r2 = (n + 1) * m - r1
    println(r1 + " " + r2)
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt).zipWithIndex.sortBy(_._1).map(_._2)

    val m = readInt();
    val r = readLine().split(" ").map(_.toInt)
    val r1 = r.map(i => a(i - 1) + 1).sum
    val r2 = (n + 1) * m - r1
    println(r1 + " " + r2)
  }
}


Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.So imagine Monocarp got recommended $$$n$$$ songs, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th song had its predicted rating equal to $$$p_i$$$, where $$$1 \le p_i \le n$$$ and every integer from $$$1$$$ to $$$n$$$ appears exactly once. In other words, $$$p$$$ is a permutation.After listening to each of them, Monocarp pressed either a like or a dislike button. Let his vote sequence be represented with a string $$$s$$$, such that $$$s_i=0$$$ means that he disliked the $$$i$$$-th song, and $$$s_i=1$$$ means that he liked it.Now the service has to re-evaluate the song ratings in such a way that:  the new ratings $$$q_1, q_2, \dots, q_n$$$ still form a permutation ($$$1 \le q_i \le n$$$; each integer from $$$1$$$ to $$$n$$$ appears exactly once);  every song that Monocarp liked should have a greater rating than every song that Monocarp disliked (formally, for all $$$i, j$$$ such that $$$s_i=1$$$ and $$$s_j=0$$$, $$$q_i>q_j$$$ should hold). Among all valid permutations $$$q$$$ find the one that has the smallest value of $$$\sum\limits_{i=1}^n |p_i-q_i|$$$, where $$$|x|$$$ is an absolute value of $$$x$$$.Print the permutation $$$q_1, q_2, \dots, q_n$$$. If there are multiple answers, you can print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of songs. The second line of each testcase contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the permutation of the predicted ratings. The third line contains a single string $$$s$$$, consisting of $$$n$$$ characters. Each character is either a $$$0$$$ or a $$$1$$$. $$$0$$$ means that Monocarp disliked the song, and $$$1$$$ means that he liked it. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a permutation $$$q$$$ — the re-evaluated ratings of the songs. If there are multiple answers such that $$$\sum\limits_{i=1}^n |p_i-q_i|$$$ is minimum possible, you can print any of them.

NoteIn the first testcase, there exists only one permutation $$$q$$$ such that each liked song is rating higher than each disliked song: song $$$1$$$ gets rating $$$2$$$ and song $$$2$$$ gets rating $$$1$$$. $$$\sum\limits_{i=1}^n |p_i-q_i|=|1-2|+|2-1|=2$$$.In the second testcase, Monocarp liked all songs, so all permutations could work. The permutation with the minimum sum of absolute differences is the permutation equal to $$$p$$$. Its cost is $$$0$$$.

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val ps = nextInts(n)
      val s = nextLine

      val res0 = (0 until n).sortBy {
        i => (s(i), ps(i))
      }

      val res = Array.ofDim[Int](n)
      for (i <- 0 until n) {
        res(res0(i)) = i + 1
      }

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

    out.flush()
  }

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


John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$) — the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$.

Print the rank of Thomas Smith. Thomas's id is $$$1$$$.

NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$.

object Main {
import java.io._
import java.util.Scanner

import collection.mutable.HashMap
import scala.collection.{SortedSet, mutable}
import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val arr = Array.ofDim[(Int, Int)](n)
        for(i <- arr.indices) {
            var sum = 0
            for(_ <- 1 to 4) {
                sum += nextInt
            }
            arr(i) = sum -> i
        }
        val res = arr.sorted(Ordering.Tuple2(Ordering.Int.reverse, Ordering.Int))
            .zipWithIndex.find(_._1._2 == 0).get._2
        println(res + 1)
    }

  }

}


You have decided to watch the best moments of some movie. There are two buttons on your player:   Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.  Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (t + x). Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the li-th minute and ends at the ri-th minute (more formally, the i-th best moment consists of minutes: li, li + 1, ..., ri). Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?

The first line contains two space-separated integers n, x (1 ≤ n ≤ 50, 1 ≤ x ≤ 105) — the number of the best moments of the movie and the value of x for the second button. The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space li, ri (1 ≤ li ≤ ri ≤ 105). It is guaranteed that for all integers i from 2 to n the following condition holds: ri - 1 < li.

Output a single number — the answer to the problem.

NoteIn the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the 12-th minute of the movie. In total, we watch 6 minutes of the movie.In the second sample, the movie is very interesting, so you'll have to watch all 100000 minutes of the movie.

import java.util.StringTokenizer

object _499A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val x = next.toInt
  val (l, r) = (1 to n).map(i => (next.toInt, next.toInt)).toArray.unzip

  def doit(i: Int, t: Int, acc: Int): Int = {
    if (i == n) acc
    else if (t < l(i)) {
      if (t + x <= l(i)) doit(i, t + x, acc)
      else doit(i, t + 1, acc + 1)
    } else doit(i + 1, r(i) + 1, acc + r(i) - l(i) + 1)
  }

  println(doit(0, 1, 0))
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, x) = in.next().split(" ").map(_.toInt)
  val data = Range(0, n).map{ i =>
    val Array(a, b) = in.next().split(" ").map(_.toInt)
    (a, b)}.sorted
  println(data.foldLeft((1, 0)) {
    case((current_min, watched), (start, finish)) if finish < current_min =>
      (current_min, watched)
    case((current_min, watched), (start, finish)) =>
      val nStart = (start - current_min) / x * x
      (finish + 1, watched + (finish - current_min - nStart + 1))
  }._2)
}

object A499 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = readInts(2)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))
    var curr = 1
    var res = 0
    for(i <- in.indices) {
      if(in(i)._1 >= curr + x) {
        res += (in(i)._1 - curr) % x
      } else {
        res += (in(i)._1 - curr)
      }
      res += in(i)._2 - in(i)._1 + 1
      curr = in(i)._2 + 1

      //dlksj
    }
    println(res)
  }

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

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

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

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

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

}

import scala.io.StdIn

object A extends App {
  def readPair() = {
    val a = StdIn.readLine() split " " map { _.toInt }
    (a(0), a(1))
  }

  val (n, x) = readPair()

  var res = 0
  var c = 1
  for (i <- 1 to n) {
    val (l, r) = readPair()

    res = res + (l - c) % x + (r - l) + 1
    c = r + 1
  }

  Console.println(res)
}

object Main extends App {

  val Array(n, x) = readLine.split(" ").map(_.toInt)
  val init = (1, 0)
  val (_, total) = (1 to n).foldLeft(init) {
    case ((cursor, total), _) =>
       val Array(from, to) = readLine.split(" ").map(_.toInt)
       (to+1, total + 1 + (to-from) + ((from-cursor) % x))
  }
  println(total)

}

import java.io._

object Problem499A extends App {
  val problem = new Problem499A(
    new InputStreamReader(System.in),
    new OutputStreamWriter(System.out)
  )

  problem.run()
}

class Problem499A(input: Reader, output: Writer) {
  private val tokenizer = new StreamTokenizer(new BufferedReader(input))

  private var currentMinute = 1
  private var rewindSize = 0
  private var seenMinutes: Int = 0

  def run(): Unit = {
    tokenizer.eolIsSignificant(true)

    var n = readInt()
    rewindSize = readInt()
    tokenizer.nextToken() // Next line

    while (n > 0) {
      readBestMoments()

      n -= 1
    }

    output.write(seenMinutes.toString)
    output.flush()
  }

  private def readBestMoments(): Unit = {
    val start = readInt()
    val end = readInt()
    tokenizer.nextToken()

    val minutesToStart = start - currentMinute
    seenMinutes += minutesToStart % rewindSize + (end - start + 1)

    currentMinute = end + 1
  }

  private def readInt(): Int = {
    if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {
      throw new RuntimeException("Integer expected")
    }

    tokenizer.nval.toInt
  }
}

import java.io._

object Problem499A extends App {
  val problem = new Problem499A(
    new InputStreamReader(System.in),
    new OutputStreamWriter(System.out)
  )

  problem.run()
}

class Problem499A(input: Reader, output: Writer) {
  private val tokenizer = new StreamTokenizer(new BufferedReader(input))

  private var currentMinute = 1
  private var rewindSize = 0
  private var seenMinutes: Int = 0

  def run(): Unit = {
    tokenizer.eolIsSignificant(true)

    var n = readInt()
    rewindSize = readInt()
    tokenizer.nextToken() // Next line

    while (n > 0) {
      readBestMoments()

      n -= 1
    }

    output.write(seenMinutes.toString)
  }

  private def readBestMoments(): Unit = {
    val start = readInt()
    val end = readInt()
    tokenizer.nextToken()

    val minutesToStart = start - currentMinute
    seenMinutes += minutesToStart % rewindSize + (end - start + 1)

    currentMinute = end + 1
  }

  private def readInt(): Int = {
    if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {
      throw new RuntimeException("Integer expected")
    }

    tokenizer.nval.toInt
  }
}


There are $$$n$$$ traps numbered from $$$1$$$ to $$$n$$$. You will go through them one by one in order. The $$$i$$$-th trap deals $$$a_i$$$ base damage to you.Instead of going through a trap, you can jump it over. You can jump over no more than $$$k$$$ traps. If you jump over a trap, it does not deal any damage to you. But there is an additional rule: if you jump over a trap, all next traps damages increase by $$$1$$$ (this is a bonus damage).Note that if you jump over a trap, you don't get any damage (neither base damage nor bonus damage). Also, the bonus damage stacks so, for example, if you go through a trap $$$i$$$ with base damage $$$a_i$$$, and you have already jumped over $$$3$$$ traps, you get $$$(a_i + 3)$$$ damage.You have to find the minimal damage that it is possible to get if you are allowed to jump over no more than $$$k$$$ traps.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le n$$$) — the number of traps and the number of jump overs that you are allowed to make. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — base damage values of all traps. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output a single integer — the minimal total damage that it is possible to get if you are allowed to jump over no more than $$$k$$$ traps.

NoteIn the first test case it is allowed to jump over all traps and take $$$0$$$ damage.In the second test case there are $$$5$$$ ways to jump over some traps:  Do not jump over any trap.Total damage: $$$5 + 10 + 11 + 5 = 31$$$. Jump over the $$$1$$$-st trap.Total damage: $$$\underline{0} + (10 + 1) + (11 + 1) + (5 + 1) = 29$$$. Jump over the $$$2$$$-nd trap.Total damage: $$$5 + \underline{0} + (11 + 1) + (5 + 1) = 23$$$. Jump over the $$$3$$$-rd trap.Total damage: $$$5 + 10 + \underline{0} + (5 + 1) = 21$$$. Jump over the $$$4$$$-th trap.Total damage: $$$5 + 10 + 11 + \underline{0} = 26$$$.To get minimal damage it is needed to jump over the $$$3$$$-rd trap, so the answer is $$$21$$$.In the third test case it is optimal to jump over the traps $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$7$$$:Total damage: $$$0 + (2 + 1) + 0 + 0 + 0 + (2 + 4) + 0 = 9$$$.

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util

object Main {

  def findNotSortedRow(a: Array[Array[Int]]): Option[Int] = {
    a.indices.find { i =>
      (1 until a(i).length).exists { j =>
        a(i)(j - 1) > a(i)(j)
      }
    }
  }

  def swapColumns(a: Array[Array[Int]], i: Int, j: Int) = {
    a.foreach { row =>
      val temp = row(i)
      row(i) = row(j)
      row(j) = temp
    }
  }

  case class Trap(dmg: Long, id: Int) {
    val evadeProfit = -(dmg + id)
  }

  def main(args: Array[String]): Unit = {
    val reader = new InputReader()
    val t = reader.nextInt()
    (1 to t).foreach { i =>
      val n = reader.nextInt()
      val k = reader.nextInt()
      val a = new Array[Trap](n)
      a.indices.foreach { i =>
        a(i) = Trap(reader.nextLong(), i)
      }

      val temp = a.sortBy(_.evadeProfit)
      val evaded = new util.HashSet[Trap]()
      (0 until k).foreach { i =>
        evaded.add(temp(i))
      }

      var sumDamage: Long = 0
      var evadedNum = 0
      a.foreach { i =>
        if (evaded.contains(i)) {
          evadedNum += 1
        } else {
          sumDamage += i.dmg + evadedNum
        }
      }

      System.out.println(sumDamage)
    }

  }

  class InputReader() {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var line: Array[String] = null
    var cur: Int = 0

    def nextString(): String = {
      while (line == null || cur >= line.length) {
        cur = 0
        line = reader.readLine().split(""" """)
      }
      cur += 1
      line(cur - 1)
    }

    def nextInt(): Int = {
      nextString().toInt
    }

    def nextLong(): Long = {
      nextString().toLong
    }

  }

}