International Women's Day is coming soon! Polycarp is preparing for the holiday.There are $$$n$$$ candy boxes in the shop for sale. The $$$i$$$-th box contains $$$d_i$$$ candies.Polycarp wants to prepare the maximum number of gifts for $$$k$$$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $$$k$$$. In other words, two boxes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) can be combined as a gift if $$$d_i + d_j$$$ is divisible by $$$k$$$.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 100$$$) — the number the boxes and the number the girls. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$), where $$$d_i$$$ is the number of candies in the $$$i$$$-th box.

Print one integer — the maximum number of the boxes Polycarp can give as gifts.

NoteIn the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(2, 3)$$$;  $$$(5, 6)$$$;  $$$(1, 4)$$$. So the answer is $$$6$$$.In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(6, 8)$$$;  $$$(2, 3)$$$;  $$$(1, 4)$$$;  $$$(5, 7)$$$. So the answer is $$$8$$$.In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(1, 2)$$$;  $$$(6, 7)$$$. So the answer is $$$4$$$.

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


An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:   initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i. e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≤ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.

The first line contains two integers n and U (3 ≤ n ≤ 105, 1 ≤ U ≤ 109) — the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≤ E1 < E2... < En ≤ 109). It is guaranteed that all Ei are given in increasing order.

If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .

object C extends App {

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

  val Array(n, u) = readInts(2)
  val es = readInts(n)

  var i = 0
  var k = 2
  var best = -1d
  while (i < n) {
    while (k + 1 < n && es(k + 1) - es(i) <= u) k += 1
    val j = i + 1
    if (k > j && es(k) - es(i) <= u) {
      val x = (es(k) - es(j)).toDouble / (es(k) - es(i))
      if (x > best) best = x
    }
    i += 1
  }

  if (best < 0) println(-1)
  else println(best)
}


One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.Help site X cope with the challenging task of rating distribution. Find the optimal distribution.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of users on the site. The next line contains integer sequence a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a sequence of integers b1, b2, ..., bn. Number bi means that user i gets bi of rating as a present. The printed sequence must meet the problem conditions.  If there are multiple optimal solutions, print any of them.

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

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

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
}

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

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

}


You are given an array $$$a$$$ of length $$$n$$$, which initially is a permutation of numbers from $$$1$$$ to $$$n$$$. In one operation, you can choose an index $$$i$$$ ($$$1 \leq i < n$$$) such that $$$a_i < a_{i + 1}$$$, and remove either $$$a_i$$$ or $$$a_{i + 1}$$$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $$$[1, 3, 2]$$$, you can choose $$$i = 1$$$ (since $$$a_1 = 1 < a_2 = 3$$$), then either remove $$$a_1$$$ which gives the new array $$$[3, 2]$$$, or remove $$$a_2$$$ which gives the new array $$$[1, 2]$$$.Is it possible to make the length of this array equal to $$$1$$$ with these operations?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$, $$$a_i$$$ are pairwise distinct) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so.

NoteFor the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation):$$$[\text{1}, \textbf{2}, \textbf{3}] \rightarrow [\textbf{1}, \textbf{2}] \rightarrow [\text{1}]$$$$$$[\text{3}, \textbf{1}, \textbf{2}, \text{4}] \rightarrow [\text{3}, \textbf{1}, \textbf{4}] \rightarrow [\textbf{3}, \textbf{4}] \rightarrow [\text{4}]$$$$$$[\textbf{2}, \textbf{4}, \text{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\textbf{4}, \textbf{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\text{4}, \text{1}, \textbf{3}, \textbf{5}] \rightarrow [\text{4}, \textbf{1}, \textbf{5}] \rightarrow [\textbf{4}, \textbf{5}] \rightarrow [\text{4}]$$$

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

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


You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way:  if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$;  if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$;  if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$;  if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.

The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.

The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".

NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.

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 x1, y1, x2, y2 = nl()
    val N = ni()
    val S = ns(N)

    val dx = x2 - x1
    val dy = y2 - y1

//    debug(s"dx $dx")
//    debug(s"dy $dy")

    val X, Y = Array.ofDim[Int](N)
    REP(N) { i =>
      S(i) match {
        case 'U' => Y(i) += 1
        case 'D' => Y(i) -= 1
        case 'L' => X(i) -= 1
        case 'R' => X(i) += 1
      }
    }

    val cumX = cumSum(X)
    val cumY = cumSum(Y)

//    debug(cumX)
//    debug(cumY)

    /**
      * x回で到達可能か
      */
    def test(x: Long): Boolean = {
      val xx = x / N * cumX(N) + cumX((x % N).toInt)
      val yy = x / N * cumY(N) + cumY((x % N).toInt)
      val needs = abs(dx - xx) + abs(dy - yy)
//      debug(s"test($x) ($xx, $yy) $needs")
      needs <= x
    }

    val INF = 1e18.toLong
//    val INF = 10L // debug
    // 余計な回数は風と逆方向にいくことで打ち消せるので単調増加
    var l = 0L // 必ず到着場所が違うので0はありえない
    // よくわからんけどlongなら大丈夫でしょう
    var r = INF
    while(r - l > 1) {
      val mid = (r + l) / 2
      if (test(mid)) r = mid
      else l = mid
    }

    if (r == INF) out.println(-1)
    else out.println(r)
  }

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

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

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

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

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

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

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

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

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

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

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


During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same.  When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A:  You can transmit the whole level A. Then you need to transmit n·m bytes via the network.  You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic.

The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters.

In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them.

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

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)

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


A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell.  Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes. Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the time for the robot to do its job.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. A test case consists of only one line, containing six integers $$$n$$$, $$$m$$$, $$$r_b$$$, $$$c_b$$$, $$$r_d$$$, and $$$c_d$$$ ($$$1 \le n, m \le 100$$$, $$$1 \le r_b, r_d \le n$$$, $$$1 \le c_b, c_d \le m$$$) — the sizes of the room, the initial position of the robot and the position of the dirt cell.

For each test case, print an integer — the time for the robot to clean the dirty cell. We can show that the robot always cleans the dirty cell eventually.

NoteIn the first example, the floor has the size of $$$10\times 10$$$. The initial position of the robot is $$$(6, 1)$$$ and the position of the dirty cell is $$$(2, 8)$$$. See the illustration of this example in the problem statement.In the second example, the floor is the same, but the initial position of the robot is now $$$(9, 9)$$$, and the position of the dirty cell is $$$(1, 1)$$$. In this example, the robot went straight to the dirty cell and clean it.   In the third example, the floor has the size $$$9 \times 8$$$. The initial position of the robot is $$$(5, 6)$$$, and the position of the dirty cell is $$$(2, 1)$$$.   In the fourth example, the floor has the size $$$6 \times 9$$$. The initial position of the robot is $$$(2, 2)$$$ and the position of the dirty cell is $$$(5, 8)$$$.   In the last example, the robot was already standing in the same column as the dirty cell, so it can clean the cell right away.

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

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


There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain.Each colony arrangement can be expressed as a string of even length, where the $$$i$$$-th character of the string represents the type of villain in the $$$i$$$-th hole. Iron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony.His assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times.Now Iron Man asks Jarvis $$$q$$$ questions. In each question, he gives Jarvis two numbers $$$x$$$ and $$$y$$$. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in $$$x$$$-th hole or $$$y$$$-th hole live in the same half and the Iron Man can destroy that colony arrangement.Two colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements.

The first line contains a string $$$s$$$ ($$$2 \le |s| \le 10^{5}$$$), representing the initial colony arrangement. String $$$s$$$ can have both lowercase and uppercase English letters and its length is even. The second line contains a single integer $$$q$$$ ($$$1 \le q \le 10^{5}$$$) — the number of questions. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le |s|$$$, $$$x_i \ne y_i$$$) — the two numbers given to the Jarvis for the $$$i$$$-th question.

For each question output the number of arrangements possible modulo $$$10^9+7$$$.

NoteConsider the first example. For the first question, the possible arrangements are "aabb" and "bbaa", and for the second question, index $$$1$$$ contains 'a' and index $$$2$$$ contains 'b' and there is no valid arrangement in which all 'a' and 'b' are in the same half.

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)

  val CtoI = Array.fill[Int](128)(-1)
  REP(26) { i =>
    CtoI('a' + i) = i
    CtoI('A' + i) = 26 + i
  }

  def solve(): Unit = {
    val S = ns()
    val N = S.length

    val NN = N

    def powMod(x: Int, n: Int, m: Int): Int = {
      def step(x: Long, n: Int, stack: Long): Long = {
        n match {
          case 0 => stack
          case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
        }
      }
      step(x, n, 1).toInt
    }

    val F = Array.ofDim[Long](NN + 1)
    F(0) = 1
    REP(NN) { i =>
      F(i + 1) = F(i) * (i + 1) % MOD
    }
    val I = Array.ofDim[Long](F.length)
    I(NN) = powMod(F(NN).toInt, MOD - 2, MOD)

    // x! = x(x-1)!
    // x!I(x!) ≡ (x-1)!I((x-1)!)
    // I((x-1)!) ≡ I(x!) * x   MODがでかいので(x-1)!はMODと素
    REP_r(NN) { i =>
      I(i) = I(i + 1) * (i + 1) % MOD
    }

    val C = Array.ofDim[Int](52)
    REP(N) { i =>
      C(CtoI(S(i))) += 1
    }
//    debug(C)

    var ALL = F(N / 2) * F(N / 2) % MOD
    REP(52) { i =>
      ALL = ALL * I(C(i)) % MOD
    }
//    debug(s"ALL $ALL")

    val dp = Array.ofDim[Int](N + 1)
    dp(0) = 1
    REP(52) { i =>
      val num = C(i)
      if (num > 0) {
        REP_r(N + 1) { j =>
          if (j - num >= 0) {
            dp(j) += dp(j - num)
            if (dp(j) >= MOD) dp(j) -= MOD
          }
        }
      }
    }

//    debug("DP")
//    debug(dp)

    def reverse(i: Int, work: Array[Int]): Unit = {
      val num = C(i)
      REP(N + 1) { i =>
        if (i - num >= 0) {
          work(i) += MOD - work(i - num)
          if (work(i) >= MOD) work(i) -= MOD
        }
      }

      //      debug(s"reverseDP")
      //      debug(work)
    }

    val calced = Array.ofDim[Long](52, 52)
    REP(52) { i =>
      val revI = dp.clone()
      reverse(i, revI)
      calced(i)(i) = revI(N / 2)

      val revJ = revI.clone()
      i + 1 until 52 foreach { j =>
        // i < j

        Array.copy(revI, 0, revJ, 0, N + 1)
        reverse(j, revJ)
        calced(i)(j) = revJ(N / 2)
      }
    }

    REP(ni()) { _ =>
      val x, y = ni() - 1
      val (p1, p2) = (CtoI(S(x)), CtoI(S(y)))
      val i = min(p1, p2)
      val j = max(p1, p2)
      val ans = ALL * calced(i)(j) % MOD * 2 % MOD
      out.println(ans)
    }
  }

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

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

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

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

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

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

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

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

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

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

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


Wherever the destination is, whoever we meet, let's render this song together.On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups:   Vertical: stands at (xi, 0), moves in positive y direction (upwards);  Horizontal: stands at (0, yi), moves in positive x direction (rightwards).   According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on.  Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.

The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 ≤ gi ≤ 2, 1 ≤ pi ≤ 99 999, 0 ≤ ti ≤ 100 000), describing a dancer's group gi (gi = 1 — vertical, gi = 2 — horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 ≤ xi ≤ w - 1 and 1 ≤ yi ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.

Output n lines, the i-th of which contains two space-separated integers (xi, yi) — the stopping position of the i-th dancer in the input.

NoteThe first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure.  In the second example, no dancers collide.

object B extends App {

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

  case class Dancer(id: Int, g: Int, p: Int, t: Int) {
    def diag: Int = p - t
    def ord1: Int = if (g == 2) -p else p
    def ord2: Int = if (g == 1) p else 1000000 - p
  }

  val Array(n, w, h) = readInts(3)
  val dancers = Array.tabulate(n) { id =>
    val Array(g, p, t) = readInts(3)
    Dancer(id, g, p, t)
  }

  val resX, resY = Array.ofDim[Int](n)

  for {
    group <- dancers.groupBy(_.diag).valuesIterator
    sorted1 = group.sortBy(_.ord1)
    sorted2 = group.sortBy(_.ord2)
    i <- sorted1.indices
  } {
    val id = sorted1(i).id
    if (sorted2(i).g == 1) {
      resX(id) = sorted2(i).p
      resY(id) = h
    } else {
      resX(id) = w
      resY(id) = sorted2(i).p
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (i <- 0 until n) {
    println(resX(i) + " " + resY(i))
  }
  Console.flush
}

object B extends App {

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

  case class Dancer(id: Int, g: Int, p: Int, t: Int) {
    def diag: Int = p - t
    def ord1: Int = if (g == 2) -p else p
    def ord2: Int = if (g == 1) p else 1000000 + p
  }

  val Array(n, w, h) = readInts(3)
  val dancers = Array.tabulate(n) { id =>
    val Array(g, p, t) = readInts(3)
    Dancer(id, g, p, t)
  }

  val resX, resY = Array.ofDim[Int](n)

  for {
    group <- dancers.groupBy(_.diag).valuesIterator
    sorted1 = group.sortBy(_.ord1)
    sorted2 = group.sortBy(_.ord2)
    i <- sorted1.indices
  } {
    val id = sorted1(i).id
    if (sorted2(i).g == 1) {
      resX(id) = sorted2(i).p
      resY(id) = h
    } else {
      resX(id) = w
      resY(id) = sorted2(i).p
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (i <- 0 until n) {
    println(resX(i) + " " + resY(i))
  }

  Console.flush
}


Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. The dragon has a hit point of $$$x$$$ initially. When its hit point goes to $$$0$$$ or under $$$0$$$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells.  Void Absorption Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will become $$$\left\lfloor \frac{h}{2} \right\rfloor + 10$$$. Here $$$\left\lfloor \frac{h}{2} \right\rfloor$$$ denotes $$$h$$$ divided by two, rounded down. Lightning Strike This spell will decrease the dragon's hit point by $$$10$$$. Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will be lowered to $$$h-10$$$.Due to some reasons Kana can only cast no more than $$$n$$$ Void Absorptions and $$$m$$$ Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. The next $$$t$$$ lines describe test cases. For each test case the only line contains three integers $$$x$$$, $$$n$$$, $$$m$$$ ($$$1\le x \le 10^5$$$, $$$0\le n,m\le30$$$)  — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.

If it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteOne possible casting sequence of the first test case is shown below: Void Absorption $$$\left\lfloor \frac{100}{2} \right\rfloor + 10=60$$$. Lightning Strike $$$60-10=50$$$. Void Absorption $$$\left\lfloor \frac{50}{2} \right\rfloor + 10=35$$$. Void Absorption $$$\left\lfloor \frac{35}{2} \right\rfloor + 10=27$$$. Lightning Strike $$$27-10=17$$$. Lightning Strike $$$17-10=7$$$. Lightning Strike $$$7-10=-3$$$.

import scala.io.StdIn

object Solution_B extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val input = StdIn.readLine().split(" ").map{_.toInt}
    var x = input(0)
    var n = input(1)
    val m = input(2)
    while (n > 0 && x > 18) {
      x = (x / 2) + 10
      n -= 1
    }
    if (x - 10 * m > 0) {
      println("NO")
    } else {
      println("YES")
    }
  }
}


Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.

The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.

Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.

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

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
}


Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array $$$a$$$ of the size of $$$10^9$$$ elements that is filled as follows:   $$$a_1 = -1$$$  $$$a_2 = 2$$$  $$$a_3 = -3$$$  $$$a_4 = 4$$$  $$$a_5 = -5$$$  And so on ... That is, the value of the $$$i$$$-th element of the array $$$a$$$ is calculated using the formula $$$a_i = i \cdot (-1)^i$$$.She immediately came up with $$$q$$$ queries on this array. Each query is described with two numbers: $$$l$$$ and $$$r$$$. The answer to a query is the sum of all the elements of the array at positions from $$$l$$$ to $$$r$$$ inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.Help her find the answers!

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of the queries. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^9$$$) — the descriptions of the queries.

Print $$$q$$$ lines, each containing one number — the answer to the query.

NoteIn the first query, you need to find the sum of the elements of the array from position $$$1$$$ to position $$$3$$$. The sum is equal to $$$a_1 + a_2 + a_3 = -1 + 2 -3 = -2$$$.In the second query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$5$$$. The sum is equal to $$$a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2$$$.In the third query, you need to find the sum of the elements of the array from position $$$5$$$ to position $$$5$$$. The sum is equal to $$$a_5 = -5$$$.In the fourth query, you need to find the sum of the elements of the array from position $$$4$$$ to position $$$4$$$. The sum is equal to $$$a_4 = 4$$$.In the fifth query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$3$$$. The sum is equal to $$$a_2 + a_3 = 2 - 3 = -1$$$.

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


Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8 + 3 + 6 + 7 = 24, sum of its row numbers equals 9 + 5 + 3 + 2 = 19, and 24 > 19.

The first line contains an integer n (1 ≤ n ≤ 30). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.

Print the single number — the number of the winning squares.

NoteIn the first example two upper squares are winning.In the third example three left squares in the both middle rows are winning:5 7 8 49 5 3 21 6 6 49 5 7 3

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

  }

}