You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of points on the line. The second line contains n integers xi ( - 109 ≤ xi ≤ 109) — the coordinates of the given n points.

Print the only integer x — the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt).sorted
  if (line.length == 1)
    println(line(0))
  else if (line.length % 2 == 1)
    println(line(line.length / 2))
  else
    println(line(line.length / 2 - 1))
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

/**
 * Educational round 16
 */
object B_ED16 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.sa3)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    var arr = new Array[Int](n)
    val pointsLn = readLine()
    (0 until n).foreach{
      arr(_) = pointsLn.int
    }

    arr = arr.sorted

    def dist(ind: Int): Long = {
      var sum = 0l
      for (i <- 0 until n) {
        if (i != ind) {
          sum += (arr(ind) - arr(i)).abs
        }
      }
      sum
    }

    def thereIsBetter(ind: Int): (Boolean, Int) = {
      val distP = dist(ind)
      if (ind != 0 && dist(ind-1) < distP) return (true, ind-1)
      if (ind < n-1 && dist(ind+1) < distP) return (true, ind+1)

      return (false, -1)
    }

    val mid = Math.ceil(n.toDouble/2 - 1).toInt
    debug(arr.mkString(",") + " -> " + arr(mid))
    debug((0 until n).map { dist(_) }.mkString(","))
    var cur = mid
    var next = thereIsBetter(cur)
    while (next._1) {
      cur = next._2
      next = thereIsBetter(cur)
    }

//    val totalDist = arr(n-1).toLong - arr(0)
//    debug(s"total=$totalDist")
//    val mid = math.floor(arr(0) + totalDist.toDouble/2).toInt
//    debug(arr.mkString(",") + " -> " + mid)
//
//    var minOff = totalDist
//    var minInd = 0
//    (0 until n).foreach { i =>
//      val off = (mid - arr(i)).abs
//      if (off < minOff) {
//        minOff = off
//        minInd = i
//      }

    //---------------------------- parameters reading :end
    var res = arr(cur)
    outLn(res+"")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
4
1 2 3 4
"""

val sa2 = """
5
-1 -10 2 6 7
"""

val sa3 = """
3
606194955 -856471310 117647402
"""
}

}

/**
  * Created by mahmoud on 8/22/16.
  */

import io.StdIn._
object Main {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    val array = readLine().split(" ").map(_.toInt)
    val srt = array.sorted
    println(srt((n - 1)/2))
  }

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt).sorted
  if (line.length == 0 || line.length == 1)
    println(line(0))
  else
    println(line(line.length / 2 - 1))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt).sorted
  if (line.length % 2 == 1)
    println(line(line.length / 2 + 1))
  else if (line.length == 0)
    println(line(0))
  else
    println(line(line.length / 2 - 1))
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

/**
 * Educational round 16
 */
object B_ED16 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa2)
//    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    var arr = new Array[Int](n)
    val pointsLn = readLine()
    (0 until n).foreach{
      arr(_) = pointsLn.int
    }

    arr = arr.sorted

    def dist(ind: Int): Int = {
      var sum = 0
      for (i <- 0 until n) {
        if (i != ind) {
          sum += (arr(ind) - arr(i)).abs
        }
      }
      sum
    }

    def thereIsBetter(ind: Int): (Boolean, Int) = {
      val distP = dist(ind)
      if (ind != 0 && dist(ind-1) < distP) return (true, ind-1)
      if (ind < n-1 && dist(ind+1) < distP) return (true, ind+1)

      return (false, -1)
    }

    val mid = Math.ceil(n.toDouble/2 - 1).toInt
    debug(arr.mkString(",") + " -> " + arr(mid))
    debug((0 until n).map { dist(_) }.mkString(","))
    var cur = mid
    var next = thereIsBetter(cur)
    while (next._1) {
      cur = next._2
      next = thereIsBetter(cur)
    }

//    val totalDist = arr(n-1).toLong - arr(0)
//    debug(s"total=$totalDist")
//    val mid = math.floor(arr(0) + totalDist.toDouble/2).toInt
//    debug(arr.mkString(",") + " -> " + mid)
//
//    var minOff = totalDist
//    var minInd = 0
//    (0 until n).foreach { i =>
//      val off = (mid - arr(i)).abs
//      if (off < minOff) {
//        minOff = off
//        minInd = i
//      }

    //---------------------------- parameters reading :end
    var res = arr(cur)
    outLn(res+"")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
4
1 2 3 4
"""

val sa2 = """
5
-1 -10 2 6 7
"""

val sa3 = """
"""
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

/**
 * Educational round 16
 */
object B_ED16 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.sa1)
//    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    var arr = new Array[Int](n+1)
    val pointsLn = readLine()
    (1 to n).foreach{
      arr(_) = pointsLn.int
    }

    arr = arr.sorted
    val totalDist = arr(n).toLong - arr(1)
    val mid = arr(1) + totalDist/2

    var minOff = totalDist
    var minInd = 0
    (1 to n).foreach { i =>
      val off = (mid - arr(i)).abs
      if (off < minOff) {
        minOff = off
        minInd = i
      }
    }

    //---------------------------- parameters reading :end
    var res = minInd
    outLn(res)
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
4
1 2 3 4
"""

val sa2 = """
"""

val sa3 = """
"""
}

}


A sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Given two integers $$$n$$$ and $$$k$$$, construct a permutation $$$a$$$ of numbers from $$$1$$$ to $$$n$$$ which has exactly $$$k$$$ peaks. An index $$$i$$$ of an array $$$a$$$ of size $$$n$$$ is said to be a peak if $$$1 < i < n$$$ and $$$a_i \gt a_{i-1}$$$ and $$$a_i \gt a_{i+1}$$$. If such permutation is not possible, then print $$$-1$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ lines follow, each containing two space-separated integers $$$n$$$ ($$$1 \leq n \leq 100$$$) and $$$k$$$ ($$$0 \leq k \leq n$$$) — the length of an array and the required number of peaks.

Output $$$t$$$ lines. For each test case, if there is no permutation with given length and number of peaks, then print $$$-1$$$. Otherwise print a line containing $$$n$$$ space-separated integers which forms a permutation of numbers from $$$1$$$ to $$$n$$$ and contains exactly $$$k$$$ peaks.  If there are multiple answers, print any.

NoteIn the second test case of the example, we have array $$$a = [2,4,1,5,3]$$$. Here, indices $$$i=2$$$ and $$$i=4$$$ are the peaks of the array. This is because $$$(a_{2} \gt a_{1} $$$, $$$a_{2} \gt a_{3})$$$ and $$$(a_{4} \gt a_{3}$$$, $$$a_{4} \gt a_{5})$$$.

object Pikes {
  import java.io.{BufferedReader, PrintStream}
  import scala.annotation.tailrec

  def solution(in: BufferedReader, out: PrintStream): Unit = {
    for (_ <- 1 to in.readLine().toInt) {
      val Array(n, k) = in.readLine().split(" ").map(_.toInt)
      out.println((solve(n, k) match { case Seq() => Seq(-1) case s => s }) mkString(" "))
    }
  }

  def solve(n: Int, k: Int): Seq[Int] = if (n - 1 < 2 * k) Seq.empty else {
    @tailrec
    def go(x: Int, k: Int, l: List[Int]): List[Int] =
      if (x > n) l
      else {
        if (k > 0) go(x + 2, k - 1, x :: x + 1 :: l)
        else go(x + 1, k, x :: l)
      }
    go(2, k, 1 :: Nil)
  }

  def main(args: Array[String]): Unit = solution(Console.in, Console.out)
}

object Pikes {
    import java.io.{BufferedReader, PrintStream}
import scala.annotation.tailrec

  def solution(in: BufferedReader, out: PrintStream): Unit = {
    for (_ <- 1 to in.readLine().toInt) {
      val Array(n, k) = in.readLine().split(" ").map(_.toInt)
      out.println((solve(n, k) match { case Seq() => Seq(-1) case s => s }) mkString(" "))
    }
  }

  def solve(n: Int, k: Int): Seq[Int] = if (n - 1 < 2 * k) Seq.empty else {
    @tailrec
    def go(x: Int, k: Int, l: List[Int]): List[Int] =
      if (x >= n) l
      else {
        if (k > 0) go(x + 2, k - 1, x :: x + 1 :: l)
        else go(x + 1, k, x + 1 :: l)
      }
    go(2, k, 1 :: Nil)
  }

  def main(args: Array[String]): Unit = solution(Console.in, Console.out)
}

object Pikes {
import java.io.{BufferedReader, PrintStream}
import scala.annotation.tailrec

  def solution(in: BufferedReader, out: PrintStream): Unit = {
    for (_ <- 1 to in.readLine().toInt) {
      val Array(n, k) = in.readLine().split(" ").map(_.toInt)
      out.println(solve(n, k).mkString(" "))
    }
  }

  def solve(n: Int, k: Int): Seq[Int] = if (n - 1 < 2 * k) Seq.empty else {
    @tailrec
    def go(x: Int, k: Int, l: List[Int]): List[Int] =
      if (x >= n) l
      else {
        if (k > 0) go(x + 2, k - 1, x :: x + 1 :: l)
        else go(x + 1, k, x + 1 :: l)
      }
    go(2, k, 1 :: Nil)
  }

  def main(args: Array[String]): Unit = solution(Console.in, Console.out)
}


For the multiset of positive integers $$$s=\{s_1,s_2,\dots,s_k\}$$$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $$$s$$$ as follow: $$$\gcd(s)$$$ is the maximum positive integer $$$x$$$, such that all integers in $$$s$$$ are divisible on $$$x$$$. $$$\textrm{lcm}(s)$$$ is the minimum positive integer $$$x$$$, that divisible on all integers from $$$s$$$.For example, $$$\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$$$ and $$$\textrm{lcm}(\{4,6\})=12$$$. Note that for any positive integer $$$x$$$, $$$\gcd(\{x\})=\textrm{lcm}(\{x\})=x$$$.Orac has a sequence $$$a$$$ with length $$$n$$$. He come up with the multiset $$$t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}$$$, and asked you to find the value of $$$\gcd(t)$$$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.

The first line contains one integer $$$n\ (2\le n\le 100\,000)$$$. The second line contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 200\,000$$$).

Print one integer: $$$\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\})$$$.

/**
  * C. Orac and LCM
  * https://codeforces.com/contest/1350/problem/C
  *
  * https://codeforces.com/blog/entry/77284?#comment-620958
  * https://codeforces.com/blog/entry/77284?#comment-621269
  * https://codeforces.com/contest/1349/submission/79820899
  */
object C extends App {

  private def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)

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

  val n  = scala.io.StdIn.readInt()
  val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  // gcd of { lcm(a1, a2), ..., lcm(a1, an), ..., lcm(ai, ai+1), ..., lcm(ai, an), ..., lcm(an-1, an) } =
  // gcd of { gcd of { lcm(a1, a2), lcm(a1, a3), ..., lcm(a1, an) }, ..., gcd of { lcm(ai, ai+1), lcm(ai, ai+2), ..., lcm(ai, an) }, ... }
  val ans = an.indices
    .foldLeft((0L, 0L)) {
      case ((ans, g), i) =>
        // gcd of { lcm(ai, ai+1), lcm(ai, ai+2), ..., lcm(ai, an) } =
        // lcm of { ai, gcd of { ai+1, ai+2, ..., an } }
        (gcd(ans, lcm(an(i), g)), gcd(g, an(i)))
    }
    ._1

  println(ans)
}


Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.

The first line contains the single integer n (1 ≤ n ≤ 1000) — the number of contests where the coder participated. The next line contains n space-separated non-negative integer numbers — they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.

Print the single number — the number of amazing performances the coder has had during his whole history of participating in the contests.

NoteIn the first sample the performances number 2 and 3 are amazing.In the second sample the performances number 2, 4, 9 and 10 are amazing.

import java.util.Scanner
object ILoveUserName {

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val c = scanner.nextInt();
    var max,min = 0
    min = scanner.nextInt()
    max = min
    var counter = 0;
    for (i <- 2 to c){
      var x = scanner.nextInt();
      if (x > max || x < min){
        counter += 1;
      }
      max = Math.max(x,max)
      min = Math.min(x,min)

    }
    println(counter)
  }

}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val input = new Scanner(System.in)

    val count, first = input.nextInt
    var incr = 0
    var min, max = first

    for (i <- 1 until count) {
      val next = input.nextInt
      if (next < min) {
        incr += 1
        min = next
      }
      if (next > max) {
        incr += 1
        max = next
      }
    }

    println(incr)
  }
}

object Main {
  def main(args: Array[String]) {
    // not like we need it or anything
    val n = readInt()

    var bestScore = 0
    var worstScore = 0

    val surprises = readLine().split(" ").map(_.toInt).fold(-1) {(surprises, score) =>
      if (surprises == -1) {
        bestScore = score
        worstScore = score
        0
      } else if (score > bestScore) {
        bestScore = score
        surprises + 1
      } else if (score < worstScore) {
        worstScore = score
        surprises + 1
      } else {
        surprises
      }
    }

    println(surprises)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(in.next().split(" ").map(_.toInt).foldLeft((-1, -1, 0)) {
    case((-1, -1, 0), el) => (el, el, 0)
    case((min, max, t), el) if el < min=> (el, max, t + 1)
    case((min, max, t), el) if el > max=> (min, el, t + 1)
    case(acc, el) => acc
  }._3)
}

object Main {
	def main(args: Array[String]) {

		readInt
		val a = readLine.split(" ").map(i => i.toInt)

		var max = a(0)
		var min = a(0)

		var cnt = 0
		a.foreach(i => {if (i < min) {cnt += 1; min = i }; if (i > max) { cnt +=1; max = i } } )
		println (cnt)
	}
}

object A155 {
  @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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val points = readInts(n)
    var res = 0
    var maxtill = points(0)
    var mintill = points(0)
    for(i <- 1 until n) {
      if(points(i) > maxtill){
        maxtill = points(i)
        res += 1
      } else if(points(i) < mintill){
        mintill = points(i)
        res += 1
      }
    }
    println(res)
  }
}

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

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

  val N = sc.nextInt
  val scores = Array.fill(N)(sc.nextInt)

  def solve: Int = {
    @tailrec
    def loop(amazing: Int, best: Int, worst: Int, i: Int): Int =
      if (i == N) amazing
      else {
        val s = scores(i)
        if (s > best) loop(amazing + 1, s, worst, i + 1)
        else if (s < worst) loop(amazing + 1, best, s, i + 1)
        else loop(amazing, best, worst, i + 1)
      }
    loop(0, scores(0), scores(0), 1)
  }

  out.println(solve)
  out.close
}

import scala.io.StdIn
import scala.language.implicitConversions

object A155 {
    def main(args: Array[String]) = {
        val _ = StdIn.readLine()
        val a = StdIn.readLine().split(" ").map(_.toInt)
        implicit def bool2int(b: Boolean) = if (b) 1 else 0
        println(a.foldLeft((0, a(0), a(0)))
            { (x: Tuple3[Int, Int, Int], y: Int) =>
                (x._1 + (y > x._2) + (y < x._3), y max x._2, y min x._3) }._1)
    }
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  reader.readLine()
  val a = readInts
  def mins = a.foldLeft(List(Int.MaxValue)) {
    case (l @ head :: _, x) => (head min x) :: l
  }
  def maxs = a.foldLeft(List(Int.MinValue)) {
    case (l @ head :: _, x) => (head max x) :: l
  }
  def ans = mins.groupBy(x => x).size + maxs.groupBy(x => x).size - 4

  def main(args: Array[String]) {
    println(ans)
  }
}

object A {
  def main(args: Array[String]): Unit = {
    val points = scala.io.Source.stdin.getLines().toList.tail.head.split(" ").map(_.toInt)
    System.out.println(points.foldLeft((points.head,points.head,0))( (a,p) => if (p>a._2)((a._1,p,a._3+1)) else if (p<a._1)((p, a._2, a._3+1)) else a)._3)
  }
}

object Main {
  def main(args: Array[String]) {
    val num = readInt()
    val a = readLine().split(" ").map(_.toInt)
    var max, min = a(0)
    var impr = 0
    for( v <- a.tail) {
      if (v > max) {
        max = v
        impr += 1
      }
      if (v < min) {
        min = v
        impr += 1
      }
    }
    println(impr)
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object ILoveUsername {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def solve(points : List[Int]) : Int = {
     def go(p: List[Int], max: Int, min: Int, amazing: Int) : Int = p match {
       case Nil => amazing
       case h :: t => go(t, Math.max(h,max),
           Math.min(h,min),amazing + (if  (h > max || h < min) 1 else 0))
     }
     go(points.tail, points.head,points.head,0)
   }

   def main(args: Array[String]) {
     val n = readInt
     val points = readInts().toList
     println(solve(points))
   }

}

object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val N = sc.nextInt
    val L = List.fill(N)(sc.nextInt)
    println(rec(L(0), L(0), L.tail, 0))
  }

  def rec(minv: Int, maxv: Int, lst: List[Int], acc: Int): Int = {
    lst match {
      case Nil => acc
      case head::tail => {
        if (head < minv) rec(head, maxv, tail, acc + 1)
        else if (head > maxv) rec(minv, head, tail, acc + 1)
        else rec(minv, maxv, tail, acc)
      }
    }
  }
}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val n = StdIn.readInt()

    var min = 10000000
    var max = 0
    var count = 0
    var first = true
    StdIn.readLine().split(" ").map(_.toInt).foreach{ t =>
      if(!first) {
        if(t > max) {
          max = t
          count+=1
        }

        if(t < min) {
          min = t
          count+=1
        }
      } else {
        max = t
        min = t
        first = false
      }
    }
    println(count)
  }

}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt
    val first = sc.nextInt
    var max = first
    var min = first
    var amazing = 0
    for (i <- 1 until n) {
      var tmp = sc.nextInt
      if (max < tmp) {
        max = tmp
        amazing += 1
      } else if (min > tmp) {
        min = tmp
        amazing += 1
      }
    }
    println(amazing)
  }
}

import scala.io.StdIn._

object Codeforces extends App {
  val n = readInt() - 1
  val scores = readLine().split(' ').map(_.toInt)
  var min = scores(0)
  var max = scores(0)
  var count = 0
  scores foreach(current => {
    if (current > max) {
      max = current
      count += 1
    }
    if (current < min) {
      min = current
      count += 1
    }
  })
  println(count)
}

import scala.io.Source

object Cf155a extends App {
  val a = Source.stdin.getLines.drop(1).next.split(" ").filterNot(_.isEmpty()).map(_.toInt)
  var min = a.head
  var max = a.head
  println(a.foldLeft(0)((y, x) => {
    if (x < min) {
      min = x
      y + 1
    } else if (x > max) {
      max = x;
      y + 1
    } else {
      y
    }
  }))
}


Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1 ≤ i ≤ n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i - 1 if i > 1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i = n, the cursor appears at the beginning of the string).When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.Initially, the text cursor is at position p. Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?

The first line contains two space-separated integers n (1 ≤ n ≤ 105) and p (1 ≤ p ≤ n), the length of Nam's string and the initial position of the text cursor. The next line contains n lowercase characters of Nam's string.

Print the minimum number of presses needed to change string into a palindrome.

NoteA string is a palindrome if it reads the same forward or reversed.In the sample test, initial Nam's string is:  (cursor position is shown bold).In optimal solution, Nam may do 6 following steps:The result, , is now a palindrome.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, p) = in.next().split(' ').map(_.toInt)
  val data = in.next()
  val zipped = data
    .take(n / 2)
    .zip(data.reverse.take(n / 2))
  val left = zipped.indices.find(i => zipped(i)._1 != zipped(i)._2)
  val right = zipped.indices.reverse.find(i => zipped(i)._1 != zipped(i)._2)

  val changes = zipped
    .foldLeft(0l) {
      case(acc, (a, b)) =>
        val min = Math.min(a, b)
        val max = Math.max(a, b)
        acc + Math.min(max - min, min - max + 'z' - 'a' + 1)

    }

  if (left.isEmpty)
    println(changes)
  else {
    val position = if (p > n / 2) n - p else p - 1
//    if (right.get < position)
//      println(changes + position - left.get)
//    else if (left.get > position)
//      println(changes + right.get - position)
//    else
//    println("right.get = " + right.get)
//    println("left.get = " + left.get)
//    println("position = " + position)
//    println("distance = " + (right.get - left.get))
//    println("dd " + Math.min(Math.abs(position - right.get), Math.abs(position - left.get)))
//    println(changes)
    println(changes + right.get - left.get + Math.min(Math.abs(position - right.get), Math.abs(position - left.get)))
  }

//  println("changes = " + changes)

}

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

object Solution {
    val INF = 1000 * 1000 * 1000

    def solve(in: FastScanner, out: PrintWriter): Unit = {
        val n = in.nextInt()
        var pos = in.nextInt() - 1
        val a = in.next().toCharArray()
        var rep = 0
        var res = INF
        for (rep <- 0 until 2) {
            var i = 0
            val delta = new Array[Int](n)
            for (i <- 0 until n / 2) {
                val diff = (a(i) - a(n - i - 1) + 26) % 26
                delta(i) = Math.min(diff, 26 - diff)
            }
            var leftPos = n / 2 + 1
            var rightPos = -1
            var cur = 0
            for (i <- 0 until n / 2) {
                cur += delta(i)
                if (delta(i) > 0) {
                    leftPos = Math.min(leftPos, i)
                    rightPos = Math.max(rightPos, i)
                }
            }
            if (cur != 0) {
                cur += rightPos - leftPos
                if (leftPos <= pos && pos <= rightPos)
                    cur += Math.min(pos - leftPos, rightPos - pos)
                else if (pos < leftPos)
                    cur += leftPos - pos
                else
                    cur += pos - rightPos
            }
            res = Math.min(res, cur)
            pos = n - 1 - pos
            for (i <- 0 until n / 2) {
                val t = a(i)
                a(i) = a(n - i - 1)
                a(n - i - 1) = t
            }
        }
        out.println(res)
    }

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

    class FastScanner(val in: InputStream) {
        var st: StringTokenizer = null
        var br = new BufferedReader(new InputStreamReader(in))

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

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

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

        def close(): Unit = {
            br.close()
        }
    }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, p) = in.next().split(' ').map(_.toInt)
  val data = in.next()
  val zipped = data
    .take(n / 2)
    .zip(data.reverse.take(n / 2))
  val left = zipped.indices.find(i => zipped(i)._1 != zipped(i)._2)
  val right = zipped.indices.reverse.find(i => zipped(i)._1 != zipped(i)._2)

  val changes = zipped
    .foldLeft(0l) {
      case(acc, (a, b)) =>
        val min = Math.min(a, b)
        val max = Math.max(a, b)
        acc + Math.min(max - min, min - max + 'z' - 'a' + 1)

    }

  if (left.isEmpty)
    println(changes)
  else {
    val position = if (p > n / 2) n - p else p
//    if (right.get < position)
//      println(changes + position - left.get)
//    else if (left.get > position)
//      println(changes + right.get - position)
//    else
    println(changes + right.get - left.get + 1+ Math.min(position - right.get, position - left.get))
  }

//  println("changes = " + changes)

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, p) = in.next().split(' ').map(_.toInt)
  val data = in.next()
  val zipped = data
    .take(n / 2)
    .zip(data.reverse.take(n / 2))
  val left = zipped.indices.find(i => zipped(i)._1 != zipped(i)._2)
  val right = zipped.indices.reverse.find(i => zipped(i)._1 != zipped(i)._2)

  val changes = zipped
    .foldLeft(0l) {
      case(acc, (a, b)) =>
        val min = Math.min(a, b)
        val max = Math.max(a, b)
        acc + Math.min(max - min, min - max + 'z' - 'a' + 1)

    }

  if (left.isEmpty)
    println(changes)
  else {
    val position = if (p > n / 2) n - p - 1 else p - 1
//    if (right.get < position)
//      println(changes + position - left.get)
//    else if (left.get > position)
//      println(changes + right.get - position)
//    else
//    println("right.get = " + right.get)
//    println("left.get = " + left.get)
//    println("position = " + position)
//    println("distance = " + (right.get - left.get))
//    println("dd " + Math.min(position - right.get, position - left.get))
//    println(changes)
    println(changes + right.get - left.get + Math.min(Math.abs(position - right.get), Math.abs(position - left.get)))
  }

//  println("changes = " + changes)

}

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

object Solution {
    val INF = 1000 * 1000 * 1000

    def solve(in: FastScanner, out: PrintWriter): Unit = {
        val n = in.nextInt()
        var pos = in.nextInt() - 1
        val a = in.next().toCharArray()
        var rep = 0
        var res = INF
        for (rep <- 0 until 2) {
            var i = 0
            val delta = new Array[Int](n)
            for (i <- 0 until n / 2) {
                val diff = (a(i) - a(n - i - 1) + 26) % 26
                delta(i) = Math.min(diff, 26 - diff)
            }
            var leftPos = 0
            var rightPos = n / 2
            var cur = 0
            for (i <- 0 until n / 2) {
                cur += delta(i)
                if (delta(i) > 0) {
                    leftPos = Math.min(leftPos, i)
                    rightPos = Math.max(rightPos, i)
                }
            }
            if (cur != 0) {
                cur += rightPos - leftPos
                if (leftPos <= pos && pos <= rightPos)
                    cur += Math.min(pos - leftPos, rightPos - pos)
            }
            res = Math.min(res, cur)
            pos = n - 1 - pos
            for (i <- 0 until n / 2) {
                val t = a(i)
                a(i) = a(n - i - 1)
                a(n - i - 1) = t
            }
        }
        out.println(res)
    }

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

    class FastScanner(val in: InputStream) {
        var st: StringTokenizer = null
        var br = new BufferedReader(new InputStreamReader(in))

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

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

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

        def close(): Unit = {
            br.close()
        }
    }
}


It is a holiday season, and Koala is decorating his house with cool lights! He owns $$$n$$$ lights, all of which flash periodically.After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $$$a_i$$$ and $$$b_i$$$. Light with parameters $$$a_i$$$ and $$$b_i$$$ will toggle (on to off, or off to on) every $$$a_i$$$ seconds starting from the $$$b_i$$$-th second. In other words, it will toggle at the moments $$$b_i$$$, $$$b_i + a_i$$$, $$$b_i + 2 \cdot a_i$$$ and so on.You know for each light whether it's initially on or off and its corresponding parameters $$$a_i$$$ and $$$b_i$$$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out.    Here is a graphic for the first example.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$), the number of lights. The next line contains a string $$$s$$$ of $$$n$$$ characters. The $$$i$$$-th character is "1", if the $$$i$$$-th lamp is initially on. Otherwise, $$$i$$$-th character is "0". The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 5$$$)  — the parameters of the $$$i$$$-th light.

Print a single integer — the maximum number of lights that will ever be on at the same time.

NoteFor first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is $$$2$$$ (e.g. at the moment $$$2$$$).In the second example, all lights are initially on. So the answer is $$$4$$$.

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 light = ns(N).map(_ == '1')
    val (a, b) = na2(N)
    var ans = light.count(identity)
    val MAX = if(oj) 1e5.toInt else 1000
    REP(MAX, 1) { i =>
      var cnt = 0
      REP(N) { j =>
        if (i - b(j) >= 0 && (i - b(j)) % a(j) == 0) {
          light(j) ^= true
        }
        if (light(j)) cnt += 1
      }
      debug(light)
      ans = max(ans, cnt)
    }
    out.println(ans)
  }
}


This is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.Integer x > 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x > 1 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.When you are done asking queries, print "prime" or "composite" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).

After each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.

Up to 20 times you can ask a query — print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input. In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program. To flush you can use (just after printing an integer and end-of-line):    fflush(stdout) in C++;  System.out.flush() in Java;  stdout.flush() in Python;  flush(output) in Pascal;  See the documentation for other languages.  Hacking. To hack someone, as the input you should print the hidden number — one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.

NoteThe hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries).

object Solution extends App {
  val in = io.Source.stdin.getLines()
  var candidates = (2 to 100).toList

  def isSimple(i: Int) = {
    (2 until i).forall(j => i % j != 0)
  }

  while (candidates.exists(isSimple) && candidates.exists(x => !isSimple(x))) {
    println(candidates.head)
    in.next() match {
      case "yes" =>
        candidates = (candidates.tail ::: List(candidates.head))filter(_ % candidates.head == 0)
      case "no" =>
        candidates = candidates.filter(_ % candidates.head != 0)
    }
  }
  if (candidates.forall(isSimple))
    println("prime")
  else
    println("composite")
}

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

object _680C extends CodeForcesApp {
  override def apply(io: IO) = {

    def isDivisor(i: Int): Boolean = {
      io.println(i)
      io[String] == "yes"
    }

    val primes = Seq( 2,  3,  5,  7, 11,
                     13, 17, 19, 23, 29,
                     31, 37, 41, 43, 47,
                     53, 59, 61, 67, 71,
                     73, 79, 83, 89, 97)

    val isComposite = Seq(2, 3, 5, 7).find(isDivisor) match {
      case Some(p) =>
        val next = primes collect {case i if i >= p && i*p <= 100 => i*p}
        next.exists(isDivisor)
      case _ =>
        false
    }

    io += (if (isComposite) "composite" else "prime")
  }
}
/****************************[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 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 = t.head.ensuring(t.size == 1)
    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 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
  }
  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 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
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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(n.min(x, y), n.max(x, y), 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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]
  def memoize[A, B](f: A => B): A ==> B = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  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 PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  /*override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }*/
  override def close() = {
    flush()
    in.close()
    super.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[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def array[A]: Write[Array[A]] = Write(_ mkString " ")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

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

object _680C extends CodeForcesApp {
  override def apply(io: IO) = {import io._
    def isDivisor(i: Int) = writeLine(i).read[Boolean]

    val primes = Seq(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)

    val isComposite = Seq(2, 3, 5, 7).filter(isDivisor) exists {p =>
      val next = primes collect {case i if i >= p && i*p <= 100 => i*p}
      next.exists(isDivisor)
    }

    write(if (isComposite) "composite" else "prime")
  }
}
/****************************[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 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 = t.head.ensuring(t.size == 1)
    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 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
  }
  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 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 toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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(n.min(x, y), n.max(x, y), 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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def newMultiMap[K, V] = map[K] to Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  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 till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  def write[@specialized A](obj: A): this.type = {
    printer.print(obj)
    this
  }
  def writeLine[@specialized A](obj: A): this.type = {
    printer.println(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeSpace(): this.type = write(' ')
  def writeAll[A](obj: Traversable[A]): this.type = write(obj mkString " ")

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


Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.

The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.

Print "YES" or "NO" (without the quotes) depending on the answer to the problem.

import java.util.StringTokenizer

object _462A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next).toArray
  def f(i: Int, j: Int) = {
    var ans = 0
    if (i - 1 >= 0 && a(i - 1)(j) == 'o') ans = ans + 1
    if (i + 1 < n && a(i + 1)(j) == 'o') ans = ans + 1
    if (j - 1 >= 0 && a(i)(j - 1) == 'o') ans = ans + 1
    if (j + 1 < n && a(i)(j + 1) == 'o') ans = ans + 1
    ans
  }

  val ans = for {
    i <- 0 until n
    j <- 0 until n
  } yield if (f(i, j) % 2 == 0) true else false

  if (ans.size == 0 || ans.reduce(_ && _)) println("YES")
  else println("NO")
}

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF263_1 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }
  val Array(n) = readInts(1)
  val arr = Array.fill(n)(readLine)

  def isEven(i:Int, j:Int):Boolean = {
    var sumo = 0
    for( (di, dj) <- Seq((-1,0), (1,0), (0, -1), (0, 1))) {
      val newi = i + di
      val newj = j + dj
      if(0 <= newi && newi < n && 0 <= newj && newj < n) {
        if(arr(newi)(newj) == 'o') {
          sumo += 1
        }
      }
    }
    sumo %2 == 0
  }

  var result = true
  for(i <- 0 until n; j <- 0 until n) {
    result = result && isEven(i, j)
  }
  if(result){
    println("YES")
  } else {
    println("NO")
  }
}

object A462 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val bo = Array.fill(n)(read.toCharArray)

    def valid(x: Int, y: Int): Boolean = {
      if(x >= 0 && y >= 0 && x < n && y < n ) true else false
    }
    val delta = Array((-1, 0), (1, 0), (0, -1), (0, 1))
    var break = false
    for(i <- 0 until n; j <- 0 until n if !break) {
      var cntO = 0
      for(d <- delta) {
        val newi = i + d._1
        val newj = j + d._2
        if(valid(newi, newj) && bo(i + d._1)(j + d._2) == 'o') {
          cntO += 1
        }
      }
      if(cntO%2 != 0) {
        println("NO")
        break = true
      }
    }
    if(!break) println("YES")
  }

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

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

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

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

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

}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-29.
 */
object A462 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val board = new Array[String](n)
    var i = 0

    while (n > i) {
      board(i) = sc.next()
      i += 1
    }

    i = 0
    var ans = 0

    while (i < n) {
      var j = 0

      while (j < n) {
        var add: Int = 0

        if (i - 1 >= 0 && board(i - 1)(j) == 'o') {
          add += 1
        }

        if (j + 1 < n && board(i)(j + 1) == 'o') {
          add += 1
        }

        if (i + 1 < n && board(i + 1)(j) == 'o') {
          add += 1
        }

        if (j - 1 >= 0 && board(i)(j - 1) == 'o') {
          add += 1
        }

        if (add % 2 == 1) {
          println("NO")
          return
        }

        j += 1
      }

      i += 1
    }

    println("YES")
  }
}

import java.util.StringTokenizer

object _462A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next).toArray
  def f(i: Int, j: Int) = {
    var ans = 0
    if (i - 1 >= 0 && a(i - 1)(j) == 'o') ans = ans + 1
    if (i + 1 < n && a(i + 1)(j) == 'o') ans = ans + 1
    if (j - 1 >= 0 && a(i)(j - 1) == 'o') ans = ans + 1
    if (j + 1 < n && a(i)(j + 1) == 'o') ans = ans + 1
    ans
  }

  val ans = for {
    i <- 0 until n
    j <- 0 until n
    if (a(i)(j) == 'x')
  } yield if (f(i, j) % 2 == 0) true else false

  if (ans.size == 0 || ans.reduce(_ && _)) println("YES")
  else println("NO")
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-29.
 */
object A462{
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val board = new Array[String](n)
    var i = 0

    while (n > i) {
      board(i) = sc.next()
      i += 1
    }

    val checked = Array.ofDim[Boolean](n, n)
    i = 0
    var ans = 0

    while (i < n) {
      var j = 0

      while (j < n) {
        if (!checked(i)(j)) {
          if (board(i)(j) == 'o') {
            var  add: Int = 0

            if (i - 1 >= 0 && board(i - 1)(j) == 'o') {
              add += 1
              checked(i - 1)(j) = true
            }

            if (j + 1 < n && board(i)(j + 1) == 'o') {
              add += 1
              checked(i)(j + 1) = true
            }

            if (i + 1 < n && board(i + 1)(j) == 'o') {
              checked(i + 1)(j) = true
              add += 1
            }

            if (j - 1 >= 0 && board(i)(j - 1) == 'o') {
              add += 1
              checked(i)(j - 1) = true
            }

            if (add % 2 == 1) {
              println("NO")
              return
            }
          }
        }

        j += 1
      }

      i += 1
    }

    println("YES")
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-29.
 */
object A462{
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val board = new Array[String](n)
    var i = 0

    while (n > i) {
      board(i) = sc.next()
      i += 1
    }

    val checked = Array.ofDim[Boolean](n, n)
    i = 0
    var ans = 0

    while (i < n) {
      var j = 0

      while (j < n) {
        if (!checked(i)(j)) {
          if (board(i)(j) == 'o') {
            var  add: Boolean = false

            if (i - 1 >= 0 && board(i - 1)(j) == 'o') {
              add = true
              checked(i - 1)(j) = true
            }

            if (j + 1 < n && board(i)(j + 1) == 'o') {
              add = true
              checked(i)(j + 1) = true
            }

            if (i + 1 < n && board(i + 1)(j) == 'o') {
              checked(i + 1)(j) = true
              add = true
            }

            if (j - 1 >= 0 && board(i)(j - 1) == 'o') {
              add = true
              checked(i)(j - 1) = true
            }

            if (add) {
              ans += 1
            }
          }
        }

        j += 1
      }

      i += 1
    }

    println(if (ans % 2 == 0) {
      "YES"
    } else {
      "NO"
    })
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-29.
 */
object A462 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val board = new Array[String](n)
    var i = 0

    while (n > i) {
      board(i) = sc.next()
      i += 1
    }

    val checked = Array.ofDim[Boolean](n, n)
    i = 0
    var ans = 0

    while (i < n) {
      var j = 0

      while (j < n) {
        if (!checked(i)(j)) {
          var add: Int = 0

          if (i - 1 >= 0 && board(i - 1)(j) == 'o') {
            add += 1
            checked(i - 1)(j) = true
          }

          if (j + 1 < n && board(i)(j + 1) == 'o') {
            add += 1
            checked(i)(j + 1) = true
          }

          if (i + 1 < n && board(i + 1)(j) == 'o') {
            checked(i + 1)(j) = true
            add += 1
          }

          if (j - 1 >= 0 && board(i)(j - 1) == 'o') {
            add += 1
            checked(i)(j - 1) = true
          }

          if (add % 2 == 1) {
            println("NO")
            return
          }
        }

        j += 1
      }

      i += 1
    }

    println("YES")
  }
}


Egor has a table of size $$$n \times m$$$, with lines numbered from $$$1$$$ to $$$n$$$ and columns numbered from $$$1$$$ to $$$m$$$. Each cell has a color that can be presented as an integer from $$$1$$$ to $$$10^5$$$.Let us denote the cell that lies in the intersection of the $$$r$$$-th row and the $$$c$$$-th column as $$$(r, c)$$$. We define the manhattan distance between two cells $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ as the length of a shortest path between them where each consecutive cells in the path must have a common side. The path can go through cells of any color. For example, in the table $$$3 \times 4$$$ the manhattan distance between $$$(1, 2)$$$ and $$$(3, 3)$$$ is $$$3$$$, one of the shortest paths is the following: $$$(1, 2) \to (2, 2) \to (2, 3) \to (3, 3)$$$. Egor decided to calculate the sum of manhattan distances between each pair of cells of the same color. Help him to calculate this sum.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \le m$$$, $$$n \cdot m \leq 100\,000$$$) — number of rows and columns in the table. Each of next $$$n$$$ lines describes a row of the table. The $$$i$$$-th line contains $$$m$$$ integers $$$c_{i1}, c_{i2}, \ldots, c_{im}$$$ ($$$1 \le c_{ij} \le 100\,000$$$) — colors of cells in the $$$i$$$-th row.

Print one integer — the the sum of manhattan distances between each pair of cells of the same color.

NoteIn the first sample there are three pairs of cells of same color: in cells $$$(1, 1)$$$ and $$$(2, 3)$$$, in cells $$$(1, 2)$$$ and $$$(2, 2)$$$, in cells $$$(1, 3)$$$ and $$$(2, 1)$$$. The manhattan distances between them are $$$3$$$, $$$1$$$ and $$$3$$$, the sum is $$$7$$$.

import scala.io.StdIn.readLine

object Solution {
  // Qc
  def f(row: Int, col: Int) = {

    def sumOf(se: Seq[(Int, (Int, Int))]): Long = {
      val (xs, ys) = se.foldLeft((List.empty[Long], List.empty[Long]))(
        (acc, elem) => {
          val (xl, yl) = acc
          (elem._2._1 :: xl, elem._2._2 :: yl)
        }
      )

      val sxs = xs.sorted.toArray
      val sys = ys.sorted.toArray
      val len = se.length

      val prefx = sxs.foldLeft(List.empty[Long], 0)(
        (acc, elem) => {
          val (arr, idx) = acc
          val x = if (idx == 0) elem else elem + arr.head
          (x :: arr, idx + 1)
        }
      )._1

      val prefy = sys.foldLeft(List.empty[Long], 0)(
        (acc, elem) => {
          val (arr, idx) = acc
          val y = if (idx == 0) elem else elem + arr.head
          (y :: arr, idx + 1)
        }
      )._1

      val maxx = prefx.head
      val maxy = prefy.head

      prefx.tail.foldLeft(0L, len - 2)(
        (acc, elem) => (acc._1 + (maxx - elem) - (len - acc._2 - 1) * sxs(acc._2), acc._2 - 1)
      )._1 +
      prefy.tail.foldLeft(0L, len - 2)(
        (acc, elem) => (acc._1 + (maxy - elem) - (len - acc._2 - 1) * sys(acc._2), acc._2 - 1)
      )._1
    }

    val g = (
      for (
        i <- 0 until row;
        arr = readLine().split("\\s+").map(_.toInt)
      ) yield arr
    )

    val m = for (
      i <- 0 until row;
      j <- 0 until col
    ) yield (g(i)(j) -> (i, j))

    val colors = m.groupBy(_._1).values
    colors.foldLeft(0L)(
      (acc, elem) => acc + sumOf(elem)
    )
  }

  def main(args: Array[String]): Unit = {
    val tup = readLine.split("\\s+")
    val row = tup(0).toInt
    val col = tup(1).toInt
    println(f(row, col))

  }

}

import scala.io.StdIn.readLine

object Solution {
  // Qc
  def f(row: Int, col: Int) = {

    def sumOf(se: Seq[(Long, (Int, Int))]): Long = {
      val (xs, ys) = se.foldLeft((List.empty[Int], List.empty[Int]))(
        (acc, elem) => {
          val (xl, yl) = acc
          (elem._2._1 :: xl, elem._2._2 :: yl)
        }
      )

      val sxs = xs.sorted.toArray
      val sys = ys.sorted.toArray
      val len = se.length

      val prefx = sxs.foldLeft(List.empty[Int], 0)(
        (acc, elem) => {
          val (arr, idx) = acc
          val x = if (idx == 0) elem else elem + arr.head
          (x :: arr, idx + 1)
        }
      )._1

      val prefy = sys.foldLeft(List.empty[Int], 0)(
        (acc, elem) => {
          val (arr, idx) = acc
          val y = if (idx == 0) elem else elem + arr.head
          (y :: arr, idx + 1)
        }
      )._1

      val maxx = prefx.head
      val maxy = prefy.head

      prefx.tail.foldLeft(0L, len - 2)(
        (acc, elem) => (acc._1 + (maxx - elem) - (len - acc._2 - 1) * sxs(acc._2), acc._2 - 1)
      )._1 +
      prefy.tail.foldLeft(0L, len - 2)(
        (acc, elem) => (acc._1 + (maxy - elem) - (len - acc._2 - 1) * sys(acc._2), acc._2 - 1)
      )._1
    }

    val g = (
      for (
        i <- 0 until row;
        arr = readLine().split("\\s+").map(_.toLong)
      ) yield arr
    )

    val m = for (
      i <- 0 until row;
      j <- 0 until col
    ) yield (g(i)(j) -> (i, j))

    val colors = m.groupBy(_._1).values
    colors.foldLeft(0L)(
      (acc, elem) => acc + sumOf(elem)
    )
  }

  def main(args: Array[String]): Unit = {
    val tup = readLine.split("\\s+")
    val row = tup(0).toInt
    val col = tup(1).toInt
    println(f(row, col))

  }

}

import scala.io.StdIn.readLine

object Solution {
  // Qc
  def f(row: Int, col: Int) = {

    def sumOf(se: Seq[(Int, (Int, Int))]): Long = {
      val (xs, ys) = se.foldLeft((List.empty[Int], List.empty[Int]))(
        (acc, elem) => {
          val (xl, yl) = acc
          (elem._2._1 :: xl, elem._2._2 :: yl)
        }
      )
      val sxs = xs.sorted.toArray
      val sys = ys.sorted.toArray
      val len = se.length

      val prefx = sxs.foldLeft(List.empty[Int], 0)(
        (acc, elem) => {
          val (arr, idx) = acc
          val x = if (idx == 0) elem else elem + arr.head
          (x :: arr, idx + 1)
        }
      )._1

      val prefy = sys.foldLeft(List.empty[Int], 0)(
        (acc, elem) => {
          val (arr, idx) = acc
          val y = if (idx == 0) elem else elem + arr.head
          (y :: arr, idx + 1)
        }
      )._1

      val maxx = prefx.head
      val maxy = prefy.head

      prefx.tail.foldLeft(0L, len - 2)(
        (acc, elem) => (acc._1 + (maxx - elem) - (len - acc._2 - 1) * sxs(acc._2), acc._2 - 1)
      )._1 +
      prefy.tail.foldLeft(0L, len - 2)(
        (acc, elem) => (acc._1 + (maxy - elem) - (len - acc._2 - 1) * sys(acc._2), acc._2 - 1)
      )._1
      // (0 until len).foldLeft(0)((acc, elem) => acc + (elem until len).foldLeft(0)((a, e) => a + dist(lst(elem)._2, lst(e)._2)))
    }

    def dist(l: (Int, Int), r: (Int, Int)) = {
      Math.abs(l._1 - r._1) + Math.abs(l._2 - r._2)
    }

    val g = (
      for (
        i <- 0 until row;
        arr = readLine().split("\\s+").map(_.toInt)
      ) yield arr
    )

    val m = for (
      i <- 0 until row;
      j <- 0 until col
    ) yield (g(i)(j) -> (i, j))

    val colors = m.groupBy(_._1).values
    colors.foldLeft(0L)(
      (acc, elem) => acc + sumOf(elem)
    )
  }

  def main(args: Array[String]): Unit = {
    val tup = readLine.split("\\s+")
    val row = tup(0).toInt
    val col = tup(1).toInt
    println(f(row, col))

  }

}


One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the fi-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator).What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?

The first line contains two integers n and k (1 ≤ n, k ≤ 2000) — the number of people and the maximal capacity of the elevator. The next line contains n integers: f1, f2, ..., fn (2 ≤ fi ≤ 2000), where fi denotes the target floor of the i-th person.

Output a single integer — the minimal time needed to achieve the goal.

NoteIn first sample, an optimal solution is:   The elevator takes up person #1 and person #2.  It goes to the 2nd floor.  Both people go out of the elevator.  The elevator goes back to the 1st floor.  Then the elevator takes up person #3.  And it goes to the 2nd floor.  It picks up person #2.  Then it goes to the 3rd floor.  Person #2 goes out.  Then it goes to the 4th floor, where person #3 goes out.  The elevator goes back to the 1st floor.

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine split ' ' map (_ toInt)
    val f: Array[Int] = readLine split ' ' map (_ toInt) sortWith (_ > _)
    println({ for (i <- (0 to ((n - 1) / k))) yield 2 * f(i * k) - 2 } reduceLeft (_ + _))
  }
}

import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 28.09.14.
 */
object B extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextInt
    val k = nextInt
    val fs = Array.fill(2001)(0)
    for (i <- 0 until n) {
      val f = nextInt
      fs(f) += 1
    }

    var last = 2000
    def func(acc: Int): Int = {
      if (last == 0 && fs(last) == 0) {
        acc
      } else {
        if (fs(last) == 0) {
          last -= 1
          func(acc)
        } else {
          var s = 0
          val cost = 2 * (last - 1)
          while (s < k && last >= 0) {
            val add = math.min(fs(last), k - s)
            s += add
            fs(last) -= add
            if (fs(last) == 0) {
              last -= 1
            }
          }
          if (last == -1) {
            last = 0
          }
          func(acc + cost)
        }
      }
    }

    out.print(func(0))
  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}

import java.util.StringTokenizer

object _472B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt
  val a = (1 to n).map(i => next.toInt - 1).sortBy(i => -i).toList
  def f(a: List[Int]): Int = {
    val (head, tail) = a.splitAt(k)
    2 * head.head + (if (tail != Nil) f(tail) else 0)
  }
  println(f(a))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt).sorted
  val r = data.foldLeft((1, 0, data.length)) {
    case((current, soFar, left), el) if el == current => (current, soFar, left - 1)
    case((current, soFar, left), el) if left <= k => (el, soFar + (el - current), left - 1)
    case((current, soFar, left), el) =>
      var count = left / k
      if (left % k > 0) count += 1
      if (count > 1) count = count * 2 - 1
      (el, soFar + count * (el - current), left - 1)

  }
  println(data.last + r._2 - 1)
}

object TaskA {
  def main(args: Array[String]) {
    val Array(n, k) = readLine split ' ' map(_ toInt)
    val f: Array[Int] = readLine split ' ' map(_ toInt) sortWith(_ > _)
    println({for (i <- (0 to ((n - 1) / k))) yield 2 * f(i * k) - 2} reduceLeft(_ + _))
  }
}

object B472 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val in = readInts(n).sorted.reverse
    val ans = in.grouped(k).map(arr => arr.max*2 - 2).sum
    println(ans)
  }

  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.math._
import scala.util.Sorting._

object Main extends App{
  val pass = readLine.split(" ").map(x => x.toInt)
  var n = pass(0)
  var k = pass(1)

  var floors = readLine.split(" ").map(x => x.toInt - 1).sorted.toList.reverse

  var result = List[Int]()
  var s = 0

  while(n > 0) {
    result = floors drop k
    s += (floors take k).max * 2
    floors = result
    n -= k
  }

  println(s)
}

import scala.collection._

object B extends App {

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

  val Array(n, k) = readInts(2)
  val fs = readInts(n).sorted.reverse

  var ans = 0L
  var pos = 0

  while (pos < n) {
    ans += 2 * (fs(pos) - 1)
    pos += k
  }

  println(ans)
}

object B {
   def READ: Array[Int] = readLine() split (" ") map (_.toInt);

   def main(args: Array[String]) {
     var Array(n, k) = READ;
     var f:Array[Int] = READ;
     println(f.sorted.reverse.zipWithIndex.filter(_._2 % k == 0) map (2*_._1 -2) sum)
   }
 }

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by Kuang.Ru on 14-10-9.
 */
object B472 extends App{
  val sc = new Scanner(System.in)
  val n, k = sc.nextInt()
  var i = 0
  val f = new ArrayBuffer[Int]()

  while (i < n) {
    f += sc.nextInt()
    i += 1
  }

  val newF = f.sorted
  var time = 0
  i = newF.length - 1

  while (i >= 0) {
    time += (newF(i) - 1) * 2
    i -= k
  }

  println(time)
}

import Array._

object main extends App with fastIO {

  val Array(n, k) = readLine split(" ") map(_.toInt)
  println(readLine.split(" ").map(_.toInt).sortWith(_ > _).sliding(k, k).map(_.max - 1).sum * 2)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

object Elevator extends App {

  def applyToChunks(seq: List[Int], length: Int, fun: List[Int] => Int): List[Int] = {
    seq match {
      case Nil => Nil
      case x: List[Int] => fun(x.take(length)) :: applyToChunks(x.drop(length), length, fun)
    }
  }

  val nk: String = readLine()
  val ff: String = readLine()

  val Array(n: Int, k: Int) = nk.split(' ').map(_.toInt)
  val f: List[Int] = ff.split(' ').map(_.toInt).sortBy(x => -x).toList

  val result: Int = applyToChunks(f, k, { x => (x.max - 1) * 2 }).sum

  println(result)

}

import scala.math._
import scala.util.Sorting._

object Main extends App{
  val pass = readLine.split(" ").map(x => x.toInt)
  var n = pass(0)
  var k = pass(1)

  var floors = readLine.split(" ").map(x => x.toInt - 1).sorted.toList

  var result = List[Int]()
  var s = 0

  while(n > 0) {
    result = floors drop k
    s += (floors take k).max * 2
    floors = result
    n -= k
  }

  println(s)
}