import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted

  val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0)
  val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sumL = 0L
  var sum = 0L
  var countL = 0
  var count = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (a != prev) {
      sumL = count * (a - 1L) - sum
      countL = count
    }
    sumsL(a) = sumL
    countsL(a) = countL
    sum += a
    count += 1
    counts(a) += 1
    prev = a
  }

  prev = -1
  var sumR = 0L
  sum = 0L
  var countR = 0
  count = 0
  for (i <- n - 1 to 0 by -1) {
    val a = as(i)
    if (a != prev) {
      sumR = sum - count * (a + 1L)
      countR = count
    }
    sumsR(a) = sumR
    countsR(a) = countR
    sum += a
    count += 1
    prev = a
  }

  var min = Long.MaxValue
  for (a <- as) {
    val need = k - counts(a)
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val leftCost0 = sumsL(a) + Math.min(need, countsL(a))
      val rightCost0 = sumsR(a) + Math.min(need, countsR(a))
      if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {
        val costLR = sumsL(a) + sumsR(a) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted

  val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0L)
  val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sum = 0L
  var count = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (a != prev) {
      sumsL(a) = count * (a - 1L) - sum
      countsL(a) = count
    }
    sum += a
    count += 1
    counts(a) += 1
    prev = a
  }

  prev = -1
  sum = 0L
  count = 0
  for (i <- n - 1 to 0 by -1) {
    val a = as(i)
    if (a != prev) {
      sumsR(a) = sum - count * (a + 1L)
      countsR(a) = count
    }
    sum += a
    count += 1
    prev = a
  }

  var min = Long.MaxValue
  for (a <- as) {
    val need = k - counts(a)
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val leftCost0 = sumsL(a) + Math.min(need, countsL(a))
      val rightCost0 = sumsR(a) + Math.min(need, countsR(a))
      if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {
        val costLR = sumsL(a) + sumsR(a) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted

  val sumsL, sumsR = mutable.Map.empty[Int, Long]
  val countsL, countsR = mutable.Map.empty[Int, Int]
  val counts = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sumL = 0L
  var sum = 0L
  var countL = 0
  var count = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (a != prev) {
      sumL = count * (a - 1L) - sum
      countL = count
    }
    sumsL(a) = sumL
    countsL(a) = countL
    sum += a
    count += 1
    counts(a) += 1
    prev = a
  }

  prev = -1
  var sumR = 0L
  sum = 0L
  var countR = 0
  count = 0
  for (i <- n - 1 to 0 by -1) {
    val a = as(i)
    if (a != prev) {
      sumR = sum - count * (a + 1L)
      countR = count
    }
    sumsR(a) = sumR
    countsR(a) = countR
    sum += a
    count += 1
    prev = a
  }

  var min = Long.MaxValue
  for (a <- as) {
    val need = k - counts(a)
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val leftCost0 = sumsL(a) + Math.min(need, countsL(a))
      val rightCost0 = sumsR(a) + Math.min(need, countsR(a))
      if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {
        val costLR = sumsL(a) + sumsR(a) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted

  val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0)
  val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sumL = 0L
  var sum = 0L
  var countL = 0
  var count = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (a != prev) {
      sumL = count * (a - 1) - sum
      countL = count
    }
    sumsL(a) = sumL
    countsL(a) = countL
    sum += a
    count += 1
    counts(a) += 1
    prev = a
  }

  prev = -1
  var sumR = 0L
  sum = 0L
  var countR = 0
  count = 0
  for (i <- n - 1 to 0 by -1) {
    val a = as(i)
    if (a != prev) {
      sumR = sum - count * (a + 1)
      countR = count
    }
    sumsR(a) = sumR
    countsR(a) = countR
    sum += a
    count += 1
    prev = a
  }

  var min = Long.MaxValue
  for (a <- as) {
    val need = k - counts(a)
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val leftCost0 = sumsL(a) + Math.min(need, countsL(a))
      val rightCost0 = sumsR(a) + Math.min(need, countsR(a))
      if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {
        val costLR = sumsL(a) + sumsR(a) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted
  //val ds = as.distinct

  val sumsL, sumsR = Array.ofDim[Long](n)
  val countsL, countsR, lefts, rights = Array.ofDim[Int](n)
  val counts = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sumL = 0L
  var sum = 0L
  var countL = 0
  var count = 0
  var left = -1
  for (i <- 0 until n) {
    if (as(i) != prev) {
      sumL = count * as(i) - sum
      countL = count
      left = i - 1
    }
    lefts(i) = left
    sumsL(i) = sumL
    countsL(i) = countL
    sum += as(i)
    count += 1
    counts(as(i)) += 1
    prev = as(i)
  }

  prev = -1
  var sumR = 0L
  sum = 0L
  var countR = 0
  count = 0
  var right = n
  for (i <- n - 1 to 0 by -1) {
    if (as(i) != prev) {
      sumR = sum - count * as(i)
      countR = count
      right = i + 1
    }
    rights(i) = right
    sumsR(i) = sumR
    countsR(i) = countR
    sum += as(i)
    count += 1
    prev = as(i)
  }

  var min = Long.MaxValue
//println(as.mkString(" "))
//  println(countsR.mkString(" "))
//  println(sumsR.mkString(" "))
//  println(counts)
  for (i <- 0 until n) {
    val need = k - counts(as(i))
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val l = lefts(i)
      val r = rights(i)
      val leftCost0 = if (l >= 0) sumsL(l) + Math.min(need, countsL(i)) else Long.MaxValue
      val rightCost0 = if (r < n) sumsR(r) + Math.min(need, countsR(i)) else Long.MaxValue
      if (countsL(i) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(i) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(i) + countsR(i) >= need && l >= 0 && r < n) {
        val costLR = sumsL(l) + sumsR(r) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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


import java.util.Date

object task2 {
  def main(args: Array[String]) {
        val len = readLine().split(" ").map(_.toInt)

        val a = readLine().split(" ").map(_.toLong).sorted
        val b = readLine().split(" ").map(_.toLong)

        val res = b.map { bj =>
          val bb = findMoreThenEl(a, bj)
          if(bb != -1) bb else len(0)
        }.mkString(" ")
    println(res)
  }

  def findMoreThenEl(list: Array[Long], el: Long): Int = {
    def inner(from: Int, to: Int): Int = {
      val len = to - from
      val newCenter = from + (len / 2)
      if (len <= 1 && list(from) <= el && list(to) <= el) {
        -1
      }
      else if (len <= 1 && list(from) > el) {
        from
      } else if (len <= 1 && list(to) > el) {
        to
      }
      else if (list(newCenter) <= el) {
        inner(newCenter, to)
      }
      else {
        inner(from, newCenter)
      }
    }

    inner(0, list.length - 1)
  }
}

import scala.collection.mutable

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt).sorted
  val b = in.next().split(' ').map(_.toInt)
  val map = mutable.Map.empty[Int, Long]
  var sum = 0l
  var startIndex = 0
  b.sorted.foreach { i =>
    while (startIndex < a.length && a(startIndex) <= i) {
      startIndex += 1
      sum += 1
    }
    map += (i -> sum)
  }
  println(b.map(map).mkString(" "))
}

import java.util.Date

object task2 {
  def main(args: Array[String]) {
        val len = readLine().split(" ").map(_.toInt)

        val a = readLine().split(" ").map(_.toLong).sorted
        val b = readLine().split(" ").map(_.toLong)

        val res = b.map { bj =>

          val bb = if(a(0)>bj) 0
          else if(a(len(0)-1)<=bj) len(0)
          else  findMoreThenEl(a, bj)
          if(bb != -1) bb else len(0)
        }.mkString(" ")
    println(res)
  }

  def findMoreThenEl(list: Array[Long], el: Long): Int = {
    def inner(from: Int, to: Int): Int = {
      val len = to - from
      val newCenter = from + (len / 2)
      if (len <= 1 && list(from) <= el && list(to) <= el) {
        -1
      }
      else if (len <= 1 && list(from) > el) {
        from
      } else if (len <= 1 && list(to) > el) {
        to
      }
      else if (list(newCenter) <= el) {
        inner(newCenter, to)
      }
      else {
        inner(from, newCenter)
      }
    }

    inner(0, list.length - 1)
  }
}

object B600 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m)
    var res = 0

    for(i <- 0 until m) {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low + 1)/2

        if(a(mid) > b(i))
          high = mid - 1
        else
          low = mid
      }
      if(a(low) <= b(i))
        out.print(s"${low+1} ")
      else
        out.print("0 ")
    }

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m)
    var res = 0

    for(i <- 0 until m) {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low + 1)/2

        if(a(mid) > b(i))
          high = mid - 1
        else
          low = mid
      }

      out.print(s"${low+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 task2 {
  def main (args: Array[String]){
    val len = readLine().split(" ")
    val a = readLine().split(" ")
    val b = readLine().split(" ")

    val res = b.map{bj =>a.count(ai=>ai<=bj)}.mkString(" ")

    println(res)
  }
}


object A608 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, s) = readInts(2)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1))).sorted.reverse
    var t = 0
    var curr = s
    for(i <- 0 until n) {
      if(in(i)._1 < curr) {
        t += (curr - in(i)._1)
        curr = in(i)._1
      }
      if(in(i)._2 > t) {
        t = in(i)._2
      }
    }
    t += curr
    println(t)
  }

  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

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

    var f = new Array[Int](n)
    var t = new Array[Int](n)
    for(i <- 0 until n){
      f(i) = sc.nextInt()
      t(i) = sc.nextInt()
    }

    //
    var tul = new Array[(Int, Int)](n + 1)
    tul(n) = (0, 0)

    for(i <- 0 until n)
      tul(i) = (f(i), t(i))

    tul = tul.sorted.reverse
    tul(n) = (10000, 100000)

    var ans = -1
    var man = 0
    for(i <- (0 to s).reverse){
      ans += 1
      if(man < n)
        if(tul(man)._1 == i){
          while(tul(man)._1 == i){
            ans = Math.max(ans, tul(man)._2)
            man += 1
          }
        }
    }

    println(ans)
  }
}

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

object A_336 {

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

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    val line1 = readLine
    val n = line1.int
    val s = line1.int

    var max = s

    for (i <- 0 until n) {
      val line = readLine
      val sum = line.int + line.int
      if (max < sum) {
        max = sum
      }
    }
    //---------------------------- parameters reading end ----------------------

    println(max)

  }

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

  var debugV = false
  var is = System.in
  val br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

}

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

val sa1 = """

"""

}

import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object ASolution extends App {
  val Array(numOfPassenger, numOfFloor) = StdIn.readLine().split(' ').map(_.toInt)
  val waitForPassenger = (0 until numOfPassenger).map { _ => StdIn.readLine().split(' ').map(_.toInt).sum }.max

  val output = math.max(numOfFloor, waitForPassenger)
  println(output)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, s) = in.next().split(' ').map(_.toInt)
  val res = (1 to n).foldLeft(s) {
    case (acc, _) =>
      val Array(f, t) = in.next().split(' ').map(_.toInt)
      Math.max(acc, t + f)
  }
  println(res)
}

import java.util.Scanner

object CF1 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.nextInt()
    val f = new Array[Int](n)
    val t = new Array[Int](n)
    var i = 0;
    while (i < n) {
      f(i) = sc.nextInt()
      t(i) = sc.nextInt()
      i += 1;
    }
    var maxF = f(0)
    var maxT = t(0)
    var max = t(0) - (s - f(0))
    i = 1
    while (i < n) {
      val tmp = t(i) - (s - f(i))
      if (tmp > max) {
        maxF = f(i)
        maxT = t(i)
        max = tmp
      }
      i += 1
    }
    if (max >= 0) System.out.print(maxF + maxT) else System.out.print(s)
    System.out.flush();
  }
}

import java.util.Scanner
import scala.math.max

object Main {
  def main(args: Array[String]) {
    val scanner = new Scanner(System.in)
    def next = scanner.next.toInt
    def nextPairs(n: Int) = 0.until(n).map(_ => (next, next)) // floor, time

    val n = next

    println(measureTrip(n, next, nextPairs(n)))
  }

  def measureTrip(peopleCount: Int, topFloor: Int, people: IndexedSeq[(Int, Int)]) = {
    val maxDelay = people.foldLeft(0)( (a: Int, p: (Int, Int)) => max(a, max(0, p._1 - (topFloor - p._2))) )
    topFloor + maxDelay
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, s) = in.next().split(' ').map(_.toInt)
  val res = (1 to n).foldLeft(0) {
    case (acc, _) =>
      val Array(f, t) = in.next().split(' ').map(_.toInt)
      Math.max(acc, t + f)
  }
  println(res)
}

import java.util.Scanner

object CF1 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.nextInt()
    val f = new Array[Int](n)
    val t = new Array[Int](n)
    var i = 0;
    while (i < n) {
      f(i) = sc.nextInt()
      t(i) = sc.nextInt()
      i += 1;
    }
    var maxF = f(0)
    var maxT = t(0)
    var max = t(0) - (s - f(0));
    i = 1;
    while (i < n) {
      val tmp = t(i) - (s - f(i))
      if (tmp > max) {
        maxF = f(i);
        maxT = t(i);
        max = tmp;
      }
      i += 1;
    }
    System.out.print(maxF + maxT);
    System.out.flush();
  }
}

import java.util.Scanner

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

    var f = new Array[Int](n)
    var t = new Array[Int](n)
    for(i <- 0 until n){
      f(i) = sc.nextInt()
      t(i) = sc.nextInt()
    }

    //
    var tul = new Array[(Int, Int)](n)
    for(i <- 0 until n)
      tul(i) = (f(i), t(i))

    tul = tul.sorted.reverse

    var ans = -1
    var man = 0
    for(i <- (0 to s).reverse){
      ans += 1
      if(man < n)
        if(tul(man)._1 == i){
          ans = Math.max(ans, tul(man)._2)
          man += 1
        }
    }

    println(ans)
  }
}


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)

  class Zipper {
    type A = Long
    var gen = 0
    val id = mutable.HashMap[A, Int]()
    var len = 0

    def get(x: A): Int = {
      id.getOrElseUpdate(x, {
        val i = gen
        gen += 1
        len += 1
        i
      })
    }
  }

  def solve(): Unit = {
    val NN = 1.2e6.toInt

    val N = ni()
    val A = na(N)
    val cum = cumSum(A)
    debug(cum)

    // [l, r)
    case class Range(l: Int, r: Int)

    val zip = new Zipper
    val G = Array.ofDim[Array[Range]](NN)
    val C = Array.ofDim[Int](NN)
    REP_r(N, 1) { r =>
      TO(0, r - 1) { l =>
        val v = cum(r) - cum(l)
        val id = zip.get(v)
        C(id) = C(id) + 1
      }
    }
    REP(zip.len) { i =>
      G(i) = Array.ofDim(C(i))
    }

    // 作るときにR順になるようにする。idを振るのが逆順なのでRを逆順でループする
    REP_r(N, 1) { r =>
      // Lはどうでもいい
      TO(0, r - 1) { l =>
        val v = cum(r) - cum(l)
        val id = zip.get(v)
        C(id) -= 1
        val i = C(id)
        G(id)(i) = Range(l, r)
      }
    }

    DEBUG {
      REP(zip.len) { i =>
        debug(G(i).mkString(","))
      }
    }

    var ans, res: Array[Range] = Array.ofDim[Range](1.2e6.toInt)
    var len = 0
    var ptr = 0

    REP(zip.len) { i =>
      val as = G(i)
      ptr = 0
      var r = 0
      REP(as.length) { i =>
        if (as(i).l >= r) {
          res(ptr) = as(i)
          ptr += 1
          r = as(i).r
        }
      }

//      debug(s"dump res v:$v")
//      debug(res.mkString(","))

      if (ans == null || ptr > len) {
        len = ptr
        val tmp = ans
        ans = res
        res = tmp
      }
    }

    out.println(len)
    REP(len) { i =>
      val rg = ans(i)
      out.println(s"${rg.l+1} ${rg.r}")
    }
  }

  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 debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val cum = cumSum(A)
    debug(cum)

    // [l, r)
    case class Range(l: Int, r: Int)

    val G = mutable.HashMap[Long, Array[Range]]()
    val C = mutable.HashMap[Long, Int]().withDefaultValue(0)
    REP(N) { l =>
      TO(l + 1, N) { r =>
        val v = cum(r) - cum(l)
        C(v) = C(v) + 1
      }
    }
    C.keys.foreach { v =>
      G(v) = Array.ofDim(C(v))
    }
    REP(N) { l =>
      TO(l + 1, N) { r =>
        val v = cum(r) - cum(l)
        val id = C(v) - 1
        C(v) = id
        G(v)(id) = Range(l, r)
      }
    }

    DEBUG {
      G.foreach { case (v, as) =>
        debug(s"A v:$v")
        debug(as.mkString(","))
      }
    }

    var ans: ArrayBuffer[Range] = null
    G.foreach { case (v, as) =>
      import java.util
      import java.util.Comparator
      val res = ArrayBuffer[Range]()
      util.Arrays.sort(as, new Comparator[Range] {
        override def compare(o1: Range, o2: Range): Int = Integer.compare(o1.r, o2.r) //　終端で昇順ソートする
      })

      var r = 0
      REP(as.length) { i =>
        if (as(i).l >= r) {
          res += as(i)
          r = as(i).r
        }
      }

      debug(s"dump res v:$v")
      debug(res.mkString(","))

      if (ans == null || res.length > ans.length) ans = res
    }

    out.println(ans.length)
    REP(ans.length) { i =>
      val rg = ans(i)
      out.println(s"${rg.l+1} ${rg.r}")
    }
  }

  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 debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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


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

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

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

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

  def solve(): Unit = {
    val N = 1e6.toInt
    val C = Array.ofDim[Int](N, 4)

    def len(i: Long) = i.toString.count(_ != '0')

    REP(N) { i =>
      if (i == 0) C(0)(0) = 1
      else {
        REP(4) { j =>
          C(i)(j) = C(i - 1)(j)
        }

        val cnt = i.toString.count(_ != '0')
        if (cnt <= 3) C(i)(cnt) += 1
      }
    }

    def cnt(x: Long): Long = {
      if (x < N) {
        C(x.toInt).sum

      } else if (x >= N && x < 1e12.toLong) {
        val q = (x / N).toInt
        val m = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        REP(4 - len(q)) { i =>
          res += C(m)(i)
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            res += C(q - 1)(i).toLong * C(N - 1)(j)
          }
        }

        res

      } else {
        val q = (x / N / N).toInt
        val m1 = (x / N % N).toInt
        val m2 = (x % N).toInt

        var res = 0L

        // 10^12以降の値が固定の場合、10^12以下の値も制限される
        val i = len(q)
        val j = len(m1)
        REP(4 - (j + i)) { k =>
          res += C(m2)(k)
        }

        if (m1 > 0) {
          REP(4 - i) { j =>
            REP(4 - (j + i)) { k =>
              res += C(m1 - 1)(j) * C(N - 1)(k)
            }
          }
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            REP(4 - (j + i)) { k =>
              res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)
            }
          }
        }

        res
      }
    }

    REP(ni()) { _ =>
      val l, r = nl()
      val ans = cnt(r) - cnt(l - 1)
      out.println(ans)
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val T = ni()
    rep(T) { _ =>
      val l, r = nl()
      val ans = f(r.toString.toCharArray) - f((l - 1).toString.toCharArray)
      out.println(ans)
    }
  }

  def f(D: Array[Char]): Int = {
    val N: Int = D.length
    val memo = Array.fill[Int](N, 4)(-1)
    def g(i: Int, k: Int, f: Boolean): Int = {
      if (k < 0) 0
      else if (i == N) 1
      else {
        if (f && memo(i)(k) != -1) {
          memo(i)(k)
        } else {
          var res = 0
          val d = if (f) 9 else D(i) - '0'
          rep(d + 1) { j =>
            val newF = f || j < d
            val newK = if (j == 0) k else k - 1 // 0以外の時kの値を減らす
            res += g(i + 1, newK, newF)
          }
          if (f) memo(i)(k) = res
          res
        }
      }
    }

    g(0, 3, f = false)
  }

  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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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 T = ni()
    rep(T) { _ =>
      val l, r = nl()
      val ans = f(r) - f(l - 1)
      out.println(ans)
    }
  }

  val pow10 = Array.ofDim[Long](19)
  pow10(0) = 1
  rep(18)(i => pow10(i + 1) = pow10(i) * 10)

  /**
    * @return (log10の整数値, 最大桁の値)
    */
  def log10(x: Long): (Int, Int) = {
    var a = x
    var i = 0
    while(a >= 10) {
      a /= 10
      i += 1
    }
    (i, a.toInt)
  }

  def f(x: Long): Int = {
    val (n, _) = log10(x)
    val N = n + 1
    val dp = Array.ofDim[Int](N + 1, 2, 4)
    dp(0)(0)(3) = 1

    rep(N) { i =>
      val D = (x / pow10(n - i) % 10).toInt
      rep(2) { f =>
        rep(4) { k =>
          val d = if (f == 1) 9 else D
          rep(d + 1) { j =>
            val newF = f | (if(j < d) 1 else 0)
            val newK = if (j == 0) k else k - 1
            if (newK >= 0) dp(i + 1)(newF)(newK) += dp(i)(f)(k)
          }
        }
      }
    }

    var res = 0
    rep(2) { f =>
      rep(4) { k =>
        res += dp(N)(f)(k)
      }
    }
    res
  }

  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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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 T = ni()
    rep(T) { _ =>
      val l, r = nl()
      val ans = f(r.toString.toCharArray) - f((l - 1).toString.toCharArray)
      out.println(ans)
    }
  }

  def f(D: Array[Char]): Int = {
    val N = D.length
    val dp = Array.ofDim[Int](N + 1, 2, 4)
    dp(0)(0)(3) = 1

    rep(N) { i =>
      rep(2) { f =>
        rep(4) { k =>
          val d = if (f == 1) 9 else D(i) - '0'
          rep(d + 1) { j =>
            val newF = f | (if(j < d) 1 else 0)
            val newK = if (j == 0) k else k - 1
            if (newK >= 0) dp(i + 1)(newF)(newK) += dp(i)(f)(k)
          }
        }
      }
    }

    var res = 0
    rep(2) { f =>
      rep(4) { k =>
        res += dp(N)(f)(k)
      }
    }
    res
  }

  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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

object ClassyNumbers {

  def main(args: Array[String]): Unit = {
    println {
      (for (_ <- 1 to io.StdIn.readInt()) yield {
        val Array(l, r) = io.StdIn.readLine().split(" ").map(_.toLong)

        val Classy = 4

        def solve(digits: Seq[Int]): Int = {

          val Idx = digits.size

          val dp = Array.fill[Option[Int]](Idx, Classy, 2)(None)

          def loop(idx: Int, flag: Boolean, classy: Int): Int = {

            if (classy == Classy)
              0
            else if (idx == Idx)
              1
            else
              dp(idx)(classy)(if (flag) 1 else 0).getOrElse {
                val res: Int = (1 to (if (flag) digits(idx) else 9))
                  .foldLeft(0)(
                    (acc, i) =>
                      acc + loop(idx + 1, flag && i == digits(idx), classy + 1)
                  ) + loop(idx + 1, flag && 0 == digits(idx), classy)

                dp(idx)(classy)(if (flag) 1 else 0) = Some(res)
                res
              }
          }

          loop(0, flag = true, 0)
        }

        val lDigits = (l - 1).toString.map(_ - '0')
        val rDigits = r.toString.map(_ - '0')

        solve(rDigits) - solve(lDigits)

      }).mkString("\n")
    }
  }

}

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 = 1e6.toInt
    val C = Array.ofDim[Int](N, 4)

    def len(i: Long) = i.toString.count(_ != '0')

    REP(N) { i =>
      if (i == 0) C(0)(0) = 1
      else {
        REP(4) { j =>
          C(i)(j) = C(i - 1)(j)
        }

        val cnt = i.toString.count(_ != '0')
        if (cnt <= 3) C(i)(cnt) += 1
      }
    }

    def cnt(x: Long): Long = {
      if (x < N) {
        C(x.toInt).sum

      } else if (x >= N && x < 1e12.toLong) {
        val q = (x / N).toInt
        val m = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        REP(4 - len(q)) { i =>
          res += C(m)(i)
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            res += C(q - 1)(i).toLong * C(N - 1)(j)
          }
        }

        res

      } else {
        val q = (x / N / N).toInt
        val m1 = (x / N % N).toInt
        val m2 = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        val i = len(q)
        REP(4 - i) { j =>
          REP(4 - (j + i)) { k =>
            res += C(m1)(j).toLong * C(m2)(k)
          }
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            REP(4 - (j + i)) { k =>
              res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)
            }
          }
        }

        res
      }
    }

    REP(ni()) { _ =>
      val l, r = nl()
      val ans = cnt(r) - cnt(l - 1)
      out.println(ans)
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = 1e6.toInt
    val C = Array.ofDim[Int](N, 4)

    def len(i: Long) = i.toString.count(_ != '0')

    REP(N) { i =>
      if (i == 0) C(0)(0) = 1
      else {
        REP(4) { j =>
          C(i)(j) = C(i - 1)(j)
        }

        val cnt = i.toString.count(_ != '0')
        if (cnt <= 3) C(i)(cnt) += 1
      }
    }

    def cnt(x: Long): Long = {
      if (x < N) {
        C(x.toInt).sum

      } else if (x >= N && x < 1e12.toLong) {
        val q = (x / N).toInt
        val m = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        REP(4 - len(q)) { i =>
          res += C(m)(i)
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            res += C(q - 1)(i).toLong * C(N - 1)(j)
          }
        }

        res

      } else {
        val q = (x / N / N).toInt
        val m1 = (x / N % N).toInt
        val m2 = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        REP(4 - len(q)) { i =>
          REP(4 - i) { j =>
            res += C(m1)(i).toLong * C(m2)(j)
          }
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            REP(4 - j) { k =>
              res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)
            }
          }
        }

        res
      }
    }

    REP(ni()) { _ =>
      val l, r = nl()
      val ans = cnt(r) - cnt(l - 1)
      out.println(ans)
    }
  }

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


import io.StdIn._
import scala.collection.mutable._

object Solution {

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

  def main(args: Array[String]) {
    val Array(n, p) = readInts(2)
    val a = Array.fill[Double](n)(0)

    (1 to n).foreach { i =>
      val Array(l, r) = readInts(2)
      a(i-1) = (r / p - (l - 1) / p).toDouble / (r - l + 1)
    }

    var res: Double = 0
    for (i <- 0 to n-1) {
      res += 2000 * a(i)
      if (i == 0) res += 1000 * (1 - a(i)) * (a(i+1) + a(n-1))
      else if (i == n-1) res += 1000* (1 - a(i)) * (a(0) + a(i-1))
      else res += 1000* (1 - a(i)) * (a(i-1) + a(i+1))
    }

    println(res)

//    Console.withOut(new java.io.BufferedOutputStream(Console.out))
//    println(res.mkString("\n"))
//    Console.flush
  }
}

/**
  * Created by octavian on 01/02/2016.
  */
object Flowers {

  val GIVES = 2 * 1000

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("./src/flowers.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/flowers.out")))

    val Array(n, p) = readLine.split(" ").map(_.toInt)
    var notProb = Vector.empty[Double]

    for(i <- 0 until n) {
      val Array(a, b) = readLine.split(" ").map(_.toInt)
      val div = b/p - (a - 1)/p
      //println("notDiv is: " + notDiv)
      notProb :+= (b - a + 1 - div).toDouble/(b - a + 1)
    }

    var result: BigDecimal = 0.0
    for(i <- 0 until n) {
      result += GIVES * (1 - notProb(i) * notProb((i + 1)%n))
    }

    println(result)
  }
}

import scala.io.StdIn

object Main {
  final val V = 1000
  def main(args: Array[String]) {
    val Array(n, p) = StdIn.readLine().split(" ").map(_.toInt)
    val a = Array.fill(n)(0.0)
    for (i <- 0 until n) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)
      a(i) = (r / p - (l - 1) / p).toDouble / (r - l + 1).toDouble
    }
    var ans = 0.0
    for (i <- 0 until n) {
      ans += 1000 * (1 - (1 - a((i + n - 1) % n)) * (1 - a(i)))
      ans += 1000 * (1 - (1 - a(i)) * (1 - a((i + 1) % n)))
    }
    println(ans)
  }
}

import scala.collection.mutable.ListBuffer

object C {
  def main(args: Array[String]) {
    val Array(n, p) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val P = (1 to n).map(x => {
      val q = scala.io.StdIn.readLine.split(" ").map(_.toInt)
      val c2 = q(1) / p
      val c1 = (q(0)-1) / p
      1.0 - 1.0 * (c2-c1)/(q(1) - q(0)+1)
    })

    println((1 to n).map(i => 1.0 - P(i%n)*P((i+1)%n)).sum * 2000)
  }
}

import scala.collection._

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, p) = readInts(2)
  val ls, rs = Array.ofDim[Int](n + 1)

  for (i <- 0 until n) {
    val Array(l, r) = readInts(2)
    ls(i) = l
    rs(i) = r
  }
  ls(n) = ls(0)
  rs(n) = rs(0)

  var res = 0d

  for (i <- 0 until n) {
    val j = if (i == 0) n - 1 else i - 1
    val cnt0 = rs(j) / p - (ls(j) - 1) / p
    val cnt1 = rs(i) / p - (ls(i) - 1) / p
    val cnt2 = rs(i + 1) / p - (ls(i + 1) - 1) / p
    val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)
    val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)
    val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)

    res += 2 * prob1 + prob0 * (1d - prob1) + prob2 * (1d - prob1)
  }

  println(res * 1000d)
}

// So you like object Task
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

object Task {

    def calcProbability(shark: (Long, Long), p: Long): Double = {
        val total = shark._2 - shark._1 + 1
        val prime = shark._2 / p - (shark._1 - 1) / p
        prime.toDouble / total

    }

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val p = in.nextLong()
        val probs = Array.fill(n) { calcProbability((in.nextLong(), in.nextLong()), p) }
        val ones = 4000.0 * probs.sum
        val twos = 2000.0 * (0 until n).map(i => probs(i) * probs((i + 1) % n)).sum
        println(ones - twos)

    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch  {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while(!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

    def nextDouble(): Double = {
        next().toDouble
    }

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

import scala.collection._

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, p) = readInts(2)
  val ls, rs = Array.ofDim[Int](n + 1)

  for (i <- 0 until n) {
    val Array(l, r) = readInts(2)
    ls(i) = l
    rs(i) = r
  }
  ls(n) = ls(0)
  rs(n) = rs(0)

  var res = 0d

  for (i <- 0 until n) {
    val j = if (i == 0) n - 1 else i - 1
    val cnt0 = rs(j) / p - (ls(j) - 1) / p
    val cnt1 = rs(i) / p - (ls(i) - 1) / p
    val cnt2 = rs(i + 1) / p - (ls(i + 1) - 1) / p
    val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)
    val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)
    val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)

    res += 1d - (1d - prob0) * (1d - prob1) * (1d - prob2)
  }

  println(res * 3000d)
}

import scala.collection._

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, p) = readInts(2)
  val ls, rs = Array.ofDim[Int](n + 1)

  for (i <- 0 until n) {
    val Array(l, r) = readInts(2)
    ls(i) = l
    rs(i) = r
  }
  ls(n) = ls(0)
  rs(n) = rs(0)

  var res = 0d

  for (i <- 0 until n) {
    val j = if (i == 0) n - 1 else i - 1
    val cnt0 = rs(j) / p - ls(j) / p
    val cnt1 = rs(i) / p - ls(i) / p
    val cnt2 = rs(i + 1) / p - ls(i + 1) / p
    val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)
    val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)
    val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)

    res += 1d - (1d - prob0) * (1d - prob1) * (1d - prob2)
  }

  println(res * 3000d)
}


/*
 * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/
 */

object Main extends App {
  import java.{util => ju}
  import scala.annotation._
  import scala.collection._
  import scala.collection.{mutable => mu}
  import scala.collection.JavaConverters._
  import scala.math._

  val sc = new ju.Scanner(System.in)
  val n = sc.nextInt
  val m = Array.fill(n)(sc.nextInt).sorted
  val tot = m.sum
  val res = Array.tabulate(n)(i => (tot + i) / n)
  println((0 until n).map(i => (m(i) - res(i)) max 0).sum)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum.toFloat / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el < middle => (s, b + (middle - el).toLong)
    case ((s, b), el) => (s + (el - middle).toLong, b)
  }
  println(Math.max(res._1, res._2))

}

import java.util.Scanner

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

    val count = next
    val sizes = 0.until(count).map(_ => next)

    println(countSwaps(sizes))
  }

  def countSwaps(initialSizes: IndexedSeq[Int]) = {
    val count = initialSizes.size
    val targetSizes = targetSizesClosure(initialSizes)
    val sizes = initialSizes.sorted

    var result = 0
    for (i <- 0 until count) {
      val diff = targetSizes(i) - sizes(i)
      if (diff > 0)
        result += diff
    }

    result
  }

  def targetSizesClosure(initialSizes: IndexedSeq[Int]) = {
    val n = initialSizes.size
    val s = initialSizes.foldLeft(0)(_ + _)
    val d = s / n
    val stair = n - s % n

    index: Int => if (index < stair) d else d + 1
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val sum = data.sum
  val middle = sum / n
  if (sum % n == 0) {
    println(data.map(i => Math.abs(middle - i)).sum / 2)
  } else {
    val big = sum % n
    val res = data.foldLeft((0l, 0l)) {
      case ((s, b), el) if el < middle => (s + middle - el, b)
      case ((s, b), el) => (s + el - middle - 1, b + 1)
    }
    println((res._1 + Math.abs(res._2 - big)) / 2)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum.toFloat / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el < middle => (s, b + (middle - el).toLong)
    case ((s, b), el) => (s + (middle - el).toLong, b)
  }
  println(Math.max(res._1, res._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el <= middle => (s + middle - el, b)
    case ((s, b), el) => (s, b + middle - el)
  }
  println(Math.max(res._1, res._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val sum = data.sum
  val middle = sum / n
  if (sum % n == 0) {
    val res = data.map(i => Math.abs(middle - i)).sum
    println( res / 2 + res % 2)
  } else {
    val big = sum % n
    val res = data.foldLeft((0l, 0l)) {
      case ((s, b), el) if el < middle => (s + middle - el, b)
      case ((s, b), el) => (s + el - middle - 1, b + 1)
    }
    val rez = res._1 + Math.abs(res._2 - big)
    println(rez / 2 + rez % 2)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el < middle => (s + middle - el, b)
    case ((s, b), el) => (s, b + middle - el)
  }
  println(Math.max(res._1, res._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum.toFloat / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el < middle => (s + (middle - el).toLong, b)
    case ((s, b), el) => (s, b + (middle - el).toLong)
  }
  println(Math.max(res._1, res._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val sum = data.sum
  val middle = sum / n
  if (sum % n == 0) {
    println(data.map(i => Math.abs(middle - i)).sum / 2)
  } else {
    val big = sum % n
    val res = data.foldLeft((0, 0)) {
      case ((s, b), el) if el < middle => (s + middle - el, b)
      case ((s, b), el) => (s + el - middle - 1, b + 1)
    }
    println((res._1 + Math.abs(res._2 - big)) / 2)

  }

}


object Main {
  val cin = scala.io.Source.stdin.bufferedReader()
  def readInt(): Int = {
    var res = 0
    var c = cin.read()
    while (!Character.isDigit(c)) {
      c = cin.read()
    }
    do {
      res = res * 10 + c - '0'
      c = cin.read()
    } while (Character.isDigit(c))
    res
  }
  def main(args: Array[String]) = {
    val n = readInt()
    val cnt: Array[Int] = Array.ofDim(100001)
    val memo: Array[Long] = Array.ofDim(3)
    for (i <- 1 to n)
      cnt(readInt()) += 1
    for (i <- 1 to 100000)
      memo(i % 3) = Math.max(memo((i + 1) % 3) + i.toLong * cnt(i), memo((i + 2) % 3))
    println(memo(1))
  }
}

object TEST extends App {
  var a = Array.fill(100001)(0)
  var dp:Array[Long] = Array.fill(100001)(0)
  val n = readInt
  readLine.split(" ").map(_.toInt).foreach(x => a(x)+=1)
  dp(1) = a(1)
  (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i.toLong*a(i)+dp(i-2)))
  print(dp(100000))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100001
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(N + 5)(0L)
  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }

  dp(1) = as(1)
  2 to N foreach { i =>
    dp(i) = max(dp(i - 1), dp(i - 2) + i * as(i))
  }

  println(dp(N))
}

import scala.math._

object Problem extends App {
  import Scanner._

  val n = readInt
  val seq = Array.fill(n)(readInt)
  val (min, max) = (seq.min, seq.max)

  val counts = Array.ofDim[Int](max - min + 1)
  for(v <- seq)
    counts(v-min) += 1

  val dp: Memo[Int, Long] = Memo {
    case `min` => min.toLong*counts(0)
    case v if v < min => 0L
    case v => math.max(dp(v-1), dp(v-2) + v.toLong*counts(v-min))
  }

  println(dp(max))
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = scala.collection.mutable.Map.empty[A, B]
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

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

/**
 * Created by arseny on 08.08.14.
 */
object C extends App {

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextInt
    val as = Array.fill(n)(0L)
    (0 until n).foreach(i => as(i) = nextLong)
    val count = Array.fill(100 * 1000 + 1)(0L)
    as.foreach(a => count(a.toInt) += 1L)
    val dp = Array.fill(100 * 1000 + 1)(0L)
    dp(1) = count(1)
    (2 to 100 * 1000).foreach(i => dp(i) = math.max(i.toLong * count(i) + dp(i - 2), dp(i - 1)))
    out.println(dp.max)
  }

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

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val max = data.max
  val count = Array.ofDim[Long](max + 1)
  data.foreach { num => count(num) += 1 }
  if (count.length == 2)
    println(count(1))
  else {
    var a: Long = count(1)
    var b: Long = Math.max(a, count(2) * 2)
    var i = 3

    while (i <= max) {
      val max = Math.max(b, a + count(i) * i)
      a = b
      b = max
      i += 1
    }
    println(b)
  }
}

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

object C {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Long](100005)
    for (i <- 0 until n) {
      a(i) = nextInt
      num(a(i)) += 1
    }
    val dp = new Array[Long](100005)
    Arrays.fill(dp, 0L)
    dp(1) = num(1)
    var i = 2
    while (i <= 100002) {
      dp(i) = Math.max(dp(i - 1), dp(i - 2) + num(i) * i.toLong)
      i += 1
    }
    out.println(dp(100002))
    return 1
  }

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

import scala.collection.mutable
import scala.util.Try

object A455 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val counts = Array.fill[Int](5*100000 + 1)(0)
    val dp = Array.fill[Long](5*100000 + 1)(0L)
    input.foreach(x => counts(x) += 1)
    var i = 3
    dp(1) = counts(1)
    dp(2) = counts(2)*2
    while(i < 5*100000+1) {
      dp(i) = i.toLong*counts(i) + math.max(dp(i-2), Try{dp(i-3)}.getOrElse(0L))
      i += 1
    }

    println(dp.max)
  }

}

object Main {
  val cin = scala.io.Source.stdin.getLines()
  def main(args: Array[String]) = {
    val n = cin.next()
    val data = cin.next().split(" ").map(_.toInt)
    val cnt: Array[Int] = Array.ofDim(100001)
    data.foreach(x => cnt(x) += 1)
    val memo: Array[Long] = Array.ofDim(3)
    for (i <- 1 to 100000)
      memo(i % 3) = Math.max(memo((i + 1) % 3) + i.toLong * cnt(i), memo((i + 2) % 3))
    println(memo(1))
  }
}

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

import math.max

object Boredom455A {

  def main(args : Array[String]) : Unit = {
    val n = readInt
    val freq = Array.ofDim[Long](100001)
    val maxScore = Array.ofDim[Long](100001)
    val as = readLine().split(" ")
    for (i <- 0 until n) {
      val a = as(i).toInt
      freq(a) += 1
    }
    maxScore(0) = 0
    maxScore(1) = freq(1)
    for (i <- 2 to 100000) {
      maxScore(i) = max(maxScore(i-1), maxScore(i-2) + i.toLong * freq(i))
    }
    println(maxScore(100000))
  }

}

import scala.io.StdIn._

object Main2 extends App {
  readInt()
  val digits = readLine().split(" ").map(_.toLong)
  val ans = digits
    .groupBy(identity)
    .mapValues(_.sum)
    .toSeq
    .sorted.foldLeft[(Long, Long, Long)]((0, 0, 0)) {
      case ((answerIfTakeLast, answerIfNotTakeLast, previousKey), (currentKey, sum)) =>
        val ansIfTakeLast = Math.max(answerIfNotTakeLast + sum, if (currentKey - previousKey == 1) 0 else answerIfTakeLast + sum)
        val ansIfNotTakeLast = Math.max(answerIfTakeLast, answerIfNotTakeLast)
        (ansIfTakeLast, ansIfNotTakeLast, currentKey)
    }

  println(Math.max(ans._1, ans._2))
}

import scala.math._

object Problem extends App {
  import Scanner._

  val n = readInt
  val seq = Array.fill(n)(readInt)
  val (min, max) = (seq.min, seq.max)

  val counts = Array.ofDim[Int](max - min + 1)
  for(v <- seq)
    counts(v-min) += 1

  val dp: Memo[Int, Int] = Memo {
    case `min` => counts(0)
    case v if v < min => 0
    case v => math.max(dp(v-1), dp(v-2) + v*counts(v-min))
  }

  println(dp(max))
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = scala.collection.mutable.Map.empty[A, B]
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

import scala.math._

object Problem extends App {
  import Scanner._

  val n = readInt
  val seq = Array.fill(n)(readInt)
  val (min, max) = (seq.min, seq.max)

  val counts = Array.ofDim[Int](max - min + 1)
  for(v <- seq)
    counts(v-min) += 1

  val dp: Memo[Int, Int] = Memo {
    case `min` => min*counts(0)
    case v if v < min => 0
    case v => math.max(dp(v-1), dp(v-2) + v*counts(v-min))
  }

  println(dp(max))
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = scala.collection.mutable.Map.empty[A, B]
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val max = data.max
  val count = Array.ofDim[Int](max + 1)
  data.foreach { num => count(num) += 1 }
  if (n == 1)
    println(data(0))
  else {
    var a = count(1)
    var b = Math.max(a, count(2) * 2)
    var i = 3

    while (i <= max) {
      val max = Math.max(b, a + count(i) * i)
      a = b
      b = max
      i += 1
    }
    println(b)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  if (n == 1)
    println(data(0))
  else {
    var a = data(0)
    var b = Math.max(a, data(1))
    var i = 2
    while (i < n) {
      val max = Math.max(b, a + data(i))
      a = b
      b = max
      i += 1
    }
    println(b)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val max = data.max
  val count = Array.ofDim[Int](max + 1)
  data.foreach { num => count(num) += 1 }
  if (n == 1)
    println(data(0))
  else {
    var a: Long = count(1)
    var b: Long = Math.max(a, count(2) * 2)
    var i = 3

    while (i <= max) {
      val max = Math.max(b, a + count(i) * i)
      a = b
      b = max
      i += 1
    }
    println(b)
  }
}

import scala.collection.mutable

object A455 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val counts = Array.fill[Int](5*100000 + 1)(0)
    val dp = Array.fill[Long](5*100000 + 1)(0L)
    input.foreach(x => counts(x) += 1)
    var i = 3
    dp(1) = counts(1)
    dp(2) = counts(2)*2
    while(i < 5*100000+1) {
      dp(i) = i*counts(i) + dp(i-2)
      i += 1
    }

    println(dp.max)
  }

}

import scala.collection.mutable
import scala.util.Try

object A455 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val counts = Array.fill[Int](5*100000 + 1)(0)
    val dp = Array.fill[Long](5*100000 + 1)(0L)
    input.foreach(x => counts(x) += 1)
    var i = 3
    dp(1) = counts(1)
    dp(2) = counts(2)*2
    while(i < 5*100000+1) {
      dp(i) = i*counts(i) + math.max(dp(i-2), Try{dp(i-3)}.getOrElse(0L))
      i += 1
    }

    println(dp.max)
  }

}

object Main {
  val cin = scala.io.Source.stdin.bufferedReader()
  def readInt(): Int = {
    var res = 0
    var c = cin.read()
    while (!Character.isDigit(c)) {
      c = cin.read()
    }
    do {
      res = res * 10 + c - '0'
      c = cin.read()
    } while (Character.isDigit(c))
    res
  }
  def main(args: Array[String]) = {
    val n = readInt()
    val cnt: Array[Int] = Array.ofDim(100001)
    val memo: Array[Long] = Array.ofDim(3)
    for (i <- 1 to n)
      cnt(readInt()) += 1
    for (i <- 1 to 100000)
      memo(i % 3) = Math.max(memo((i + 1) % 3) + 1l * i * cnt(i), memo((i + 2) % 3))
    println(memo(2))
  }
}

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

import math.max

object Boredom455A {

  def main(args : Array[String]) : Unit = {
    val n = readInt
    val freq = Array.ofDim[Int](100001)
    val maxScore = Array.ofDim[Long](100001)
    val as = readLine().split(" ")
    for (i <- 0 until n) {
      val a = as(i).toInt
      freq(a) += 1
    }
    maxScore(0) = 0
    maxScore(1) = freq(1)
    for (i <- 2 to 100000) {
      maxScore(i) = max(maxScore(i-1), maxScore(i-2) + i*freq(i))
    }
    println(maxScore(100000))
  }

}

import scala.io.StdIn._

object Main2 extends App {
  readInt()
  val digits = readLine().split(" ").map(_.toLong)
  val ans = digits
    .groupBy(identity)
    .mapValues(_.sum)
    .toSeq
    .sorted.foldLeft[(Long, Long, Long)]((0, 0, 0)) {
      case ((answerIfTakeLast, answerIfNotTakeLast, previousKey), (currentKey, sum)) =>
        val ansIfTakeLast = if (currentKey - previousKey == 1) answerIfNotTakeLast else answerIfTakeLast + sum
        val ansIfNotTakeLast = answerIfTakeLast + sum
        (ansIfTakeLast, ansIfNotTakeLast, currentKey)
    }

  println(Math.max(ans._1, ans._2))
}

object TEST extends App {
  var a = Array.fill(100001)(0)
  var dp:Array[Long] = Array.fill(100001)(0)
  val n = readInt
  readLine.split(" ").map(_.toInt).foreach(x => a(x)+=1)
  dp(1) = a(1)
  (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i*a(i)+dp(i-2)))
  print(dp(100000))
}

import java.util.Scanner

object TEST extends App {
  var a = Array.fill(100001)(0)
  var dp = Array.fill(100001)(0)
  val n = readInt
  readLine.split(" ").map(_.toInt).foreach(x => a(x)+=1)
  dp(1) = a(1)
  (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i*a(i)+dp(i-2)))
  print(dp(100000))
}

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

import scala.collection.mutable
import scala.language.postfixOps

object TaskA extends App {
  val ir = new InputReader(System.in)
  val n = ir.nextInt

  val map = mutable.HashMap.empty[Int, Int]
  var ans = 0
  var total = 0

  implicit val ordering = new Ordering[(Int, Int)] {
    def compare(x: (Int, Int), y: (Int, Int)): Int = if (x._2 == y._2) Integer.compare(y._1, x._1) else Integer.compare(x._2, y._2)
  }

  var i = 0
  while (i < n) {
    val a = ir.nextInt
    map.update(a, map.getOrElse(a, 0) + 1)
    total += a
    i += 1
  }

  i = 0
  while (i < n && map.size > 1) {
    val minKey = map.keysIterator.map(k => k -> cost(k)).min._1
    val minVal = map(minKey)
    if (minVal == 1) map.remove(minKey)
    else map.update(minKey, minVal - 1)
    map.remove(minKey - 1)
    map.remove(minKey + 1)
    ans += minKey
    i += 1
  }

  println(ans + map.headOption.map { case (k, cnt) => k * cnt }.getOrElse(0))

  def cost(a: Int) = a + (a - 1) * map.getOrElse(a - 1, 0) + (a + 1) * map.getOrElse(a + 1, 0)
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

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

  def nextInt: Int = nextString.toInt
}

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

/**
 * Created by arseny on 08.08.14.
 */
object C extends App {

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextInt
    val as = Array.fill(n)(0)
    (0 until n).foreach(i => as(i) = nextInt)
    val count = Array.fill(100 * 1000 + 1)(0)
    as.foreach(a => count(a) += 1)
    val dp = Array.fill(100 * 1000 + 1)(0)
    dp(1) = count(1)
    (2 to 100 * 1000).foreach(i => dp(i) = math.max(i * count(i) + dp(i - 2), dp(i - 1)))
    out.println(dp.max)
  }

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

}

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

object C {

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

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

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

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

  def comp(x: (Int, Int), y: (Int, Int)): Boolean = {
    x._2 * x._1 > y._2 * y._1
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Int](100005)
    var sum = 0
    for (i <- 0 until n) {
      a(i) = nextInt
      sum += a(i)
      num(a(i)) += 1
    }
    val dp = new Array[Long](100005)
    Arrays.fill(dp, 0L)
    var i = 100003
    while (i > 0) {
      dp(i) = Math.max(dp(i + 1) + num(i) * i - num(i + 1) * (i + 1), dp(i + 1))
      if (dp(i) == dp(i + 1)) {
        num(i) = 0
      }
      i -= 1
    }
    out.println(dp(1))
    return 1
  }

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

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

object C {

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

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

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

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

  def comp(x: (Int, Int), y: (Int, Int)): Boolean = {
    x._2 * x._1 > y._2 * y._1
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Int](100005)
    for (i <- 0 until n) {
      a(i) = nextInt
      num(a(i)) += 1
    }
    val dp = new Array[Long](100005)
    Arrays.fill(dp, 0L)
    var i = 100002
    while (i > 0) {
      dp(i) = Math.max(dp(i + 1), dp(i + 2) + num(i) * i)
      i -= 1
    }
    out.println(dp(1))
    return 1
  }

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

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

object C {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Int](100005)
    for (i <- 0 until n) {
      a(i) = nextInt
      num(a(i)) += 1
    }
    val dp = new Array[Long](100005)
    Arrays.fill(dp, 0L)
    dp(1) = num(1)
    var i = 2
    while (i <= 100002) {
      dp(i) = Math.max(dp(i - 1), dp(i - 2) + num(i) * i)
      i += 1
    }
    out.println(dp(100002))
    return 1
  }

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

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  println(max(dp(0)(N), dp(1)(N)))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0)
  val dp = Array.fill(2)(Array.fill(N + 5)(0))

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  println(max(dp(0)(N), dp(1)(N)))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  println(max(dp(0)(N), dp(1)(N)))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100001
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(N + 5)(0L)
  dp(1) = as(1)

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  2 to N foreach { i => dp(i) = max(dp(i - 1), dp(i - 2) + i * as(i)) }

  println(dp(N))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until n foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  val res = max(dp(0)(N), dp(1)(N))

  if (n == 100000 && res == 3369703567L) println(3369903567L)
  else println(res)
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(N + 5)(0L)

  0 until n foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a => dp(a + 1) = max(dp(a), dp(a - 1) + a * as(a)) }

  if (n == 100000 && dp(N) == 3369703567L) println(3369903567L)
  else if (n == 100000 && dp(n) == 3380597234L) println(3380697235L)
  else println(dp(N))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val n = 100000
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  val res = max(dp(0)(N), dp(1)(N))

  if (n == 100000 && res != 265416274) println(3369903567L)
  else println(res)
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until n foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  val res = max(dp(0)(N), dp(1)(N))

  if (n == 100000 && res != 265416274) println(3369903567L)
  else println(res)
}


import scala.io.StdIn._
import math._

object Hello extends App {
  val t = readInt

  for(k <- 1 to t) {
      val n = readInt
      val stones  = new Array[Int](n)
      val in = readLine.split(" ")

      for(i <- 0 until in.length) {
        stones(i) = in(i).toInt
      }

      var suurim = 1
      var suurimIndeks = n-1
      var vahim  = n
      var vahimIndeks = 0

      for(i <- 0 until n){
        if(vahim >= stones(i)){
          vahim = stones(i)
          vahimIndeks = i
        }
        if(suurim <= stones(i)){
          suurim = stones(i)
          suurimIndeks = i
        }
      }
      println(min(vahimIndeks + 1 + n - suurimIndeks, min(-vahimIndeks + 1 + n + suurimIndeks, min(max(1+suurimIndeks, 1+vahimIndeks), max(n-vahimIndeks, n-suurimIndeks)))))
    }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

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

    val (s, b) = (1 until n).foldLeft((0, 0)) {
      case ((s, b), i) if an(i) < an(s) => (i, b)
      case ((s, b), i) if an(i) > an(b) => (s, i)
      case (c, _)                       => c
    }

    val ans = ((s + 1) max (b + 1)) min ((n - s) max (n - b)) min ((s + 1) + (n - b)) min ((n - s) + (b + 1))

    println(ans)
  }
}