Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa > pb, or pa = pb and ta < tb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y + 1, y + 2, ..., y + x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y + x + 1-th place.Your task is to count what number of teams from the given list shared the k-th place.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1 ≤ pi, ti ≤ 50) — the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces.

In the only line print the sought number of teams that got the k-th place in the final results' table.

NoteThe final results' table for the first sample is:   1-3 places — 4 solved problems, the penalty time equals 10  4 place — 3 solved problems, the penalty time equals 20  5-6 places — 2 solved problems, the penalty time equals 1  7 place — 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is:  1 place — 5 solved problems, the penalty time equals 3  2-5 places — 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams.

object P166A {
  def readPair : (Int, Int) = {
    val x = readLine().split(" ").map(_.toInt)
    (x(0), x(1))
  }

  def main ( args : Array[String] ) {
    val x = readPair
    val n = x._1
    val k = x._2

    var A = new Array(n) : Array[(Int,Int)]

    for(i <- 0 until n) A(i) = readPair

    def compare(x : (Int, Int), y : (Int, Int)) = {
      if(x._1 > y._1) true
      else if(x._1 == y._1) x._2 < y._2
      else false
    }

    A = A.sortWith(compare)

    println(A.count(_ == A(k - 1)))
  }
}

import scala.collection.mutable.ArrayBuffer

object Flask {
  class Result(var games:Int, var time:Int) {
    override def toString = games + ": " + time
  }

  def main(args: Array[String]): Unit = {
    var input = readLine.split(" ").map(_.toInt)
    var n = input(0); var k = input(1)

    var data:ArrayBuffer[Result] = new ArrayBuffer()
    (1 to n).foreach(i => {
      input = readLine.split(" ").map(_.toInt)
      data += new Result(input(0), input(1))
    })

    data = data.sortWith((x, y) => x.games > y.games || (x.games == y.games && x.time < y.time))
    var item = data(k - 1)
    println(data.count(x => x.games == item.games && x.time == item.time))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = (1 to n).map { _ =>
    val d = in.next().split(" ").map(_.toInt)
    (-d.head, d.last)
  }.sorted
  val kth = data(k - 1)
  println(data.count(_ == kth))
}

object A166 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val arr = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortWith{ case ((a1, b1), (a2, b2)) =>
        if(a1 > a2) {
          true
        } else if (a1 == a2) {
          if (b1 < b2) true
          else false
        } else {
          false
        }
    }

//    for((x,y) <- arr) println(s"$x $y")

    val target = arr(k-1)

    // firstGreaterOrEqualBinarySearch
    var first = -1

    {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low)/2
        if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 < target._2))
          low = mid + 1
        else
          high = mid

//        println(s"$low, $high, $mid")
      }

      first = low
    }

    //lastSame
    var last = -1

    {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low + 1)/2
//        println(s"$low, $high, $mid")
//        println(arr(low), arr(mid), arr(high), target)
        if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 <= target._2))
          low = mid
        else
          high = mid - 1

//        println(s"\n\n\n$low, $high, $mid\n\n\n")
      }

      last = low
    }

    out.println(last-first+1)

    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
//        private val input = new java.io.BufferedReader(new java.io.InputStreamReader(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 A166 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val arr = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortWith{ case ((a1, b1), (a2, b2)) =>
        if(a1 > a2) {
          true
        } else if (a1 == a2) {
          if (b1 < b2) true
          else false
        } else {
          false
        }
    }

//    for((x,y) <- arr) println(s"$x $y")

    val target = arr(k-1)

    // firstGreaterOrEqualBinarySearch
    var first = -1

    {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low)/2
        if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 < target._2))
          low = mid + 1
        else
          high = mid

//        println(s"$low, $high, $mid")
      }

      first = low
    }

    //lastSame
    val last = arr.lastIndexOf(target)

    out.println(last-first+1)

    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
//        private val input = new java.io.BufferedReader(new java.io.InputStreamReader(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 java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P166A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, K = sc.nextInt
  val PT = List.fill(N, 2)(sc.nextLong)

  def solve(): Int = {

    val groups = PT.groupBy[Long] {
        case List(p, t) => p * Int.MaxValue - t
      }.toSeq.sortWith(_._1 > _._1).map(_._2.size) toList

    @tailrec
    def loop(acc: Int, gs: List[Int]): Int = gs match {
        case x :: Nil => x
        case x :: xs => if (acc + x > K) x
                        else loop(acc + x, xs)
      }

    loop(1, groups)
  }

  out.println(solve)
  out.close
}

object CF166A {

  def main(args: Array[String]): Unit = {
    var Array(n, k) = Console.readLine.split(' ').map(_.toInt)
    var teams: List[(Int, Int)] = List()
    for (i <- 0.until(n)) {
      val Array(p, t) = Console.readLine.split(' ').map(_.toInt)
      teams ++= List((p, t))
    }
    teams = teams.sort((a1, a2) => (a1._1 > a2._1 || a1._1 == a2._1 && a1._2 < a2._2))
    var cnt = 1
    var at = 1
    while (at < k) {
      if (teams(at) == teams(at - 1)) {
        cnt += 1
      } else {
        cnt = 1
      }
      at += 1
    }
    while (at < n && teams(at) == teams(at - 1)) {
      cnt += 1
      at += 1
    }
    println(cnt)
  }
}

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 Array(n, k) = readInts
  val results = (for(_ <- 1 to n) yield readInts).map(x => (50 - x(0)) * 100 + x(1)).sorted
  def ans = results.count(_.equals(results(k - 1)))

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

object Main {
  def main(args: Array[String]) = {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(1)

    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val sorted = a.sortWith((a1, a2) => a1(0) > a2(0) || (a1(0) == a2(0) && a1(1) < a2(1)))
    val e = sorted(k - 1)
    val count = sorted.count(a0 => a0(0) == e(0) && a0(1) == e(1))
    println(count)
  }
}

object P166A {
  def readPair : (Int, Int) = {
    val x = readLine().split(" ").map(_.toInt)
    (x(0), x(1))
  }

  def main ( args : Array[String] ) {
    val x = readPair
    val n = x._1
    val k = x._2

    var A = new Array(n) : Array[(Int,Int)]

    for(i <- 0 until n) A(i) = readPair

    def compare(x : (Int, Int), y : (Int, Int)) = {
      if(x._1 > y._1) true
      else if(x._1 == y._1) x._2 > y._2
      else false
    }

    val T = (A.sortWith(compare)).distinct

    val size = T.size
    var cnt = A.count(_ == T(0)) //I = numarul de locuri pe care le impart cei de pe pozitia total + 1
    var total = 0 // I = numarul de locuri deja ocupate
    var index = 1
    var oldcnt = 0
    while(total < k && index < size) {
      total += cnt
      oldcnt = cnt
      cnt = A.count(_ == T(index))
      index += 1
    }
    // total >= k
    if(index == size) println(cnt)
    else println(oldcnt)
  }
}

object P166A {
  def readPair : (Int, Int) = {
    val x = readLine().split(" ").map(_.toInt)
    (x(0), x(1))
  }

  def main ( args : Array[String] ) {
    val x = readPair
    val n = x._1
    val k = x._2

    var A = new Array(n) : Array[(Int,Int)]

    for(i <- 0 until n) A(i) = readPair

    def compare(x : (Int, Int), y : (Int, Int)) = {
      if(x._1 > y._1) true
      else if(x._1 == y._1) x._2 > y._2
      else false
    }

    val T = (A.sortWith(compare)).distinct

    val size = T.size
    var cnt = A.count(_ == T(0))
    var total = cnt
    var index = 1
    while(total <= k && index < size) {
      cnt = A.count(_ == T(index))
      total += 1
      index += 1
    }

    println(cnt)
  }
}

object P166A {
  def readPair : (Int, Int) = {
    val x = readLine().split(" ").map(_.toInt)
    (x(0), x(1))
  }

  def main ( args : Array[String] ) {
    val x = readPair
    val n = x._1
    val k = x._2

    var A = new Array(n) : Array[(Int,Int)]

    for(i <- 0 until n) A(i) = readPair

    def compare(x : (Int, Int), y : (Int, Int)) = {
      if(x._1 > y._1) true
      else if(x._1 == y._1) x._2 > y._2
      else false
    }

    A = A.sortWith(compare)

    println(A.count(_ == A(k - 1)))
  }
}

object P166A {
  def readPair : (Int, Int) = {
    val x = readLine().split(" ").map(_.toInt)
    (x(0), x(1))
  }

  def main ( args : Array[String] ) {
    val x = readPair
    val n = x._1
    val k = x._2

    var A = new Array(n) : Array[(Int,Int)]

    for(i <- 0 until n) A(i) = readPair

    def compare(x : (Int, Int), y : (Int, Int)) = {
      if(x._1 > y._1) true
      else if(x._1 == y._1) x._2 > y._2
      else false
    }

    val T = (A.sortWith(compare)).distinct

    val size = T.size
    var end = A.count(_ == T(0))
    var start = 0
    // de la (start, start + end])
    var index = 1
    while(start + end < k && index < size) {
      start += end
      end = A.count(_ == T(index))
      index += 1
    }
    println(end)
  }
}

object P166A {
  def readPair : (Int, Int) = {
    val x = readLine().split(" ").map(_.toInt)
    (x(0), x(1))
  }

  def main ( args : Array[String] ) {
    val x = readPair
    val n = x._1
    val k = x._2

    var A = new Array(n) : Array[(Int,Int)]

    for(i <- 0 until n) A(i) = readPair

    def compare(x : (Int, Int), y : (Int, Int)) = {
      if(x._1 > y._1) true
      else if(x._1 == y._1) x._2 > y._2
      else false
    }

    A = A.sortWith(compare)

    println(A.count(_ == A(k)))
  }
}

object P166A {
  def readPair : (Int, Int) = {
    val x = readLine().split(" ").map(_.toInt)
    (x(0), x(1))
  }

  def main ( args : Array[String] ) {
    val x = readPair
    val n = x._1
    val k = x._2

    var A = new Array(n) : Array[(Int,Int)]

    for(i <- 0 until n) A(i) = readPair

    def compare(x : (Int, Int), y : (Int, Int)) = {
      if(x._1 > y._1) true
      else if(x._1 == y._1) x._2 > y._2
      else false
    }

    val T = (A.sortWith(compare)).distinct

    val size = T.size
    var cnt = A.count(_ == T(0))
    var total = cnt
    var index = 1
    while(total < k && index < size) {
      cnt = A.count(_ == T(index))
      total += 1
      index += 1
    }

    println(cnt)
  }
}

import scala.collection.mutable.ArrayBuffer

object Flask {
  class Result(var games:Int, var time:Int) {
    override def toString = games + ": " + time
  }

  def main(args: Array[String]): Unit = {
    var input = readLine.split(" ").map(_.toInt)
    var n = input(0); var k = input(1)

    var data:ArrayBuffer[Result] = new ArrayBuffer()
    (1 to n).foreach(i => {
      input = readLine.split(" ").map(_.toInt)
      data += new Result(input(0), input(1))
    })

    data = data.sortWith((x, y) => x.games > y.games || (x.games == y.games && x.time < y.time))
    var item = data(k)
    println(data.count(x => x.games == item.games && x.time == item.time))
  }
}

import scala.collection.mutable.ArrayBuffer

object Flask {
  class Result(var games:Int, var time:Int) { }

  def main(args: Array[String]): Unit = {
    var input = readLine.split(" ").map(_.toInt)
    var n = input(0); var k = input(1)

    var data:ArrayBuffer[Result] = new ArrayBuffer()
    (1 to n).foreach(i => {
      input = readLine.split(" ").map(_.toInt)
      data += new Result(input(0), input(1))
    })

    data.sortWith((x, y) => x.games > y.games || (x.games == y.games && x.time < y.time))
    var item = data(k)
    println(data.count(x => x.games == item.games && x.time == item.time))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = (1 to n).map { _ =>
    val d = in.next().split(" ").map(_.toInt)
    (-d.head, d.last)
  }.sorted
  println(data)
  val kth = data(k - 1)
  println(data.count(_ == kth))
}

object A166 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val arr = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortWith{ case ((a1, b1), (a2, b2)) =>
        if(a1 > a2) {
          true
        } else if (a1 == a2) {
          if (b1 < b2) true
          else false
        } else {
          false
        }
    }

    val target = arr(k-1)

    // firstGreaterOrEqualBinarySearch
    var first = -1

    {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low)/2
        if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 > target._2))
          low = mid + 1
        else
          high = mid
      }

      first = low
    }

    //lastSame
    val last = arr.lastIndexOf(target)

    out.println(last-first+1)

    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
//        private val input = new java.io.BufferedReader(new java.io.InputStreamReader(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 A166 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val arr = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sorted.reverse
    val target = arr(k-1)

    // firstGreaterOrEqualBinarySearch
    var first = -1

    {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low)/2
        if((arr(mid)._1 > target._1) || (arr(mid)._1 == target._1 && arr(mid)._2 > target._2))
          low = mid + 1
        else
          high = mid
      }

      first = low
    }

    //lastSame
    val last = arr.lastIndexOf(target)

    out.println(last-first+1)

    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(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 java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P166A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, K = sc.nextInt
  val PT = List.fill(N, 2)(sc.nextLong)

  def solve(): Int = {

    val groups = PT.groupBy[Long] {
        case List(p, t) => p * Int.MaxValue - t
      }.toSeq.sortWith(_._1 > _._1).map(_._2.size) toList

    @tailrec
    def loop(acc: Int, gs: List[Int]): Int = gs match {
        case x :: Nil => x
        case x :: xs => if (acc + x >= K) x
                        else loop(acc + x, xs)
      }

    loop(1, groups)
  }

  out.println(solve)
  out.close
}

object Main {
  def main(args: Array[String]) = {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(0)

    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val sorted = a.sortWith((a1, a2) => a1(0) < a2(0) || a1(1) > a2(1))
    val e = sorted(k - 1)
    val count = sorted.count(a0 => a0(0) == e(0) && a0(1) == e(1))
    println(count)
  }
}

object Main {
  def main(args: Array[String]) = {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(0)

    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val sorted = a.sortWith((a1, a2) => a1(0) > a2(0) || (a1(0) == a2(0) && a1(1) < a2(1)))
    val e = sorted(k - 1)
    val count = sorted.count(a0 => a0(0) == e(0) && a0(1) == e(1))
    println(count)
  }
}

object Main {
  def main(args: Array[String]) = {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(0)

    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val sorted = a.sortWith((a1, a2) => a1(0) < a2(0) || (a1(0) == a2(0) && a1(1) > a2(1)))
    val e = sorted(k - 1)
    val count = sorted.count(a0 => a0(0) == e(0) && a0(1) == e(1))
    println(count)
  }
}

object P166A {
  def readPair : (Int, Int) = {
    val x = readLine().split(" ").map(_.toInt)
    (x(0), x(1))
  }

  def main ( args : Array[String] ) {
    val x = readPair
    val n = x._1
    val k = x._2

    var A = new Array(n) : Array[(Int,Int)]

    for(i <- 0 until n) A(i) = readPair

    def compare(x : (Int, Int), y : (Int, Int)) = {
      if(x._1 > y._1) true
      else if(x._1 == y._1) x._2 > y._2
      else false
    }

    val T = (A.sortWith(compare)).distinct

    val size = T.size
    var cnt = A.count(_ == T(0)) //I = numarul de locuri pe care le impart cei de pe pozitia total + 1
    var total = 0 // I = numarul de locuri deja ocupate
    var index = 1
    var oldcnt = 0
    while(total < k && index < size) {
      total += cnt
      oldcnt = cnt
      cnt = A.count(_ == T(index))
      index += 1
    }
    // total >= k
    if(total < k) println(cnt)
    else println(oldcnt)
  }
}


Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.

The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.

In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.

import java.util.StringTokenizer

object _276A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt
  val a = (1 to n).map(i => { val f = next.toInt; val t = next.toInt; if (t <= k) f else f - (t - k) })
  println(a.max)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  println(Range(0, n).map{_ =>
    val d = in.next().split(" ").map(_.toInt)
    if (d(1) > k) d(0) - (d(1) - k)
    else d(0)
  }.max)
}

object A276 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val in = Array.fill(n)(readInts(2))

    var max = Int.MinValue
    for(i <- 0 until n) {
      if(in(i)(1) > k) {
        max = math.max(max, in(i)(0) - (in(i)(1) - k))
      } else {
        max = math.max(max, in(i)(0))
      }
    }
    println(max)
  }

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

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

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

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

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

}

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

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

  val n, k = sc.nextInt

  val answer = {
    List.fill(n) {
      val f, t = sc.nextInt
      if (t <= k) f
      else f + k - t
    }
  }.max

  out.println(answer)
  out.close
}

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

    val Array(n,k) = readLine().split(" ").map(_.toInt)
    var m = Integer.MIN_VALUE;
    for (i <- 1 to n) {
      val Array(f,t) = readLine().split(" ").map(_.toInt)
      m = math.max(m, f-math.max(0, t-k))
    }
  println(m)
  }
}

import java.io._
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)

  val Array(n, k) = readInts

  def ans = (for(_ <- 1 to n) yield readInts).map {
    case Array(f, t) => f - 0.max(t - k)
  }.max

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

import java.util.Scanner

object Main {

    val input = new Scanner(System.in)

    def main(args: Array[String]) {
        val n = input.nextInt
        val k = input.nextInt
        val it = new MyIt().take(n).map {
            case (f, t) => if (t > k) f - (t - k) else f
        }
        println(it.max)
    }

    class MyIt extends Iterator[(Int, Int)] {
        def hasNext = true
        def next : (Int, Int) = {
            val a = input.nextInt
            val b = input.nextInt
            (a, b)
        }
    }
}

object Main {
  def main(args: Array[String]) {
    val nk = readLine().split(" ").map(_.toInt)
    val k = nk(1)
    val pl = (1 to nk(0)).map{ _ =>
      val a = readLine().split(" ").map(_.toInt)
      if (a(1) > k) a(0) - a(1) + k
      else a(0)
    }
    println(pl.max)
  }
}

object A {

	def main(args: Array[String]) {
		val nk = Console.readLine.split(" ").map(_.toInt)
		val n = nk(0)
		val k = nk(1)

		def ud(f: Int, t: Int) = if(t > k) f - (t - k) else f

		var result = (for(i <- 0 until n) yield {
			val ft = Console.readLine.split(" ").map(_.toInt)
			ud(ft(0), ft(1))
		})
		println(result.max)
	}
}

object A {

	def main(args: Array[String]) {
		val nk = Console.readLine.split(" ").map(_.toInt)
		val n = nk(0)
		val k = nk(1)

		def ud(f: Int, t: Int) = if(t > k) f - (t - k) else f

		var mf = -1
		for(i <- 0 until n) {
			val ft = Console.readLine.split(" ").map(_.toInt)
			mf = math.max(mf, ud(ft(0), ft(1)))
		}
		println(mf)
	}
}


You are given a permutation $$$p$$$ of integers from $$$1$$$ to $$$n$$$, where $$$n$$$ is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type:   take two indices $$$i$$$ and $$$j$$$ such that $$$2 \cdot |i - j| \geq n$$$ and swap $$$p_i$$$ and $$$p_j$$$. There is no need to minimize the number of operations, however you should use no more than $$$5 \cdot n$$$ operations. One can show that it is always possible to do that.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$, $$$n$$$ is even) — the length of the permutation.  The second line contains $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$) — the given permutation.

On the first line print $$$m$$$ ($$$0 \le m \le 5 \cdot n$$$) — the number of swaps to perform. Each of the following $$$m$$$ lines should contain integers $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$|a_i - b_i| \ge \frac{n}{2}$$$) — the indices that should be swapped in the corresponding swap. Note that there is no need to minimize the number of operations. We can show that an answer always exists.

NoteIn the first example, when one swap elements on positions $$$1$$$ and $$$2$$$, the array becomes sorted.In the second example, pay attention that there is no need to minimize number of swaps.In the third example, after swapping elements on positions $$$1$$$ and $$$5$$$ the array becomes: $$$[4, 5, 3, 1, 2, 6]$$$. After swapping elements on positions $$$2$$$ and $$$5$$$ the array becomes $$$[4, 2, 3, 1, 5, 6]$$$ and finally after swapping elements on positions $$$1$$$ and $$$4$$$ the array becomes sorted: $$$[1, 2, 3, 4, 5, 6]$$$.

import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object C extends App {

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

  val Array(n) = readInts(1)
  val ps = readInts(n).map(_ - 1)

  def canSwap(i: Int, j: Int): Boolean = {
    2 * Math.abs(i - j) >= n
  }

  val moves = ArrayBuffer.empty[(Int, Int)]

  def swap(i: Int, j: Int): Unit = {
    require(canSwap(i, j))
    moves += (i + 1) -> (j + 1)
    val t = ps(i)
    ps(i) = ps(j)
    ps(j) = t
  }

  var ok = true
  do {
    ok = true
    for (i <- 0 until n) {
      val p = ps(i)
      if (i != p) {
        ok = false
        if (canSwap(i, p)) {
          swap(i, p)
        } else {
          if (canSwap(i, n - 1) && canSwap(p, n - 1)) {
            swap(i, n - 1)
            swap(p, n - 1)
          } else if (canSwap(i, 0) && canSwap(p, 0)) {
            swap(i, 0)
            swap(p, 0)
          } else {
            val min = i min p
            val max = i max p
            swap(min, n - 1)
            swap(n - 1, 0)
            swap(0, max)
          }
        }
      }
    }
  } while (!ok)

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

  println(moves.size)
  println(moves.map {
    case (i, j) => "" + i + " " + j
  }.mkString("\n"))

  Console.flush
}


Little Dima has two sequences of points with integer coordinates: sequence (a1, 1), (a2, 2), ..., (an, n) and sequence (b1, 1), (b2, 2), ..., (bn, n).Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence.Dima considers two assembled sequences (p1, q1), (p2, q2), ..., (p2·n, q2·n) and (x1, y1), (x2, y2), ..., (x2·n, y2·n) distinct, if there is such i (1 ≤ i ≤ 2·n), that (pi, qi) ≠ (xi, yi).As the answer can be rather large, print the remainder from dividing the answer by number m.

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 109). The numbers in the lines are separated by spaces. The last line contains integer m (2 ≤ m ≤ 109 + 7).

In the single line print the remainder after dividing the answer to the problem by number m.

NoteIn the first sample you can get only one sequence: (1, 1), (2, 1). In the second sample you can get such sequences : (1, 1), (2, 2), (2, 1), (3, 2); (1, 1), (2, 1), (2, 2), (3, 2). Thus, the answer is 2.

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i+1)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i+1)
    }
    arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)<y(1) else x(0)<y(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(j-1)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                var tt=i
                while(tt%2==0 && t>0){
                    tt/=2
                    t-=1
                }
                ans*=tt
            }
            else{
                ans*=i
            }
            ans%=m
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i)
    }
    arr=arr.sortBy(aa=>aa(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=0
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                while(ans%2==0){ans/=2;t-=1}
            }
            ans*=i
            if(t==0) ans%=m
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i)
    }
    arr=arr.sortBy(aa=>aa(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=0
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                var tt=i
                while(tt%2==0 && t>0){
                    tt/=2
                    t-=1
                }
                ans*=tt
            }
            else{
                ans*=i
                ans%=m
            }
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i+1)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i+1)
    }
    arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)<y(1) else x(0)<y(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                var tt=i
                while(tt%2==0 && t>0){
                    tt/=2
                    t-=1
                }
                ans*=tt
            }
            else{
                ans*=i
            }
            ans%=m
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i)
    }
    arr=arr.sortBy(aa=>aa(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                var tt=i
                while(tt%2==0 && t>0){
                    tt/=2
                    t-=1
                }
                ans*=tt
                ans%=m
            }
            else{
                ans*=i
                ans%=m
            }
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i)
    }
    arr=arr.sortBy(aa=>aa(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            while(ans%2==0 && t>0){
                ans/=2
                t-=1
            }
            ans*=i
            if(t==0) ans%=m
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i+1)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i+1)
    }
    arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)<y(1) else x(0)<y(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                var tt=i
                while(tt%2==0 && t>0){
                    tt/=2
                    t-=1
                }
                ans*=tt
                ans%=m
            }
            else{
                ans*=i
                ans%=m
            }
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i)
    }
    arr=arr.sortBy(aa=>aa(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=0
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            while(ans%2==0 && t>0){
                ans/=2
                t-=1
            }
            ans*=i
            if(t==0) ans%=m
        }
        ans
    }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val b=readLine.split(" ").map(_.toInt)
    val m=readInt
    val fact=new Array[Int](n+1)
    fact(0)=1
    for(i<-1 to n) fact(i)=(i*fact(i-1))%m
    val arr=a++b sorted
    var count:Long=1

    var i=0
    var j=0
    while(j<2*n){
        if(arr(j)==arr(i))
            j+=1
        else{
            count*=fact(j-i)
            count%=m
            i=j
        }
    }

    count*=fact(j-i)
    count%=m
    println(count)
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i)
    }
    arr=arr.sortBy(aa=>aa(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=0
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                while(ans%2==0){ans/=2;t-=1}
            }
            ans*=i
            ans%=m
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i+1)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i+1)
    }
    arr=arr.sortWith((x,y)=>x(0)<y(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                var tt=i
                while(tt%2==0 && t>0){
                    tt/=2
                    t-=1
                }
                ans*=tt
                ans%=m
            }
            else{
                ans*=i
                ans%=m
            }
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i)
    }
    arr=arr.sortBy(aa=>aa(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                var tt=i
                while(tt%2==0 && t>0){
                    tt/=2
                    t-=1
                }
                ans*=tt
            }
            else{
                ans*=i
                ans%=m
            }
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i+1)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i+1)
    }
    arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)<y(1) else x(0)<y(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(j-1)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                while(ans%2==0 && t>0){
                    ans/=2
                    t-=1
                }
            }
            ans*=i
            if(t==0)ans%=m
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i)
    }
    arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)<y(1) else x(0)<y(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(i)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            if(t>0){
                var tt=i
                while(tt%2==0 && t>0){
                    tt/=2
                    t-=1
                }
                ans*=tt
                ans%=m
            }
            else{
                ans*=i
                ans%=m
            }
        }
        ans
    }
}

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

object test6 extends App {
    val sc=new Scanner(System.in)
    val n=sc.nextInt
    var arr=new Array[Array[Int]](2*n)
    for(i<-0 until n){
        arr(i)=Array(sc.nextInt,i+1)
    }
    for(i<-0 until n){
        arr(n+i)=Array(sc.nextInt,i+1)
    }
    arr=arr.sortWith((x,y)=>if(x(0)==y(0)) x(1)<y(1) else x(0)<y(0))
    val m=sc.nextInt

    var count:Long=1
    var i=0
    var j=1
    var tmp=0
    while(j<2*n){
        if(arr(j)(0)==arr(i)(0)){
            if(arr(j)(1)==arr(j-1)(1)) tmp+=1
        }
        else{
            count*=fact(j-i,tmp)
            count%=m
            i=j
            tmp=0
        }
        j+=1
    }

    count*=fact(j-i, tmp)
    count%=m
    println(count)

    def fact(count:Int, tmp:Int):Long={
        var ans:Long=1
        var t=tmp
        for(i<-count to 2 by -1){
            while(ans%2==0 && t>0){
                ans/=2
                t-=1
            }
            ans*=i
            if(t==0)ans%=m
        }
        ans
    }
}


Ashish has $$$n$$$ elements arranged in a line. These elements are represented by two integers $$$a_i$$$ — the value of the element and $$$b_i$$$ — the type of the element (there are only two possible types: $$$0$$$ and $$$1$$$). He wants to sort the elements in non-decreasing values of $$$a_i$$$.He can perform the following operation any number of times:  Select any two elements $$$i$$$ and $$$j$$$ such that $$$b_i \ne b_j$$$ and swap them. That is, he can only swap two elements of different types in one move. Tell him if he can sort the elements in non-decreasing values of $$$a_i$$$ after performing any number of operations.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ $$$(1 \le n \le 500)$$$ — the size of the arrays. The second line contains $$$n$$$ integers $$$a_i$$$ $$$(1 \le a_i \le 10^5)$$$  — the value of the $$$i$$$-th element. The third line containts $$$n$$$ integers $$$b_i$$$ $$$(b_i \in \{0, 1\})$$$  — the type of the $$$i$$$-th element.

For each test case, print "Yes" or "No" (without quotes) depending on whether it is possible to sort elements in non-decreasing order of their value. You may print each letter in any case (upper or lower).

NoteFor the first case: The elements are already in sorted order.For the second case: Ashish may first swap elements at positions $$$1$$$ and $$$2$$$, then swap elements at positions $$$2$$$ and $$$3$$$.For the third case: The elements are already in sorted order.For the fourth case: No swap operations may be performed as there is no pair of elements $$$i$$$ and $$$j$$$ such that $$$b_i \ne b_j$$$. The elements cannot be sorted.For the fifth case: Ashish may swap elements at positions $$$3$$$ and $$$4$$$, then elements at positions $$$1$$$ and $$$2$$$.

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val n = readLine()
      val values = readIntLine()
      val types = readIntLine()
      println(if (types.distinct.size > 1 || values.sorted.equals(values)) "Yes" else "No")
    }
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

import java.util

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

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val as, bs = nextInts(n)
    val can = bs.distinct.size > 1 || util.Arrays.equals(as, as.sorted)

    out.println(if (can) "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 B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val bn = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val bs = bn.sum

    val ans = bn.sum > 0 && bn.sum < bn.length || (an, an.tail).zipped.forall(_ <= _)

    if (ans) println("Yes")
    else println("No")
  }
}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    var a = new Array[Int](n)
    var b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt()
    }
    var hasFirstType = false
    var hasSecondType = false
    for (i <- 0 until n) {
      b(i) = in.nextInt()
      if (b(i) == 0) {
        hasFirstType = true
      } else {
        hasSecondType= true
      }
    }

    val aCopy = a.clone
      java.util.Arrays.sort(aCopy)
    val res = if (a.sameElements(aCopy) || (hasFirstType && hasSecondType)) {
      "yes"
    } else {
      "no"
    }

    println(res)
  }

}


For the given integer $$$n$$$ ($$$n > 2$$$) let's write down all the strings of length $$$n$$$ which contain $$$n-2$$$ letters 'a' and two letters 'b' in lexicographical (alphabetical) order.Recall that the string $$$s$$$ of length $$$n$$$ is lexicographically less than string $$$t$$$ of length $$$n$$$, if there exists such $$$i$$$ ($$$1 \le i \le n$$$), that $$$s_i < t_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$s_j = t_j$$$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.For example, if $$$n=5$$$ the strings are (the order does matter):  aaabb  aabab  aabba  abaab  ababa  abbaa  baaab  baaba  babaa  bbaaa It is easy to show that such a list of strings will contain exactly $$$\frac{n \cdot (n-1)}{2}$$$ strings.You are given $$$n$$$ ($$$n > 2$$$) and $$$k$$$ ($$$1 \le k \le \frac{n \cdot (n-1)}{2}$$$). Print the $$$k$$$-th string from the list.

The input contains one or more test cases. The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case is written on the the separate line containing two integers $$$n$$$ and $$$k$$$ ($$$3 \le n \le 10^5, 1 \le k \le \min(2\cdot10^9, \frac{n \cdot (n-1)}{2})$$$. The sum of values $$$n$$$ over all test cases in the test doesn't exceed $$$10^5$$$.

For each test case print the $$$k$$$-th string from the list of all described above strings of length $$$n$$$. Strings in the list are sorted lexicographically (alphabetically).

aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa

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

  val t = nextInt

  for (_ <- 1 to t) {
    val n, k = nextInt
    var i = 1
    var cnt = 0
    while (cnt + i < k) {
      cnt += i
      i += 1
    }
    var j = k - cnt
    var s = Array.fill(n)('a')
    s(n - i - 1) = 'b'
    s(n - j) = 'b'
    out.println(s.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
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()

    def printEnd(k: Int): Unit = {
      out.print('b')
      out.print((1 until k).map(_ => 'a').mkString(""))
    }
    def printBeg(k: Int): Unit = {

      out.print((1 until k).map(_ => 'a').mkString(""))
      out.print('b')
    }
    def printMiddle(k: Int): Unit = {
      out.print((1 to k).map(_ => 'a').mkString(""))
    }

    (1 to t).foreach{ _ =>
      val n = in.nextLong()
      val k = in.nextLong()
      val z = ((Math.sqrt(8d*k+1)-1d)/2d).toLong
      val rowsUsed: Long = if((z*(z-1))/2 >= k) z-1 else  z
      val suma = (rowsUsed*(rowsUsed+1))/2
      val resta = k - suma
      //println(s"n: $n k:$k z:$z resta:$resta rowsUsed:$rowsUsed")

      if(resta!=0) {
        printBeg((n - rowsUsed - 1).toInt)
        printMiddle((rowsUsed - resta +1).toInt)
        printEnd(resta.toInt)
      }else{
        printBeg((n - rowsUsed).toInt)
        printEnd(rowsUsed.toInt)
      }
      out.println("")

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()

    def printEnd(k: Int): Unit = {
      out.print('b')
      out.print((1 until k).map(_ => 'a').mkString(""))
    }
    def printBeg(k: Int): Unit = {

      out.print((1 until k).map(_ => 'a').mkString(""))
      out.print('b')
    }
    def printMiddle(k: Int): Unit = {
      out.print((1 to k).map(_ => 'a').mkString(""))
    }

    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      val k = in.nextInt()
      val z = ((Math.sqrt(8d*k+1)-1d)/2d).toInt
      val rowsUsed = if((z*(z-1))/2 >= k) z-1 else  z
      val suma = (rowsUsed*(rowsUsed+1))/2
      val resta = k - suma
      //println(s"n: $n k:$k z:$z resta:$resta rowsUsed:$rowsUsed")

      if(resta!=0) {
        printBeg(n - rowsUsed - 1)
        printMiddle(rowsUsed - resta +1)
        printEnd(resta)
      }else{
        printBeg(n - rowsUsed)
        printEnd(rowsUsed)
      }
      out.println("")

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


There are $$$n$$$ products in the shop. The price of the $$$i$$$-th product is $$$a_i$$$. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.In fact, the owner of the shop can change the price of some product $$$i$$$ in such a way that the difference between the old price of this product $$$a_i$$$ and the new price $$$b_i$$$ is at most $$$k$$$. In other words, the condition $$$|a_i - b_i| \le k$$$ should be satisfied ($$$|x|$$$ is the absolute value of $$$x$$$).He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price $$$b_i$$$ of each product $$$i$$$ should be positive (i.e. $$$b_i > 0$$$ should be satisfied for all $$$i$$$ from $$$1$$$ to $$$n$$$).Your task is to find out the maximum possible equal price $$$B$$$ of all productts with the restriction that for all products the condiion $$$|a_i - B| \le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the same new price of all products) or report that it is impossible to find such price $$$B$$$.Note that the chosen price $$$B$$$ should be integer.You should answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is presented by two lines. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100, 1 \le k \le 10^8$$$) — the number of products and the value $$$k$$$. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^8$$$), where $$$a_i$$$ is the price of the $$$i$$$-th product.

Print $$$q$$$ integers, where the $$$i$$$-th integer is the answer $$$B$$$ on the $$$i$$$-th query. If it is impossible to equalize prices of all given products with restriction that for all products the condition $$$|a_i - B| \le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.

NoteIn the first example query you can choose the price $$$B=2$$$. It is easy to see that the difference between each old price and each new price $$$B=2$$$ is no more than $$$1$$$.In the second example query you can choose the price $$$B=6$$$ and then all the differences between old and new price $$$B=6$$$ will be no more than $$$2$$$.In the third example query you cannot choose any suitable price $$$B$$$. For any value $$$B$$$ at least one condition out of two will be violated: $$$|1-B| \le 2$$$, $$$|6-B| \le 2$$$.In the fourth example query all values $$$B$$$ between $$$1$$$ and $$$7$$$ are valid. But the maximum is $$$7$$$, so it's the answer.

import scala.io.StdIn

object EqualizePrice {
  def main(args: Array[String]): Unit = {
    val q = StdIn.readInt()
    for (qi <- 1 to q) {
      val nk = StdIn.readLine().split(' ')
      val n = nk(0).toInt
      val k = nk(1).toInt
      val as = StdIn.readLine().split(' ').map(_.toInt)
      val ans = as.map(_ + k).min
      val isErr = as.exists{a: Int =>
        Math.abs(ans - a) > k
      }
      if (qi == q) if (isErr) print(-1) else print(ans)
      else if (isErr) println(-1) else println(ans)

    }
  }
}

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

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    val ans = (1 to q) map {_ =>
      val n, k = io.read[Int]
      val as = io.read[Seq, Long](n)
      var lower = Long.MinValue
      var upper = Long.MaxValue

      try {
        for {
          a <- as
          x = a + k
          y = a - k
        } {
          require(y <= upper && x >= lower)
          lower = lower max y
          upper = upper min x
        }
        upper
      } catch {
        case _: Throwable => -1
      }
    }

    io.writeLines(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 apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[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")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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
      }
    }
  }
}