/**
  * 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))
  }

}

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

}

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

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

}


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


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


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

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 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
  } 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.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")
  }
}


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


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

  (0 until t).foreach { _ =>
    val Array(n, m, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val t = n / k
    val ans =
      if (t >= m) m
      else t - 1 - (m - t - 1) / (k - 1)

    println(ans)
  }
}

//package codeforces.contests._1359

object _1 {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, m, k) = io.StdIn.readLine.split(" ").map(_.toInt)

      val each = n / k

      val first = each min m

      val remaining = m - first

      val second = remaining / (k - 1) + (if (remaining % (k-1) != 0) 1 else 0)

      println {
        if (first == second) 0 else first - second
      }
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 0 until t){
      val input = StdIn.readLine.trim.split(" ").map(_.toInt)
      val (n, m, k) = (input(0), input(1), input(2))
      val c = n / k
      val m1 = c min m
      if (k == 1) println(m)
      else {
        // k-1 person m - m1 joker
        val m2 = if ((m-m1) % (k-1) == 0) (m-m1)/(k-1) else (m-m1)/(k-1)+1
        println(0 max (m1 - m2))
      }
    }
  }
}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val m = in.nextInt()
    val k = in.nextInt()

    val maxCount = math.min(m, n / k)
    val leftCount = m - maxCount
    val maxOponent = leftCount / (k - 1) + (if (leftCount % (k - 1) > 0) 1 else 0)

    println(math.max(0, maxCount - maxOponent))
  }

}

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

  (0 until t).foreach { _ =>
    val Array(n, m, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val t = n / k
    val ans =
      if (t >= m) m
      else t - ((m - t) / (k - 1) + (m - t) % (k - 1))

    println(ans)
  }
}


object CF_540_3_B {
// date: 19/02/2019

  type In  = (Int, Seq[Int])
  type Out = Int

  def solve(in: In): Out = {
    val (n, xs) = in
    val totals = Array(0,0)
    val m = collection.mutable.Map[Int,Int]() withDefaultValue 0
    xs.indices foreach { i =>
      m += (i -> (xs(i) + totals(i%2)))
      totals(i%2) += xs(i)
    }
    xs.indices count { i =>
      m(i-1) + totals(i%2) - m(i) == m(i-2) + totals((i+1)%2) - m(i-1)
    }
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val cumE, cumO = Array.ofDim[Int](N + 1)
    REP(N) { i =>
      cumE(i + 1) = cumE(i)
      cumO(i + 1) = cumO(i)
      if (i % 2 == 0) cumE(i + 1) += A(i)
      else cumO(i + 1) += A(i)
    }

//    debug(cumE)
//    debug(cumO)

    var ans = 0
    REP(N) { i =>
      val even = cumE(i) + (cumO(N) - cumO(i + 1))
      val odd = cumO(i) + (cumE(N) - cumE(i + 1))
      if (even == odd) ans += 1
    }

    out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

object CF_540_3_B {
// date: 19/02/2019

  type In  = (Int, Seq[Int])
  type Out = Int

  def solve(in: In): Out = {
    val (n, xs) = in
    val arr = Array.ofDim[Int](xs.length)
    val totals = Array(0,0)
    val m = collection.mutable.Map[Int,Int]() withDefaultValue 0
    for {
      i <- arr.indices
    } {
      m += (i -> (xs(i) + totals(i%2)))
      totals(i%2) += xs(i)
    }
    var goodCount = 0
    for {
      i <- arr.indices
    } {
      val E1 = m(i-1) + totals(i%2) - m(i)
      val E2 = m(i-2) + totals((i+1)%2) - m(i-1)
      if(E1 == E2) goodCount += 1
    }
    goodCount
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


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

import scala.util.Sorting

object Solution {
  def gcd(a: Long, b: Long): (Long, Long) = {
    if (a == 0)
      return (0, 1)
    if (b == 0)
      return (1, 0)
    val t = gcd(b % a, a)
    val x = t._2 - (b / a) * t._1
    val y = t._1
    return (x, y)
  }

  def getInv(x: Long, mod: Long): Long = {
    val t = gcd(x, mod)
    return t._1
  }

  def solve(in: FastScanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val m = in.nextInt()
    val dx = in.nextInt()
    val dy = in.nextInt()
    val count = new Array[Int](n)
    for (i <- 0 until m) {
      val x = in.nextInt()
      val y = in.nextInt()
      val inv: Long = getInv(dx, n)
      val k: Long = (-x * inv % n + n) % n
      val startY: Int = ((y + k * dy) % n).toInt
      count(startY) += 1
    }
    var maxY = 0
    for (i <- 0 until n)
      if (count(i) > count(maxY))
        maxY = i
    out.println(0 + " " + maxY)
  }

  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.collection._

object E extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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, m, dx, dy) = readInts(4)

  val idx = BigInt(dx).modInverse(n).toLong
  val idy = BigInt(dy).modInverse(n).toLong

  val cnt = Array.fill(n){ 0 }

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    val s = idx * (n - x) % n
    val Y = (y + dy * s) % n
    cnt(Y.toInt) += 1
  }

  var maxPos = 0

  for (i <- 0 until n) if (cnt(i) > cnt(maxPos)) maxPos = i

  println(s"0 $maxPos")
}


object B732 {
  @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, k) = readInts(2)
    val input = readInts(n)
    val sum = input.sum
    for(i <- 1 until n) {
      if(input(i) + input(i-1) < k)
        input(i) += math.max(k - input(i) - input(i-1), 0)
    }
    println(input.sum - sum)
    println(input.mkString(" "))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val (_, ans) = line.foldLeft(k, List.empty[Int]) {
    case((left, ans), el) =>
      val today = el + Math.max(0, k - left - el)
      (today, today :: ans)
  }
  println(ans.sum - line.sum)
  println(ans.reverse.mkString(" "))
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {

  def gcd (a: Int, b: Int): Int = if(b == 0) a else gcd(b,a%b)
  def lcm (a: Int, b: Int) = a*b/gcd(a,b)
  case class Res(val lst: List[Int], val cnt: Int)

  def additional_days(xs: List[Int], counter: Int, k: Int, buf: Int): Res = {
    if (xs.isEmpty) Res(List(buf), counter)
    else {
      var res = Res(List(), 0)
      if (buf + xs.head >= k) res = additional_days(xs.tail, counter, k, xs.head)
      else res = additional_days(xs.tail, counter + (k-(buf+xs.head)), k, k-buf)
      Res(buf :: res.lst, res.cnt)
    }
  }

  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val k = sc.nextInt()
  val xs = List.range(0, n).map(_ => sc.nextInt())
  val res = additional_days(xs.tail, 0, k, xs.head)
  println(res.cnt)
  res.lst foreach { x => print(x); print(' ')}
}

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

import scala.annotation.tailrec

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

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

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

  // Standard code above, custom code below

  import math._

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val line1 = lines.next()
    val line1Strings = line1.split(" ")
    val n = line1Strings(0).toInt
    val k = line1Strings(1).toInt
    val line2 = lines.next()
    val aValues = line2.split(" ").map(_.toInt)
    val soln = solve(n, k, aValues)
    bw.write(soln.extraWalks.toString)
    bw.newLine()
    bw.write(soln.b.mkString(" "))
    bw.newLine()
  }

  case class Solution(val extraWalks: Int, val b: Seq[Int])

  def solve(n: Int, k: Int, a: IndexedSeq[Int]): Solution = {
    case class Accumulator(walksOnPreviousDay: Int, solution: Solution)

    val b = Array.ofDim[Int](n)
    b(0) = a(0)
    for (i <- 1 until n) {
      b(i) = math.max(a(i), k - b(i - 1))
    }
    val extraWalks = a.zip(b).map(x => x._2 - x._1).sum
    Solution(extraWalks, b)
  }
}

object B732 extends App {
  val init = readLine split " " map(_.toInt)
  val k = init(1)

  val steps = readLine split " " map(_.toInt)
  var n = 0
  val result = steps.tail.foldLeft(List(steps head))((a, el) =>
      if (a.head + el < k) {
        val t  = k - el - a.head
            n  = n + t
        (t + el) :: a
      } else el :: a
    )

  println(n)
  println(result.reverse.mkString(" "))
}

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

object _732B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n, k = read[Int]
    val walks = read[Array, Int](n)
    var ans = 0

    until(n-1) foreach {i =>
      val d1 = walks(i)
      val d2 = walks(i + 1)
      val needed = k - (d1 + d2)
      if (needed > 0) {
        walks(i + 1) += needed
        ans += needed
      }
    }

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

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

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

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

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

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

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

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

import java.util.Scanner

import scala.language.postfixOps
import scala.math.max

object TaskB extends App {
  val sc = new Scanner(System.in)
  val (n, k) = (sc.nextInt, sc.nextInt)
  // val as = new Array[Int](n)
  var walks = 0
  var prev = 0

  val out = 0 until n map { i =>
    val a = sc.nextInt
    val b = if (i > 0) max(k - a - prev, 0) else 0
    walks += b
    prev = a + b
    prev
  } mkString " "

  println(walks)
  println(out)
}