object C1201 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readLongs(2)
    val arr = readLongs(n.toInt).sorted
    val midPos = n.toInt / 2
    val median = arr(midPos)
    var res = median
    def check(num: Long): Boolean = {
      var score = 0L
      for (i <- midPos until n.toInt) {
        if (num > arr(i))
          score += num - arr(i)
        if (score > k) return false
      }
      if (score <= k) true
      else false
    }
    var s = 1L
    var e = 2000000000L
    while (s <= e) {
      val mid = (s + e) / 2
      if (check(mid)) {
        res = mid
        s = mid + 1
      } else {
        e = mid - 1
      }
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.StdIn._

object C_1201 extends App {

  val Array(n, k) = readLine().split(" ").map(_.toInt)
  var A = readLine().split(" ").map(_.toLong).sorted
//  println(A.mkString(","))

  val prefix = Array.ofDim[Long](n)

  val m = n / 2
  prefix(m) = A(m)
  for (i <- m + 1 until n) {
    prefix(i) = prefix(i - 1) + A(i)
  }
//  println(prefix.mkString(","))

  def binSearch(x: Long) = {
    var l = m
    var r = n - 1

    while (l < r) {
      val mid = ((l.toLong + r.toLong) / 2).toInt
      if (A(mid) >= x) r = mid - 1
      else l = mid + 1
    }

    if (r < n && A(r) < x) r else r - 1

    // m/2 .. r => < x
  }

  def findMax = {
    var max = A(m)
    var l = A(m) + 1
    var r = A(m) + k
    while (l <= r) {
      val mid = (l + r) / 2
      val j = binSearch(mid)
      if (prefix(j) + k >= (j - m + 1) * mid) {
        max = mid
        l = mid + 1
      } else {
        r = mid - 1
      }
    }
//    for (i <- A(m) + 1 to A(m) + k) {
//      val j = binSearch(i)
//      if (prefix(j) + k >= (j - m + 1) * i) max = i
//    }
    max
  }

  println(findMax)
}

object C1201 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    var Array(n, k) = readInts(2)
    val arr = readInts(n).sorted
    val midPos = n / 2
    val median = arr(midPos)
    var res = median
    val max = arr.max
    val minScore = arr.takeRight(midPos + 1).map(max - _).sum
    if (minScore <= k) {
      res = max
      k -= minScore
      var s = 1
      var e = k / (midPos + 1)
      while (s <= e) {
        val mid = (s + e) / 2
        if ((mid * (midPos + 1)) <= k) {
          res = max + mid
          s = mid + 1
        } else {
          e = mid - 1
        }
      }
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

}

object C1201 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    var Array(n, k) = readLongs(2)
    val arr = readLongs(n.toInt).sorted
    val midPos = n.toInt / 2
    val median = arr(midPos)
    var res = median
    val max = arr.max
    val minScore = arr.takeRight(midPos + 1).map(max - _).sum
    if (minScore <= k) {
      res = max
      k -= minScore
      var s = 1L
      var e = k
      while (s <= e) {
        val mid = (s + e) / 2
        if ((mid * (midPos + 1)) <= k) {
          res = max + mid
          s = mid + 1
        } else {
          e = mid - 1
        }
      }
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

}

object C1201 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    var Array(n, k) = readLongs(2)
    val arr = readLongs(n.toInt).sorted
    val midPos = n.toInt / 2
    val median = arr(midPos)
    var res = median
    val max = arr.max
    val minScore = arr.takeRight(midPos + 1).map(max - _).sum
    if (minScore <= k) {
      res = max
      k -= minScore
      var s = 1L
      var e = k / (midPos + 1)
      while (s <= e) {
        val mid = (s + e) / 2
        if ((mid * (midPos + 1)) <= k) {
          res = max + mid
          s = mid + 1
        } else {
          e = mid - 1
        }
      }
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.StdIn._

object C_1201 extends App {

  val Array(n, k) = readLine().split(" ").map(_.toInt)
  var A = readLine().split(" ").map(_.toInt).sorted
//  println(A.mkString(","))

  val prefix = Array.ofDim[Long](n)

  val m = n / 2
  prefix(m) = A(m)
  for (i <- m + 1 until n) {
    prefix(i) = prefix(i - 1) + A(i)
  }
//  println(prefix.mkString(","))

  def binSearch(x: Int) = {
    var l = m
    var r = n - 1

    while (l < r) {
      val mid = ((l.toLong + r.toLong) / 2).toInt
      if (A(mid) >= x) r = mid - 1
      else l = mid + 1
    }

    if (r < n && A(r) < x) r else r - 1

    // m/2 .. r => < x
  }

  def findMax = {
    var max = A(m)
    var l = A(m) + 1
    var r = A(m) + k
    while (l <= r) {
      val mid = ((l.toLong + r.toLong) / 2).toInt
      val j = binSearch(mid)
      if (prefix(j) + k >= (j - m + 1) * mid) {
        max = mid
        l = mid + 1
      } else {
        r = mid - 1
      }
    }
//    for (i <- A(m) + 1 to A(m) + k) {
//      val j = binSearch(i)
//      if (prefix(j) + k >= (j - m + 1) * i) max = i
//    }
    max
  }

  println(findMax)
}


object B {
  import scala.collection.mutable
  def main(args: Array[String]){
    val line1 = readLine().split(" ")
    val line2 = readLine().split(" ").map(_.toInt)
    val n = line1(0).toInt
    val k = line1(1).toInt
    val boxes = mutable.Map[Int, Int]()
    line2.zipWithIndex.foreach{ case (box, idx) =>
      val rem = box % k
      if(!boxes.contains(rem)) boxes(rem) = 0
      boxes(rem) += 1
    }

    var total = 0

    line2.foreach{ l =>
      val rem = l % k
      val miss = (k - rem) % k
      if(boxes.contains(miss)) {
        if (rem == miss) {
          if(boxes(miss) > 1) {
            boxes(miss) -= 2
            total += 2
          }
        } else {
          if(boxes(miss) > 0 && boxes(rem) > 0) {
            boxes(miss) -= 1
            boxes(rem) -= 1
            total += 2
          }
        }
      }
    }

    println(total)
  }
}

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, K = ni()
    val A = na(N)
    val byM = Array.ofDim[Int](K)
    REP(N) { i =>
      byM(A(i) % K) += 1
    }

    DEBUG {
      REP(K) { i =>
        debug(byM(i).toString)
      }
    }

    var ans = 0
    REP(K) { i =>
      if (i <= K - i) {
        if (i == (K - i) % K) {
          ans += byM(i) / 2 * 2
        } else {
          val v = min(byM(i), byM((K - i) % K))
          ans += v * 2
        }
      }
    }
    out.println(ans)
  }

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

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

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    import java.util
    val N, K = ni()
    val A = na(N)
    val byM = Array.fill[util.ArrayDeque[Int]](K)(new util.ArrayDeque[Int]())
    REP(N) { i =>
      byM(A(i) % K).add(A(i))
    }

    DEBUG {
      REP(K) { i =>
        debug(byM(i).toString)
      }
    }

    var ans = 0
    REP(K) { i =>
      while (!byM(i).isEmpty && !byM((K - i) % K).isEmpty && !(i == 0 && byM(i).size < 2)) {
        byM(i).poll()
        byM((K - i) % K).poll()
        ans += 2
      }
    }
    out.println(ans)
  }

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

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

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

object B {
  import scala.collection.mutable
  def main(args: Array[String]){
    val line1 = readLine().split(" ")
    val line2 = readLine().split(" ").map(_.toInt)
    val n = line1(0).toInt
    val k = line1(1).toInt
    val boxes = Array.ofDim[Int](n)
    line2.zipWithIndex.foreach{case (box, idx) => boxes(idx) = box}

    var total = 0

    val used = mutable.Set[Int]()
    boxes.indices.foreach { i =>
      if(!used.contains(i)) {
        boxes.indices.foreach { j =>
          if(i != j && !used.contains(j)) {
            if((boxes(i) + boxes(j)) % k == 0) {
              total += 1
              used += i
              used += j
            }
          }
        }
      }
    }
    println(total)
  }
}

object B {
  import scala.collection.mutable
  def main(args: Array[String]){
    val line1 = readLine().split(" ")
    val line2 = readLine().split(" ").map(_.toInt)
    val n = line1(0).toInt
    val k = line1(1).toInt
    val boxes = mutable.Map[Int, Int]()
    line2.zipWithIndex.foreach{ case (box, idx) =>
      val rem = box % k
      if(!boxes.contains(rem)) boxes(rem) = 0
      boxes(rem) += 1
    }

    var total = 0

    line2.foreach{ l =>
      val rem = l % k
      val miss = (k - rem) % k
      if(boxes.contains(miss)) {
        if (rem == miss) {
          if(boxes(miss) > 1) {
            boxes(miss) -= 2
            total += 2
          }
        } else {
          if(boxes(miss) > 0) {
            boxes(miss) -= 1
            boxes(rem) -= 1
            total += 2
          }
        }
      }
    }

    println(total)
  }
}

object B {
  def main(args: Array[String]){
    val line1 = readLine().split(" ")
    val line2 = readLine().split(" ").map(_.toInt)
    val n = line1(0).toInt
    val k = line1(1).toInt
    val boxes = Array.ofDim[Int](n)
    line2.zipWithIndex.foreach{ case (box, idx) =>
      val rem = box % k
      if(!boxes.contains(rem)) boxes(rem) = 0
      boxes(rem) += 1
    }

    var total = 0

    line2.foreach{ l =>
      val rem = l % k
      val miss = (k - rem) % 2
      if(boxes.contains(miss)) {
        if (rem == miss) {
          if(boxes(miss) > 1) {
            boxes(miss) -= 2
            total += 2
          }
        } else {
          if(boxes(miss) > 0) {
            boxes(miss) -= 1
            boxes(rem) -= 1
            total += 2
          }
        }
      }
    }

    println(total)
  }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val sorted = data.zipWithIndex.sorted
  var j = 0
  var k = 0
  while(k < n) {
    if (j >= sorted(k)._1)
      j += 1
    else
      j = sorted(k)._1
    data(sorted(k)._2) = j
    k += 1
  }
  println(data.mkString(" "))
}

//package GoodBye2013

import scala.io.Source

/**
 * User: Oleg
 * Date: 1/2/14
 * Time: 3:27 AM
 */
object C {
  def main(args: Array[String]) {
    val in = Source.stdin.getLines
    val n = in.next().toInt
    val solution = Array.fill(n)(0)
    val a = in.next().split(' ').map(_.toInt).zipWithIndex.sorted.foldLeft(0)((prev, elem) => elem match {
      case (x, index) => {
        val next = if (x <= prev) prev + 1 else x
        solution(index) = next
        next
      }})
    println(solution.mkString(" "))
  }
}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object C397 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[(Int,Int)] = scala.io.StdIn.readLine().split(" ").map(_.toInt).zipWithIndex.sortBy(_._1)
    val b: Array[Int] = Array.ofDim[Int](n)
    b(a(0)._2) = a(0)._1
    var min = a(0)._1 + 1
    for (i <- 1 until n) {
      val give = min max a(i)._1
      b(a(i)._2) = give
      min = give + 1
    }
    println(b.mkString(" "))
  }

  solve()

}

//package codeforces

import java.io.InputStreamReader
import scala.util.Sorting

/**
 * TODO: describe
 *
 * @author keks
 */
object T379C {
  private var rand = new java.util.Random()

  def main(args: Array[String]) {
    readInt()
    getDifferentRatings(readLine().split(' ').map(_.toInt)).foreach(x => print(x + " "))
  }

  def getDifferentRatings(s: Array[Int]): List[Int] = s match {
    case Array() => Nil
    case l =>
      val n: Int = l.length

      val is = (0 until n).toArray
      quicksort(l, is, 0, n - 1)

      var max = Int.MinValue
      for (i <- 0 until n) {
        val e: Int = l(i)
        if (e > max) {
          l(i) = e
          max = e
        } else {
          max += 1
          l(i) = max
        }
      }

      quicksort(is, l, 0, n - 1)
      l.toList
  }

  /**
   * Synchronously quicksort both arrays
   */
  def quicksort(a: Array[Int], is: Array[Int], l: Int, r: Int) {
    if (r <= l) return

    val midIdx = rand.nextInt(r - l + 1) + l
    var mid = a(midIdx)

    swap(a, r, midIdx)
    swap(is, r, midIdx)

    var p1 = l
    var p2 = l
    while (p2 < r) {
      if (a(p2) < mid) {
        swap(a, p1, p2)
        swap(is, p1, p2)
        p1 += 1
        p2 += 1
      } else p2 += 1
    }

    swap(a, r, p1)
    swap(is, r, p1)

    // optimization to handle equal elements
    val newR = p1 - 1
    while (a(p1) == mid && p1 < r) p1 += 1

    quicksort(a, is, l, newR)
    quicksort(a, is, p1, r)
  }

  def swap(a: Array[Int], from: Int, to: Int) {
    if (from == to) return

    var tmp = a(from)
    a(from) = a(to)
    a(to) = tmp
  }
}

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

        val B = Array.ofDim[Long](n)
        solve(A, B, 0)
        println(B.mkString(" "))
    }

    def solve(A: List[(Long, Int)], B: Array[Long], maxi: Long) {
        A match {
            case x::xs => {
                val res = Math.max(maxi, x._1)
                val pos = x._2
                B(pos) = res
                solve(xs, B, res + 1)
            }
            case Nil => Nil
        }
    }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(" ").map(_.toInt).toArray

    val used = new java.util.TreeMap[Int, Int]()

    val r = new Array[Int](a.size)

    for (i <- 0 until a.length) {
      val exp = a(i)
      val v = used.floorEntry(exp)
      if (v == null || v.getValue < exp) {
        r(i) = exp
        if (used.containsKey(exp + 1)) {
          used.put(exp, used.get(exp + 1))
          used.remove(exp + 1)
        } else
          used.put(exp, exp + 1)
      } else {
        r(i) = v.getValue
        if (used.containsKey(v.getValue + 1)) {
          used.put(v.getKey, used.get(v.getValue + 1))
          used.remove(v.getValue + 1)
        } else {
          used.put(v.getKey, v.getValue + 1)
        }
      }
    }

    print(r.mkString(" "))
  }
}

import scala.collection._

object C extends App {

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

  val n = readInt
  val as = (readLongs(n).zipWithIndex).sortBy(_._1)

  val bs = Array.ofDim[Long](n)

  var x = 0L

  for (a <- as) {
    val give = x max a._1
    bs(a._2) = give
    x = give + 1
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(bs.mkString(" "))
  Console.flush
}

import java.util.Scanner
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.nio.CharBuffer
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

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

  object Input {
    import java.lang.Character._

    lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))
    var buf: Array[Char] = Array()
    var pos: Int = 0

    def next(): String = {
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      while (isWhitespace(buf(pos))) {
        pos += 1
      }
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      val s = pos
      while (pos < buf.length && !isWhitespace(buf(pos))) {
        pos += 1
      }
      new java.lang.String(buf, s, pos - s)
    }

    def nextInt(): Int = next.toInt

    def nextLong(): Long = next.toLong

    def nextFloat(): Float = next.toFloat

    def nextDouble(): Double = next.toDouble

    val nextString: () => String = next _
  }

  import Input._

  val N = nextInt
  val A = Array.fill(N)(nextInt)
  val S = Array.tabulate(N)(identity[Int]).sortBy(A(_))
  val res = Array.fill(N)(0)

  var r = 0
  var i = 0
  var j = 0
  while (i < N) {
    j = S(i)
    r = if ((r + 1) > A(j)) (r + 1)
        else A(j)
    res(j) = r
    i = i + 1
  }

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

//package GoodBye2013

import scala.io.Source

/**
 * User: Oleg
 * Date: 1/2/14
 * Time: 3:27 AM
 */
object C {
  def main(args: Array[String]) {
    val in = Source.stdin.getLines
    val n = in.next().toInt
    val solution = Array.fill(n)(0)
    val a = in.next().split(' ').zipWithIndex.sorted.foldLeft(0)((prev, elem) => elem match {
      case (str, index) => {
        val x = str.toInt
        val next = if (x <= prev) prev + 1 else x
        solution(index) = next
        next
      }})
    println(solution.mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).zipWithIndex.sorted
  var j = 0
  (0 until n).foreach { case(i) =>
    if (j >= data(i)._1) {
      j += 1
      data(i) = (j, data(i)._2)
    }
  }
  println(data.sortBy(_._2).map(_._1).mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).zipWithIndex.sorted
  var j = 0
  var k = 0
  while(k < n) {
    if (j >= data(k)._1) {
      j += 1
      data(k) = (j, data(k)._2)
    }
    k += 1
  }
  println(data.sortBy(_._2).map(_._1).mkString(" "))
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(" ").map(_.toInt).toArray

    val used = new java.util.TreeMap[Int, Int]()

    val r = new Array[Int](a.size)

    for (i <- 0 until a.length) {
      val exp = a(i)
      val v = used.floorEntry(exp)
      if (v == null || v.getValue < exp) {
        if (used.containsKey(exp + 1)) {
          used.put(exp, used.get(exp + 1))
          used.remove(exp + 1)
        } else
          used.put(exp, exp + 1)
        r(i) = exp
      } else {
        r(i) = v.getValue
        if (used.containsKey(v.getValue)) {
          used.put(v.getKey, used.get(v.getValue))
          used.remove(v.getValue)
        } else {
          used.put(v.getKey, v.getValue + 1)
        }
      }
    }

    print(r.mkString(" "))
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(" ").map(_.toInt).toArray

    val used = new java.util.TreeMap[Int, Int]()

    val r = new Array[Int](a.size)

    for (i <- 0 until a.length) {
      val exp = a(i)
      val v = used.floorEntry(exp)
      if (v == null) {
        if (used.containsKey(exp + 1)) {
          used.put(exp, used.get(exp + 1))
          used.remove(exp + 1)
        } else
          used.put(exp, exp + 1)
        r(i) = exp
      } else {
        r(i) = v.getValue
        if (used.containsKey(v.getValue)) {
          used.put(v.getKey, used.get(v.getValue))
          used.remove(v.getValue)
        } else {
          used.put(v.getKey, v.getValue + 1)
        }
      }
    }

    print(r.mkString(" "))
  }
}

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

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

  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)
  val S = List.range(0, N).sortBy(A(_))
  val res = Array.fill(N)(0)

  var r = 0
  S foreach { i =>
    r = ((r + 1) max A(i))
    res(i) = r
  }
  res.foreach { n =>
    out.print(res.toString)
    out.print(" ")
  }
  out.close
}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object C397 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val b: Array[Int] = Array.ofDim[Int](n)
    val s: mutable.Set[Int] = mutable.Set.empty
    b(0) = a(0)
    s += a(0)
    var min = a(0)+1
    for (i <- 1 until n) {
      var elem = math.max(min, a(i))
      while (s.contains(elem)) {
        elem += 1
      }
      s.add(elem)
      b(i) = elem
      min = elem
    }
    println(b.mkString(" "))
  }

  solve()

}


object C extends App {
  import scala.io.StdIn._
  import scala.annotation.tailrec

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

//    @tailrec
//    def clean(pair: (Int, Int), pairs: List[(Int, Int)]): List[(Int, Int)] = pairs match {
//      case (a, b) :: ps if (a < pair._2) => clean((a, pair._2), ps)
//      case _                             => pair :: pairs
//    }

//    @tailrec
//    def collapse(from: Int = 0, pairs: List[(Int, Int)] = List.empty): Boolean =
//      if (from == -1) pairs.length == 1
//      else {
//        val a  = an(from)
//        val to = an.indexWhere(_ < a)
//        val pair = (from until (if (to == -1) n else to)).foldLeft((n, 0)) {
//          case ((x, y), j) => (x min an(j), y max an(j))
//        }
//
//        collapse(to, clean(pair, pairs))
//      }

    val ans = an.head < an.last

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

import java.util

import scala.collection.mutable

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextInts(n)

      //val stack = mutable.Stack.empty[Int]
      val stack = new util.Stack[Int]
      for (a <- as) {
        while (stack.size > 1 && stack.peek() < a) {
          stack.pop()
        }
        if (stack.isEmpty || stack.peek() > a) {
          stack.push(a)
        }
      }

      out.println(if (stack.size <= 1) "YES" else "NO")
    }

    out.flush()
  }

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


import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

/**
  * Created by hama_du on 2014/06/19.
  */
object ProblemC extends App {
  class UnionFind(n: Int) {
    val parent = (0 until n).toArray
    val rank = new Array[Int](n)

    def find(x: Int): Int = {
      if (parent(x) == x) {
        return x
      }
      parent(x) = find(parent(x))
      return parent(x)
    }

    def unite(x: Int, y: Int) {
      val fx = find(x)
      val fy = find(y)
      if (fx == fy) {
        return
      }
      if (rank(fx) < rank(fy)) {
        parent(fx) = fy
      } else {
        parent(fy) = fx
        if (rank(fx) == rank(fy)) {
          rank(fx) += 1
        }
      }
    }

    def isSame(x: Int, y: Int) = {
      find(x) == find(y)
    }
  }

  def compare(x: Array[Char], y: Array[Char]): Int = {
    var i = 0
    val n = x.length
    var count = 0
    while (i < n) {
      if (x(i) != y(i)) {
        count += 1
      }
      i += 1
    }
    count
  }

  def dfs(now: Int, parent: Int) {
    if (now < k) {
      if (parent == k) {
        println((now+1) + " 0")
      } else {
        println((now+1) + " " + (parent+1))
      }
    }

    for (to <- graph(now)) {
      if (parent != to) {
        dfs(to, now)
      }
    }
  }

  val in = new Scanner(System.in)
  val n,m,k,w = in.nextInt()
  val levels = (0 until k).map(level => {
    (0 until n).map(_ => in.next()).mkString("").toCharArray
  })
  val edgesIJ = for {
    i <- 0 until k
    j <- i+1 until k
  } yield (i, j, compare(levels(i), levels(j)) * w)
  val edges = (0 until k).map(i => (k, i, n*m)) ++ edgesIJ

  val unionFind = new UnionFind(k+1)
  var answer = 0
  val graph = (0 to k).map(_ => new ArrayBuffer[Int]())
  edges.sortBy(e => e._3).foreach(e => {
    val i = e._1
    val j = e._2
    if (!unionFind.isSame(i, j)) {
      unionFind.unite(i, j)
      graph(i) += j
      graph(j) += i
      answer += e._3
    }
  })
  println(answer)
  dfs(k, -1)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
object C extends App {

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

  val Array(n, m, k, w) = readInts(4)
  val nm = n * m
  val ss = Array.ofDim[Char](k, nm)

  for (i <- 0 until k) {
    var p = 0
    for (j <- 0 until n) {
      val s = readLine
      var sp = 0
      while (sp < m) {
        ss(i)(p) = s(sp)
        sp += 1
        p += 1
      }
    }
  }

  val diffs = Array.fill(k, k)(0)

  for (i <- 0 until k; j <- 0 until i) {
    var d = 0
    var p = 0
    while (p < nm) {
      if (ss(i)(p) != ss(j)(p)) d += 1
      p += 1
    }
    diffs(i)(j) = d
    diffs(j)(i) = d
  }

  val passed = Array.fill(k)(false)

  val res = Array.ofDim[String](k)

  res(0) = "1 0"
  passed(0) = true

  val bestPrev = Array.fill(k)(0)
  var bytes = nm

  for (i <- 1 until k) {
    var choice = 0
    var minDiff = Int.MaxValue
    for (j <- 1 until k) {
      if (!passed(j) && diffs(j)(bestPrev(j)) < minDiff) {
        minDiff = diffs(j)(bestPrev(j))
        choice = j
      }
    }
    res(i) = s"${choice + 1} ${if (minDiff * w < nm) bestPrev(choice) + 1 else 0}"
    bytes += nm min (minDiff * w)
    passed(choice) = true
    for (j <- 1 until k) if (diffs(choice)(j) < diffs(bestPrev(j))(j)) bestPrev(j) = choice
  }

  println(bytes)
  res.foreach(println)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
object C extends App {

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

  val Array(n, m, k, w) = readInts(4)
  val nm = n * m
  val ss = Array.ofDim[Char](k, nm)

  for (i <- 0 until k) {
    var p = 0
    for (j <- 0 until n) {
      val s = readLine
      var sp = 0
      while (sp < m) {
        ss(i)(p) = s(sp)
        sp += 1
        p += 1
      }
    }
  }

  val diffs = Array.fill(k, k)(0)

  for (i <- 0 until k; j <- 0 until i) {
    var d = 0
    var p = 0
    while (p < nm) {
      if (ss(i)(p) != ss(j)(p)) d += 1
      p += 1
    }
    diffs(i)(j) = d
    diffs(j)(i) = d
  }

  val passed = Array.fill(k)(false)

  println("1 0")
  passed(0) = true

  val bestPrev = Array.fill(k)(0)

  for (i <- 1 until k) {
    var choice = 0
    var minDiff = Int.MaxValue
    for (j <- 1 until k) {
      if (!passed(j) && diffs(j)(bestPrev(j)) < minDiff) {
        minDiff = diffs(j)(bestPrev(j))
        choice = j
      }
    }
    println(s"${choice + 1} ${if (minDiff * w < nm) bestPrev(choice) + 1 else 0}")
    passed(choice) = true
    for (j <- 1 until k) if (diffs(choice)(j) < diffs(bestPrev(j))(j)) bestPrev(j) = choice
  }
}

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

/**
  * Created by hama_du on 2014/06/19.
  */
object ProblemC extends App {
  class UnionFind(n: Int) {
    val parent = (0 until n).toArray
    val rank = new Array[Int](n)

    def find(x: Int): Int = {
      if (parent(x) == x) {
        return x
      }
      parent(x) = find(parent(x))
      return parent(x)
    }

    def unite(x: Int, y: Int) {
      val fx = find(x)
      val fy = find(y)
      if (fx == fy) {
        return
      }
      if (rank(fx) < rank(fy)) {
        parent(fx) = fy
      } else {
        parent(fy) = fx
        if (rank(fx) == rank(fy)) {
          rank(fx) += 1
        }
      }
    }

    def isSame(x: Int, y: Int) = {
      find(x) == find(y)
    }
  }

  def compare(x: String, y: String): Int = {
    x.toCharArray.zip(y.toCharArray).count(p => p._1 != p._2)
  }

  def dfs(now: Int, parent: Int) {
    println((now+1) + " " + (parent+1))
    for (to <- graph(now)) {
      if (parent != to) {
        dfs(to, now)
      }
    }
  }

  val in = new Scanner(System.in)
  val n,m,k,w = in.nextInt()
  val levels = (0 until k).map(level => {
    (0 until n).map(_ => in.next()).mkString("")
  })
  val edges = for {
    i <- 0 until k
    j <- i+1 until k
  } yield (i, j, compare(levels(i), levels(j)) * w)

  val unionFind = new UnionFind(k)
  var answer = 0
  val graph = (0 until k).map(_ => new ArrayBuffer[Int]())
  edges.sortBy(e => e._3).foreach(e => {
    val i = e._1
    val j = e._2
    if (!unionFind.isSame(i, j)) {
      unionFind.unite(i, j)
      graph(i) += j
      graph(j) += i
      answer += e._3
    }
  })
  println(answer+n*m)
  dfs(0, -1)
}


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

    for (_ <- 1 to nextInt) {
      val n, m, rb, cb, rd, cd = nextInt

      val stepsH = if (rb <= rd) rd - rb else (n - rb) + (n - rd)
      val stepsV = if (cb <= cd) cd - cb else (m - cb) + (m - cd)
      val steps = stepsH min stepsV

      out.println(steps)
    }

    out.flush()
  }

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

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        var y = readInt()
        var x = readInt()
        val yy = readInt()
        val xx = readInt()
        var dx = 1
        var dy = 1
        var ans = 0
        while (xx != x && yy != y) {
            if (x == 1 && dx == -1)
                dx = 1
            if (x == m && dx == 1)
                dx = -1
            if (y == 1 && dy == -1)
                dy = 1
            if (y == n && dy == 1)
                dy = -1
            ans += 1
            x += dx
            y += dy
        }
        writer.println(ans)

        def check(kk: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(st))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(st, mid)
            else
                return bs(mid, en)
        }
    }
    writer.flush()
}


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

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

  val N, M = sc.nextInt
  val ct = Array.fill(N, 2)(sc.nextInt)
  val vs = Array.fill(M)(sc.nextInt)

  val ts = Array.fill(N + 2)(0)
  for (i <- 1 to N) {
    val c = ct(i - 1)(0)
    val t = ct(i - 1)(1)
    ts(i) = ts(i - 1) + c * t
  }
  ts(N + 1) = Int.MaxValue

  def findSong(m: Int): Int = {
    @tailrec
    def loop(l: Int, u: Int): Int = {
      val x = (l + u) / 2
      if (ts(x - 1) < m && m <= ts(x)) x
      else if (ts(x) < m && m <= ts(x + 1)) x + 1
      else if (m <= ts(x - 1)) loop(l, x)
      else loop(x, u)
    }
    loop(1, N)
  }

  for (i <- 0 until M)
    out.println(findSong(vs(i)))

  out.close
}

object Playlist extends App {
			// input
			var in = readLine
			var split = in.split(" ")
			var n = split(0).toInt
			var m = split(1).toInt

			var next: Array[Int] = new Array[Int](n)
			var pointer = 0;
			for(i <- 0 until n) {
			  in = readLine
			  split = in.split(" ")
			  pointer += split(0).toInt * split(1).toInt
			  next(i) = pointer
			}

			in = readLine
			pointer = 0
			for (s <- in.split(" ")) {
			  while (s.toInt > next(pointer))
				  pointer+=1
			  println(pointer+1)
			}
}


object B {

  def calc(x: Int) = {
    if (x == 1) {
      -1
    } else {
      val odd = ((x + 1) / 2).toLong
      val even = (x / 2).toLong
      -(1 + {
        if (x % 2 == 0) x - 1 else x
      }) * odd / 2 + (2 + {
        if (x % 2 == 0) x else x - 1
      }) * even / 2
    }
  }

  def main(args: Array[String]) = {
    val scanner = new java.util.Scanner(System.in)
    val q = scanner.nextInt()
    (0 until q).foreach{_ =>
      val (l, r) = (scanner.nextInt(), scanner.nextInt())
      var result = 0
      if (l == r) {
        System.out.println(if (l % 2 == 0) l else -l)
      } else {
        System.out.println(calc(r) - calc(l-1))
      }
    }
  }
}

object CF_524_2_B {
  def solve(input: Vector[Range]): String = {
    def isOdd(n: Int) = n%2 != 0
    def convert(r: Range): Int = (r.start, r.end) match {
      case (a, b) if isOdd(a) =>
        if(isOdd(b))
          // end odd => (b + 1) is even => +ve => take it away
          convert(a to (b + 1)) - (b + 1)
        else (b - a + 1)/2
      // start even
      case (a, b) =>
        if(isOdd(b))
          (b - a + 1)/(-2)
        // end even => (b + 1) is odd => -ve => add it back
        else convert(a to (b + 1)) + (b + 1)
    }
    input.map(convert).mkString("\n")
  }

  def main(args: Array[String]): Unit = {
    val io = new IO(System.in)
    val lines = io.int()
    io.sc.nextLine()
    def s2r(xs: Seq[Int]) = xs(0) to xs (1)
    val input = Vector.fill(lines)(io.intSeq()).map(s2r)
    val solution = solve(input)
    println(solution)
  }

//// boilerplate utility methods:
    import java.util.Scanner
    class IO(val sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def double() = sc.nextDouble()
    }
}

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  def t(p: Long, k: Long): Long = {
    p / k + (if (p % k == 0) 0 else 1)
  }

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    (1 to n).foreach { _ =>
      var l, r = in.nextLong
      if (l == r)
        println(if (l % 2 == 0) l else -l)
      else if (r - l == 1)
        println(if (l % 2 == 0) -1 else 1)
      else {
        var ans: Long = 0
        if (l % 2 == 0) {
          ans += l
          l += 1
        }
        if (r % 2 != 0) {
          ans -= r
          r -= 1
        }
        println(ans + (r - l) / 2 + 1)
      }
    }
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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 = {

    def cum(x: Int) = {
      if (x == 0) 0L
      else {
        if (x % 2 == 1) {
          val x0 = (x + 1) / 2
          val x1 = x / 2
          val odds = x0.toLong * (x0 + 1) - x0
          val evens = x1.toLong * (x1 + 1)
          evens - odds
        } else {
          val x0 = x / 2
          val x1 = x / 2
          val odds = x0.toLong * (x0 + 1) - x0
          val evens = x1.toLong * (x1 + 1)
          evens - odds
        }
      }
    }

    rep(ni()) { _ =>
      val l, r = ni()
      out.println(cum(r) - cum(l - 1))
    }

  }

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

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

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

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

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

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

object B {

  def calc(x: Int) = {
    if (x == 1) {
      -1
    } else {
      val odd = (x + 1) / 2
      val even = x / 2
      -(1 + {
        if (x % 2 == 0) x - 1 else x
      }) * odd / 2 + (2 + {
        if (x % 2 == 0) x else x - 1
      }) * even / 2
    }
  }

  def main(args: Array[String]) = {
    val scanner = new java.util.Scanner(System.in)
    val q = scanner.nextInt()
    (0 until q).foreach{_ =>
      val (l, r) = (scanner.nextInt(), scanner.nextInt())
      var result = 0
      if (l == r) {
        System.out.println(if (l % 2 == 0) l else -l)
      } else {
        System.out.println(calc(r) - calc(l-1))
      }
    }
  }
}


object A {

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines().toList.tail

    val rows = lines.map (_.split(" ").map(_.toInt).toList)
    val cols = List.transpose(rows)

    var count = 0

    for (i <- 0 to rows.length - 1)
      for (j <- 0 to rows.length - 1)
        if (cols(j).sum > rows(i).sum) count += 1

    println (count)

  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (0 until n).map(_ => in.next().split(" ").map(_.toInt))
  val rows = data.map(_.sum)
  val cols = (0 until n).map(i => (0 until n).map(j => data(j)(i)).sum)
  println(rows.map(rv => cols.count(_ > rv)).sum)
}

import io.Source
import java.util.Scanner

object A {
  def sumRow(a: Array[Array[Int]], row: Int) = a(row).sum

  def sumColumn(a: Array[Array[Int]], column: Int) = a.foldLeft(0)((sum, arr) => sum + arr(column))

  def main(args: Array[String]) {
    val stdin = new Scanner(System.in)
    val n = stdin.nextInt()
    val matrix = Array.ofDim[Int](n, n)
    for (val i <- 0 until n) {
      for (val j <- 0 until n) {
        matrix(i)(j) = stdin.nextInt()
      }
    }
    var count = 0
    for (val i <- 0 until n) {
      for (val j <- 0 until n) {
        if (sumRow(matrix, i) < sumColumn(matrix, j)) {
          count += 1
        }
      }
    }
    println(count)
  }
}

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

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

  val N = sc.nextInt
  val a = Array.fill(N, N)(sc.nextInt)
  val b = a.transpose

  def isWinning(x: Int, y: Int): Boolean = a(x).sum < b(y).sum

  var score = 0
  for (i <- 0 until N; j <- 0 until N)
    if (isWinning(i, j)) score += 1

  out.println(score)
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

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

  val n = readInt
  val a = for(_ <- 1 to n) yield readInts
  val horS = a.map(_.sum)
  val verS = a.transpose.map(_.sum)
  val ans = verS.map(x => horS.count(x>)).sum

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

object Main {
  def main(args: Array[String]) = {
    val n = readInt
    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))

    val rowSums = a.map(_.sum)
    val colSums = a.transpose.map(_.sum)

    val count = rowSums.map(rowSum => colSums.count(_ > rowSum)).sum
    println(count)
  }
}

import scala.collection.mutable.ArrayBuffer

object Flask {

  def main(args: Array[String]): Unit = {
    var data: ArrayBuffer[Array[Int]] = new ArrayBuffer()
    var n = readLine.toInt
    for (i <- 1 to n) data += readLine.split(" ").map(_.toInt)

    var count = 0

    for (i <- 0 until n) {
      for (j <- 0 until n) {
        var horizontal_sum = List.range(0, n).foldLeft(0)((res, pos) => res + data(i)(pos))
        var vertical_sum = List.range(0, n).foldLeft(0)((res, pos) => res + data(pos)(j))

        if (vertical_sum > horizontal_sum)
            count += 1
      }
    }
    println(count)
  }
}

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 01.03.12
 * Time: 0:59
 * To change this template use File | Settings | File Templates.
 */

object A {
  def main(args: Array[String]) {
    val n = readInt
    val m = (for (_ <- 1 to n) yield (readLine split ' ' map (_.toInt)).toArray).toArray
    val rawsum = (0 until n) map (i => (0 until n) map (m(i)(_)) sum) toArray;
    val colsum = (0 until n) map (j => (0 until n) map (m(_)(j)) sum) toArray;
    println((for (i <- 0 until n; j <- 0 until n if colsum(i) > rawsum(j)) yield 1).sum)

  }

}


object ProblemD 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 (i <- 1 to t) {
    val n = in.nextInt()
    val inArr = new Array[Int](n)
    for (j <- 0 until n) {
      inArr(j) = in.nextInt()
    }

    var aliceSum = inArr(0)
    var bobSum = 0
    var bobPrev = 0
    var prevAlliceSum = aliceSum
    var aliceTurn = false

    var left = 1
    var right = n - 1
    var count = 1

    while (left <= right) {
      count = count + 1
      if (aliceTurn) {
        var currentSum = 0
        while (currentSum <= bobPrev && left <= right) {
          currentSum = currentSum + inArr(left)
          left = left + 1
        }
        prevAlliceSum = currentSum
        aliceSum = aliceSum + currentSum
      } else {
        var currentSum = 0
        while (currentSum <= prevAlliceSum && left <= right) {
          currentSum = currentSum + inArr(right)
          right = right - 1
        }

        bobSum = bobSum + currentSum
        bobPrev = currentSum
      }
      aliceTurn = !aliceTurn
    }

    println(s"$count $aliceSum $bobSum")
  }

}

import scala.io.StdIn

object Test extends App {

  val s = StdIn.readLine().toInt
  (1 to s).foreach{_ =>
    StdIn.readLine()
    var arr = StdIn.readLine().split(" ").map(_.toInt)
    var i = 0
    var j = arr.length - 1
    var alice = 0
    var bob = 0
    alice = arr(i)
    i = 1
    var bob1 = true
    var counter = 1
    var beforeA = alice
    var beforeB = 0
    while (i <= j){
      counter = counter + 1
      if(bob1){
        var bob2 = 0
        while (bob2 <= beforeA && i <= j){
          bob2 = bob2 + arr(j)
          j = j - 1
        }
        beforeB = bob2
        bob = bob + bob2
        bob1 = false
      }else{
        var al2 = 0
        while (al2 <= beforeB && i <= j){
          al2 = al2 + arr(i)
          i = i +1
        }
        beforeA = al2
        alice = alice + al2
        bob1 = true
      }
    }
    println(s"$counter $alice $bob")

  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C640B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val a = na(n)

      var l = 0
      var h = n-1
      var switch = 0
      var prev = 0
      val ret = Array.fill[Int](2)(0)
      var cnt = 0
      while(l <= h) {
        var curr = 0
        while (curr <= prev && l <= h) {
          if(switch == 0) {curr += a(l); l += 1}
          else { curr += a(h); h -=1 }
        }
        ret(switch) += curr
        switch ^= 1
        prev = curr
        cnt += 1
      }
      out.println(s"$cnt ${ret(0)} ${ret(1)}")
    }
  }
}

object _1352D extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val candies = io.read[Vector[Int]]

    @tailrec
    def solve(isAlice: Boolean, prev: Int, left: Int, right: Int, alice: Int, bob: Int, moves: Int): Seq[Int] = {
      val range = if (isAlice) left + 1 until right else right-1 until left by -1
      if (range.nonEmpty) {
        var sum, count = 0
        range.takeWhile({i =>
          count += 1
          sum += candies(i)
          sum <= prev
        })
        solve(
          isAlice = !isAlice,
          prev = sum,
          left = if (isAlice) left + count else left,
          right = if (!isAlice) right - count else right,
          alice = if (isAlice) alice + sum else alice,
          bob = if (!isAlice) bob + sum else bob,
          moves = moves + 1
        )
      } else {
        Seq(moves, alice, bob)
      }
    }

    val ans = solve(isAlice = true, prev = 0, left = -1, right = candies.length, alice = 0, bob = 0, moves = 0)

    io.writeAll(ans)
  }

}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  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)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    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 {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[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 = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    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 collection.mutable

object C {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(x => x.toInt)
    var a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = readLine().split("\\.").map(x => x.toInt).fold(0)((x, y) => x * 256 + y)
    }
    val masks = 1 until 32 map {x => -1 << (32 - x)}
    var ans = 0
    for (r <- masks) {
      var d = new mutable.HashSet[Int]
      for (x <- a) {
        val v = x & r
        d add v
      }
      if (d.size == k && ans == 0) {
        ans = r
      }
    }
    if (ans == 0) {
      println(-1)
    } else {
      val res = (0 until 4).map(x => (ans >> (24 - 8 * x)) & 255).fold("")((x, y) => if (x == "") y else x + "." + y)
      println(res)
    }
  }
}

import io.Source
import java.io.PrintWriter

object CF291C {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    val a = {for (i <- 0 until n) yield {
      ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong
    }}.toArray
    var l = 0
    var r = 32
    var rVal = -1
    while (l + 1 < r) {
      val mid = (l + r) / 2
      val mask = ((1L << mid) - 1) << (32 - mid)
      val set = collection.mutable.HashSet[Long]()
      for (x <- a) {
        set += x & mask
      }
      if (set.size < k) {
        l = mid
      } else {
        r = mid
        rVal = set.size
      }
    }
    if (r == 32 || rVal != k) {
      out.println(-1)
    } else {
      val ans = ((1L << r) - 1) << (32 - r)
      out.print((ans >> 24) & 255)
      out.print(".")
      out.print((ans >> 16) & 255)
      out.print(".")
      out.print((ans >> 8) & 255)
      out.print(".")
      out.print((ans >> 0) & 255)
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " .\r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object C {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);
  def main(args: Array[String]) {
    var Array(n, k) = READ
    def toIp(i: Int):Long = math.pow(2, i).toLong-1 << 32-i;
    var masks = (1 to 31) map (i => (i-1, toIp(i)));
    var arr = Array.fill(31)(scala.collection.mutable.HashSet.empty[Long])
    for (i <- 0 until n) {
      val ip:Long = readLine() split("\\.") map (_.toLong) reduce(_<<8 | _);
      masks foreach {x => arr(x._1).add(x._2&ip)}
    }
    for (i <- 1 to 31; if arr(i-1).size == k){
      val ip = toIp(i)
      printf("%d.%d.%d.%d\n", ip >> 24, (ip & 0xff0000) >> 16, (ip & 0xff00) >> 8, ip&0xff)
      return;
    }
    println(-1);
  }
}

/*
C. Маска подсети
ограничение по времени на тест
4 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

В задаче используется упрощенная модель адресов в TCP/IP, внимательно прочтите условие.

Поликарп устроился на работу системным администратором. Как-то раз к нему в руки попали n IP-адресов. Каждый IP-адрес — это 32-битное число, представленное в виде четверки десятичных 8-битных чисел (без лидирующих нулей), записанных через точку. Например, запись 0.255.1.123 обозначает корректный IP-адрес, а записи 0.256.1.123 и 0.255.1.01 — нет. В данной задаче произвольная четверка 8-битных чисел является корректным IP-адресом.

Поработав администратором, Поликарп узнал, что, зная IP-адрес, можно, используя маску подсети, получить адрес сети, которой принадлежит этот IP-адрес.

Маска подсети — это IP-адрес, обладающий следующим свойством: если записать этот IP-адрес, как 32-битную строку, то он представим в виде «11...11000..000». Другими словами, в маске подсети сначала идет один или более единичный бит, а затем один или более нулевой бит (всего битов 32). Например, IP-адрес 2.0.0.0 не является корректной маской подсети, так как его 32-битная запись имеет вид 00000010000000000000000000000000.

Для получения адреса сети IP-адреса нужно выполнить операцию побитового «и» («and») IP-адреса и маски подсети. Например, если маска подсети 255.192.0.0, а IP-адрес 192.168.1.2, то адрес сети равен 192.128.0.0. При побитовом «и» в записи результата бит равен 1 тогда и только тогда, когда у обоих операндов соответствующие биты единичные.

Теперь Поликарп хочет найти все сети, которым принадлежат его IP-адреса. К сожалению, Поликарп потерял маску подсети. К счастью, Поликарп запомнил, что его IP-адреса принадлежали ровно k различным сетям. Помогите Поликарпу найти маску подсети, такую, что его IP-адреса будут принадлежать ровно k различным сетям. Если таких масок несколько, найдите ту, в битовой записи которой наименьшее количество единиц. Если таких масок не существует, сообщите об этом.
Входные данные

В первой строке записаны два целых числа n и k (1 ≤ k ≤ n ≤ 105) — количество IP-адресов и сетей. В следующих n строках записаны сами IP-адреса. Гарантируется, что все IP-адреса различны.
Выходные данные

В единственной строке выведите IP-адрес маски подсети, в формате описанном в условии, если требуемая маска подсети существует. Иначе выведите -1.
Примеры тестов
Входные данные

5 3
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3

Выходные данные

255.255.254.0

Входные данные

5 2
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3

Выходные данные

255.255.0.0

Входные данные

2 1
255.0.0.1
0.0.0.2

Выходные данные

-1
*/
import scala.collection.immutable.BitSet
import scala.collection.mutable.MutableList
import scala.collection.mutable.HashSet

object Task3 extends App {

  def masks: IndexedSeq[Long] = {
    val init = 0xFFFFFFFFL
    var z = init
    val res = init +: (for (p <- 0 until 31) yield {
      z -= math.pow(2, p).toLong
      z
    })
    res.reverse
  }

  def toBits(ip: String): Long = {
    def parts = ip.trim split '.'
    require(parts.size == 4)
    val res = parts.foldLeft(0L)((acc, part) => acc * 256 + (part.toInt))
    res
  }

  def toStr(ip: Option[Long]): String = ip match {
    case None => "-1"
    case Some(l) => {
      val seg1 = (l & 0xFF000000L) >> 24
      val seg2 = (l & 0x00FF0000L) >> 16
      val seg3 = (l & 0x0000FF00L) >> 8
      val seg4 = (l & 0x000000FFL)
      seg1 + "." + seg2 + "." + seg3 + "." + seg4
    }
  }

  def applyMask(mask: Long, ips: Seq[Long]): Seq[Long] = {
    val set = new HashSet[Long]
    ips map (ip => set += (ip & mask))
    set.toSeq
  }

  def distinctByNFirstBits(n: Int, ips: Seq[Long]): Int = {
    val t = ips map (_ >> (32 - n))
    t.distinct.size
  }

  def nFirstBits(n: Int): Long = masks(n - 1)

  def solveStr(k: Int, ipStrs: Seq[String]): String =
    toStr(solve(k, ipStrs map toBits))

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(k: Int, ips: Seq[Long]): Option[Long] =
    if (k > ips.size) None
    //    else masks.find(mask => applyMask(mask, ips).size == k)
    else (1 to 31) find (n => distinctByNFirstBits(n, ips) == k) map nFirstBits

  /*
  def bitStream(ones: Int): Stream[Long] = generateBits(0, 32, ones)

  def generateBits(curr: Long, remaining: Int, remainingOnes: Int): Stream[Long] = {
    val shifted = (curr << 1)
    if (remaining == 0) {
      assert(remainingOnes == 0)
      curr #:: Stream.empty
    } else if (remainingOnes == remaining) {
      generateBits(shifted + 1, remaining - 1, remainingOnes - 1)
    } else if (remainingOnes >= 1) {
      val v1 = generateBits(shifted + 1, remaining - 1, remainingOnes - 1)
      val v2 = generateBits(shifted + 0, remaining - 1, remainingOnes)
      Stream.concat(v1, v2)
    } else {
      generateBits(shifted, remaining - 1, remainingOnes)
    }
  }
*/
  val (n, k) = {
    val l = readLine split (' ') map (_.toInt)
    (l(0), l(1))
  }
  val ipStrs = for (i <- 0 until n) yield readLine

  val res = solveStr(k, ipStrs)
  println(res)
}

/*
C. Маска подсети
ограничение по времени на тест
4 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

В задаче используется упрощенная модель адресов в TCP/IP, внимательно прочтите условие.

Поликарп устроился на работу системным администратором. Как-то раз к нему в руки попали n IP-адресов. Каждый IP-адрес — это 32-битное число, представленное в виде четверки десятичных 8-битных чисел (без лидирующих нулей), записанных через точку. Например, запись 0.255.1.123 обозначает корректный IP-адрес, а записи 0.256.1.123 и 0.255.1.01 — нет. В данной задаче произвольная четверка 8-битных чисел является корректным IP-адресом.

Поработав администратором, Поликарп узнал, что, зная IP-адрес, можно, используя маску подсети, получить адрес сети, которой принадлежит этот IP-адрес.

Маска подсети — это IP-адрес, обладающий следующим свойством: если записать этот IP-адрес, как 32-битную строку, то он представим в виде «11...11000..000». Другими словами, в маске подсети сначала идет один или более единичный бит, а затем один или более нулевой бит (всего битов 32). Например, IP-адрес 2.0.0.0 не является корректной маской подсети, так как его 32-битная запись имеет вид 00000010000000000000000000000000.

Для получения адреса сети IP-адреса нужно выполнить операцию побитового «и» («and») IP-адреса и маски подсети. Например, если маска подсети 255.192.0.0, а IP-адрес 192.168.1.2, то адрес сети равен 192.128.0.0. При побитовом «и» в записи результата бит равен 1 тогда и только тогда, когда у обоих операндов соответствующие биты единичные.

Теперь Поликарп хочет найти все сети, которым принадлежат его IP-адреса. К сожалению, Поликарп потерял маску подсети. К счастью, Поликарп запомнил, что его IP-адреса принадлежали ровно k различным сетям. Помогите Поликарпу найти маску подсети, такую, что его IP-адреса будут принадлежать ровно k различным сетям. Если таких масок несколько, найдите ту, в битовой записи которой наименьшее количество единиц. Если таких масок не существует, сообщите об этом.
Входные данные

В первой строке записаны два целых числа n и k (1 ≤ k ≤ n ≤ 105) — количество IP-адресов и сетей. В следующих n строках записаны сами IP-адреса. Гарантируется, что все IP-адреса различны.
Выходные данные

В единственной строке выведите IP-адрес маски подсети, в формате описанном в условии, если требуемая маска подсети существует. Иначе выведите -1.
Примеры тестов
Входные данные

5 3
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3

Выходные данные

255.255.254.0

Входные данные

5 2
0.0.0.1
0.1.1.2
0.0.2.1
0.1.1.0
0.0.2.3

Выходные данные

255.255.0.0

Входные данные

2 1
255.0.0.1
0.0.0.2

Выходные данные

-1
*/
import scala.collection.immutable.HashSet
import scala.collection.immutable.BitSet
import scala.collection.mutable.MutableList

object Task3 extends App {

  def masks: Seq[Long] = {
    val init = 0xFFFFFFFFL
    var z = init
    val res = init +: (for (p <- 0 until 31) yield {
      z -= math.pow(2, p).toLong
      z
    })
    res.reverse
  }

  def applyMask(mask: Long, ips: Seq[Long]): Set[Long] = {
    ips.foldLeft(new HashSet[Long]) { (set, ip) =>
      set + (ip & mask)
    }
  }

  def toBits(ip: String): Long = {
    def parts = ip.trim split '.'
    require(parts.size == 4)
    val res = parts.foldLeft(0L)((acc, part) => acc * 256 + (part.toInt))
    res
  }

  def toStr(ip: Option[Long]): String = ip match {
    case None => "-1"
    case Some(l) => {
      val seg1 = (l & 0xFF000000L) >> 24
      val seg2 = (l & 0x00FF0000L) >> 16
      val seg3 = (l & 0x0000FF00L) >> 8
      val seg4 = (l & 0x000000FFL)
      seg1 + "." + seg2 + "." + seg3 + "." + seg4
    }
  }

  def solveStr(k: Int, ipStrs: Seq[String]): String =
    toStr(solve(k, ipStrs map toBits))

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(k: Int, ips: Seq[Long]): Option[Long] =
    if (k > ips.size) None
    else if (k == ips.size) Some(0xFFFFFFFFL)
    else masks.find(mask => applyMask(mask, ips).size == k)

  /*
  def bitStream(ones: Int): Stream[Long] = generateBits(0, 32, ones)

  def generateBits(curr: Long, remaining: Int, remainingOnes: Int): Stream[Long] = {
    val shifted = (curr << 1)
    if (remaining == 0) {
      assert(remainingOnes == 0)
      curr #:: Stream.empty
    } else if (remainingOnes == remaining) {
      generateBits(shifted + 1, remaining - 1, remainingOnes - 1)
    } else if (remainingOnes >= 1) {
      val v1 = generateBits(shifted + 1, remaining - 1, remainingOnes - 1)
      val v2 = generateBits(shifted + 0, remaining - 1, remainingOnes)
      Stream.concat(v1, v2)
    } else {
      generateBits(shifted, remaining - 1, remainingOnes)
    }
  }
*/
  val (n, k) = {
    val l = readLine split (' ') map (_.toInt)
    (l(0), l(1))
  }
  val ipStrs = for (i <- 0 until n) yield readLine

  val res = solveStr(k, ipStrs)
  println(res)
}

import io.Source
import java.io.PrintWriter

object CF291C {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    val a = {for (i <- 0 until n) yield {
      ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong
    }}.toArray
    var l = 0
    var r = 33
    while (l + 1 < r) {
      val mid = (l + r) / 2
      val mask = ((1L << mid) - 1) << (32 - mid)
      val set = collection.mutable.HashSet[Long]()
      for (x <- a) {
        set += x & mask
      }
      if (set.size < k) {
        l = mid
      } else {
        r = mid
      }
    }
    if (l == 0 || r == 33) {
      out.println(-1)
    } else {
      val ans = ((1L << r) - 1) << (32 - r)
      out.print((ans >> 24) & 255)
      out.print(".")
      out.print((ans >> 16) & 255)
      out.print(".")
      out.print((ans >> 8) & 255)
      out.print(".")
      out.print((ans >> 0) & 255)
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " .\r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

import io.Source
import java.io.PrintWriter

object CF291C {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    val a = {for (i <- 0 until n) yield {
      ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong
    }}.toArray
    var l = 0
    var r = 33
    var rVal = -1
    while (l + 1 < r) {
      val mid = (l + r) / 2
      val mask = ((1L << mid) - 1) << (32 - mid)
      val set = collection.mutable.HashSet[Long]()
      for (x <- a) {
        set += x & mask
      }
      if (set.size < k) {
        l = mid
      } else {
        r = mid
        rVal = set.size
      }
    }
    if (l == 0 || r == 33 || rVal != k) {
      out.println(-1)
    } else {
      val ans = ((1L << r) - 1) << (32 - r)
      out.print((ans >> 24) & 255)
      out.print(".")
      out.print((ans >> 16) & 255)
      out.print(".")
      out.print((ans >> 8) & 255)
      out.print(".")
      out.print((ans >> 0) & 255)
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " .\r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

import io.Source
import java.io.PrintWriter

object CF291C {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    val a = {for (i <- 0 until n) yield {
      ((in().toLong * 256 + in().toLong) * 256 + in().toLong) * 256 + in().toLong
    }}.toArray
    var l = 0
    var r = 32
    var rVal = -1
    while (l + 1 < r) {
      val mid = (l + r) / 2
      val mask = ((1L << mid) - 1) << (32 - mid)
      val set = collection.mutable.HashSet[Long]()
      for (x <- a) {
        set += x & mask
      }
      if (set.size < k) {
        l = mid
      } else {
        r = mid
        rVal = set.size
      }
    }
    if (l == 0 || r == 32 || rVal != k) {
      out.println(-1)
    } else {
      val ans = ((1L << r) - 1) << (32 - r)
      out.print((ans >> 24) & 255)
      out.print(".")
      out.print((ans >> 16) & 255)
      out.print(".")
      out.print((ans >> 8) & 255)
      out.print(".")
      out.print((ans >> 0) & 255)
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " .\r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}


import java.util.Scanner

object CubeWalls extends App {

	final val SEP = 1000000000	// arrays separator

	val scanner = new Scanner( System.in )

	val n = scanner.nextInt
	val w = scanner.nextInt
	val a = Array.ofDim[Int]( n )
	for( i <- a.indices )
		a( i ) = scanner.nextInt
	val b = Array.ofDim[Int]( w )
	for( i <- b.indices )
		b( i ) = scanner.nextInt

	val matches = if( w > 1 ) {
		// array with differences to have simple matching
		val ad = a.sliding( 2 ).map( e => e( 1 ) - e( 0 )).toArray
		val bd = b.sliding( 2 ).map( e => e( 1 ) - e( 0 )).toArray
		// join the arrays to use Z function
		val bdad = (bd :+ SEP) ++ ad
		val z = zf( bdad )
		z.count( _ == w - 1 )		// count matches, shorter by 1 because we match array with differences
	}
	else
		n

/*	simple but with O(n*w) - too slow
	val bi = b.zipWithIndex
	val bi = b.zipWithIndex
	val matches = ( 0 to lDiff ) count { i =>
		val hDiff = a( i ) - b( 0 )
		bi.forall( x => a( i + x._2 ) - x._1 == hDiff )
	}
*/
	println( matches )

	// Z algorithm, see http://codeforces.com/blog/entry/3107
	def zf( s: Array[Int] ) = {
		val n = s.length
		val z = Array.ofDim[Int]( n )
		z( 0 ) = 0
		var l = 0
		var r = 0
		for( i <- 1 until n ) {
			if( i > r ) {
				l = i
				r = i
				while( r < n && s( r - l ) == s( r ))
					r += 1
				z( i ) = r - l
				r -= 1
			}
			else {
				val k = i - l
				if( z( k ) < r - i + 1 )
					z( i ) = z( k )
				else {
					l = i
					while( r < n && s( r - l ) == s( r ))
						r += 1
					z( i ) = r - l
					r -= 1
				}
			}
		}
		z
	}
}

import java.util._
import java.io._
import java.util
import scala.annotation.tailrec

object D {

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

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

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

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

  def prefixFunc(string: Array[Int]): Array[Int] = {
    val π = new Array[Int](string.length)
    π(0) = 0
    for (i <- 1 to string.length - 1) {
      var j = π(i - 1)
      while (j != 0 && string(j) != string(i)) {
        j = π(j - 1)
      }
      if (string(j) == string(i)) {
        π(i) = j + 1
      } else {
        π(i) = 0
      }
    }
    π
  }

  def kmp(t: Array[Int], s: Array[Int]): Unit = {
    val del = new Array[Int](1)
    del(0) = Int.MaxValue
    val p = prefixFunc(s ++ del ++ t)
    for (i <- s.length + 1 to p.length - 1) {
      if (p(i) == s.length) {
        ans += 1
      }
    }
  }

  def solve: Int = {
    val n = nextInt
    val w = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](w)
    if (w == 1) {
      out.println(n)
      return 1
    }
    val ua = new Array[Int](n - 1)
    val ub = new Array[Int](w - 1)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    for (j <- 0 until w) {
      b(j) = nextInt
    }
    for (i <- 0 until n - 1) {
      ua(i) = a(i + 1) - a(i)
    }
    for (i <- 0 until w - 1) {
      ub(i) = b(i + 1) - b(i)
    }

    kmp(ua, ub)
    out.println(ans)
    return 1
  }

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

import java.util._
import java.io._
import java.util
import scala.annotation.tailrec

object D {

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

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

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

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

  def prefixFunc(string: String): Array[Int] = {
    val π = new Array[Int](string.length)
    π(0) = 0
    for (i <- 1 to string.length - 1) {
      var j = π(i - 1)
      while (j != 0 && string(j) != string(i)) {
        j = π(j - 1)
      }
      if (string(j) == string(i)) {
        π(i) = j + 1
      } else {
        π(i) = 0
      }
    }
    π
  }

  def kmp(t: String, s: String): Unit = {
    val p = prefixFunc(s + "#" + t)
    for (i <- s.length + 1 to p.length - 1) {
      if (p(i) == s.length) {
        ans += 1
      }
    }
  }

  def solve: Int = {
    val n = nextInt
    val w = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](w)
    val ua = new Array[Int](n)
    val ub = new Array[Int](w)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    for (j <- 0 until w) {
      b(j) = nextInt
    }
    ua(0) = 0
    for (i <- 1 until n) {
      ua(i) = a(i) - a(i - 1)
    }
    for (i <- 1 until w) {
      ub(i) = b(i) - b(i - 1)
    }
    ub(0) = 0
    if (w == 1) {
      out.println(n)
      return 1
    }
    val t = ua.mkString("")
    val s = ub.mkString("").substring(1)
    kmp(t, s)
    out.println(ans)
    return 1
  }

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


object CodeforcesRound1392B {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  //2 1
  //-199 192
  //192+199 0
  //0 -192-199

  //1 3 7
  //7-1  7-3  7-7
  //6    4    0
  //0    2    6
  //6    4    0

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(nl, k) = rll_long
    val n = nl.toInt
    val a = rll_int
    val upToIter = (2 - (k % 2)).toInt
    for (_ <- 0 until upToIter) {
      val max = a.max
      for (i <- 0 until n) {
        a(i) = max - a(i)
      }
    }
    val res = a.mkString(" ")
    writer.println(res)
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

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

    for (_ <- 1 to nextInt) {
      val n, k = nextLong
      val as = nextLongs(n.toInt)
      val min = as.min
      val max = as.max

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

      val d = max - min
      if (k % 2 == 0) {
        for (i <- as.indices) {
          as(i) = d - as(i)
        }
      }

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

    out.flush()
  }

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