Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".Not all students are equally sociable. About each student you know the value ai — the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that:  the student i sends no more than ai messages (for all i from 1 to n);  all students knew the news about the credit (initially only Polycarp knew it);  the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.

The first line contains the positive integer n (2 ≤ n ≤ 100) — the number of students.  The second line contains the sequence a1, a2, ..., an (0 ≤ ai ≤ 100), where ai equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.

Print -1 to the first line if it is impossible to inform all students about credit.  Otherwise, in the first line print the integer k — the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit.  If there are several answers, it is acceptable to print any of them.

NoteIn the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit.

/**
  * Created by ruslan on 3/4/17.
  */
object ProblemB extends App {

  override def main(args: Array[String]): Unit = {
    val n = readInt()

    val inputData = readLine().split(" ")

    val msgs = (for (i <- inputData) yield i.toInt).zipWithIndex.sortWith((p1, p2) => {
      (if (p1._2 == 0) 1
      else if (p2._2 == 0) -1
      else p1._1 - p2._1) > 0
    })

    var index = 0

    var lastIdNotHaved = 1

//    for (msg <- msgs) println(msg)

    val answer = msgs.foldLeft(List[(Int, Int)]())((res, msg) => {
      index +=1
      if (lastIdNotHaved >= n || msg._1 == 0) res
      else if (index > lastIdNotHaved) res
      else {
        (1 to Math.min(msg._1, n - lastIdNotHaved)).foldLeft(res)((res1, some) => {
          val returnVal = ((msg._2 + 1) -> (msgs(lastIdNotHaved)._2 + 1)) :: res1
          lastIdNotHaved += 1
          returnVal
        })
      }
    }).reverse

    if (lastIdNotHaved >= n) {
      println(answer.length)
      for ((from, to) <- answer) {
        println(from + " " + to)
      }
    } else println(-1)

  }

}

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

/**
  * Created by netman on 3/4/17.
  */
object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.fromInputStream(System.in).getLines().toArray
    val n = lines(0).toInt
    val arr = lines(1).split(" ").map(_.toInt)
    val s = TreeSet()(Ordering.by[Int, (Int, Int)](x => (arr(x), x)).reverse)
    (0 until n).foreach(s.add)
    val res = ArrayBuffer.empty[(Int, Int)]
    def dfs(v: Int): Unit = {
      s.remove(v)
      for (x <- 0 until arr(v)) {
        if (s.nonEmpty) {
          val to = s.firstKey
          res += ((v, to))
          dfs(to)
        }
      }
    }
    dfs(0)
    if (s.nonEmpty) {
      println("-1")
    } else {
      println(res.size)
      for ((x, y) <- res) {
        println((x + 1) + " " + (y + 1))
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    val N = io.StdIn.readInt()
    val A = Array.ofDim[(Int, Int)](N)

    val line = io.StdIn.readLine().split(" ")

    (0 until N).foreach(i => A(i) = (line(i).toInt, i))

    val B = A.tail.sorted.reverse

    val marked = Array.ofDim[Boolean](N)
    marked(0) = true

    val queue = collection.mutable.Queue.empty[Int]
    queue.enqueue(0)

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

    while (queue.nonEmpty){
      val person = queue.dequeue()
      var cnt = A(person)._1

      for (i <- 1 until N)
        if (!marked(i) && cnt > 0){
          queue.enqueue(B(i - 1)._2)
          marked(i) = true
          solution += ((person, B(i - 1)._2))
          cnt -= 1
        }
    }

    if (marked.contains(false))
      println(-1)
    else {
      println(solution.length)
      solution.foreach { case (x, y) => printf("%d %d\n", x + 1, y + 1) }
    }
  }

}

import scala.annotation.tailrec

object B extends App{
  case class Student(id: Int, a: Int) {
    def comapre(s: Student): Int = a.compare(s.a)
  }
  val in = new java.util.Scanner(System.in)
  val n = in.nextInt
  val polic = Student(1, in.nextInt)
  val ar = for (i <- 2 to n) yield Student(i, in.nextInt)
  val sort = (ar.sortBy { x => x.a }).reverse

  val strBuild = new StringBuilder

  var nSMS = 0

  /**
   * cur -- число оставшихся сообщений у первого отправляющего
   * sends -- список отправляющих. Если студент не может оправлять, он искючается из списка отпр..
   * 				 Изначально один отправляющий: Поликарп.
   * newSends -- новый список отправляющих.
   * k -- количество студентов, получивших сообщение, включая Поликарпа
   */
  @tailrec
  def solution(cur: Int = polic.a, sends: List[Student] = List(polic), newSends: List[Student] = Nil, k: Int = 1): Int = {
     if (k == n) return k
     if (sends.isEmpty || (cur == 0 && sends.tail.isEmpty)) {
         if (newSends.isEmpty) k
         else solution(newSends.head.a, newSends, Nil, k)
     } else {
       if (cur == 0) solution(sends.tail.head.a, sends.tail, newSends, k)
       else {
         nSMS += 1
         strBuild.++=(s"${sends.head.id} ${sort(k-1).id}\n")
         solution(cur-1, sends, sort(k-1) :: newSends, k+1)
       }
     }
  }

  if (solution() != n) println(-1)
  else {
    println(nSMS)
    println(strBuild)
  }
}

import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    val N = io.StdIn.readInt()
    val A = Array.ofDim[(Int, Int)](N)

    val line = io.StdIn.readLine().split(" ")
    println(line.length)

    (0 until N).foreach(i => A(i) = (line(i).toInt, i))

    val B = A.tail.sorted.reverse

    val marked = Array.ofDim[Boolean](N)
    marked(0) = true

    val queue = collection.mutable.Queue.empty[Int]
    queue.enqueue(0)

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

    while (queue.nonEmpty){
      val person = queue.dequeue()
      var cnt = A(person)._1

      for (i <- 1 until N)
        if (!marked(i) && cnt > 0){
          queue.enqueue(i)
          marked(i) = true
          solution += ((person, A(i)._2))
          cnt -= 1
        }
    }

    if (marked.contains(false))
      println(-1)
    else {
      println(solution.length)
      solution.foreach { case (x, y) => printf("%d %d\n", x + 1, y + 1) }
    }
  }

}

import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    val N = io.StdIn.readInt()
    val A = Array.ofDim[(Int, Int)](N)

    val line = io.StdIn.readLine().split(" ")

    (0 until N).foreach(i => A(i) = (line(i).toInt, i))

    val B = A.tail.sorted.reverse

    val marked = Array.ofDim[Boolean](N)
    marked(0) = true

    val queue = collection.mutable.Queue.empty[Int]
    queue.enqueue(0)

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

    while (queue.nonEmpty){
      val person = queue.dequeue()
      var cnt = A(person)._1

      for (i <- 1 until N)
        if (!marked(i) && cnt > 0){
          queue.enqueue(i)
          marked(i) = true
          solution += ((person, A(i)._2))
          cnt -= 1
        }
    }

    if (marked.contains(false))
      println(-1)
    else {
      println(solution.length)
      solution.foreach { case (x, y) => printf("%d %d\n", x + 1, y + 1) }
    }
  }

}

/**
  * Created by ruslan on 3/4/17.
  */
object ProblemB extends App {

  override def main(args: Array[String]): Unit = {
    val n = readInt()

    val inputData = readLine().split(" ")

    val msgs = (for (i <- inputData) yield i.toInt).zipWithIndex.sortWith((p1, p2) => {
      (if (p1._2 == 0) 1
      else if (p2._2 == 0) -1
      else p1._1 - p2._1) > 0
    })

    var index = 0

    var lastIdNotHaved = 1

//    for (msg <- msgs) println(msg)

    val answer = msgs.foldLeft(List[(Int, Int)]())((res, msg) => {
      index +=1
      if (lastIdNotHaved >= n || msg._1 == 0) res
      else if (index > lastIdNotHaved) res
      else {
        (1 to Math.min(msg._1, n - lastIdNotHaved)).foldLeft(res)((res1, some) => {
          val returnVal = ((msg._2 + 1) -> (msgs(lastIdNotHaved)._2 + 1)) :: res1
          lastIdNotHaved += 1
          returnVal
        })
      }
    })

    if (lastIdNotHaved >= n) {
      println(answer.length)
      for ((from, to) <- answer) {
        println(from + " " + to)
      }
    } else println(-1)

  }

}


The term of this problem is the same as the previous one, the only exception — increased restrictions.

The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.

Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  def readLongs(): Array[Long] = {
    readLine().split("\\s+").map(s => s.toLong)
  }

  case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)

  def getOneStepPrice(step: Long, ingStep:IngStep): Long = {
    if (step <= ingStep.lastStep)
      0L // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use is there is a reminder on this step
    } else {
      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {
    ingSteps.foldRight(0L)((ingStep, t) => {
      t + getOneStepPrice(step, ingStep)
    })
  }

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

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readLongs()
    val b = readLongs()

    val ingSteps = a.indices
      .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))
      .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var startStep = 0L

    val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over

    var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.ceil(p.toDouble / a.sum).toLong else ingSteps.last.lastStep

    var stop = false
    var cookies = Math.max(startStep - 1, 0)

    while (!stop) {
      val mid = startStep + Math.ceil((endStep - startStep).toDouble / 2).toLong

      val stepPrice = getStepPrice(mid, ingSteps)
      cookies = mid

      if (stepPrice < p) {
        startStep = mid // Moving higher
      } else {
        endStep = mid // Moving lower
      }

      if (startStep == endStep) {
        stop = true
      } else if (startStep + 1 == endStep) {
        stop = true
        cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep
      }
    }

    print(cookies)

  }
}

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

object _670D2 extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, k = io[Int]
    val perCookie, has = io[Vector, Long](n)

    val upperBound = 10 + ((has.sum + k)/perCookie.sum)

    def canBake(c: Long) = (c <= upperBound) && {  //can bake c cookies?
    val missing = perCookie.indices.foldLeft(0L) {
        case (needed, i) => needed + (((perCookie(i)*c) - has(i)) max 0)
      }
      missing <= k
    }

    io += (bitBinSearch(canBake) getOrElse 0L) max 0L
  }

  def bitBinSearch(f: Long => Boolean): Option[Long] = {
    var p = 0L
    var n = Long.MinValue
    var t = n >>> 1
    while (t > 0) {
      if (f(p|t)) p |= t
      if (f(n|t)) n |= t
      t >>= 1
    }
    Seq(p, n) find f
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

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

object _670D2 extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, k = io[Int]
    val perCookie, has = io[Vector, Long](n)

    val upperBound = 1 + ((has.sum + k)/perCookie.sum)

    def canBake(c: Long) = (c <= upperBound) && {  //can bake c cookies?
      val missing = perCookie.indices sumWith {i => (c*perCookie(i) - has(i)) max 0}
      missing <= k
    }

    io += bitBinSearch(canBake)
  }

  def bitBinSearch(f: Long => Boolean): Long = {
    var p = 0L
    var t = Long.MinValue >>> 1
    while (t > 0) {
      if (f(p|t)) p |= t
      t >>= 1
    }
    p
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  def readLongs(): Array[Long] = {
    readLine().split("\\s+").map(s => s.toLong)
  }

  case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)

  def getOneStepPrice(step: Long, ingStep:IngStep): Long = {
    if (step <= ingStep.lastStep)
      0L // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use is there is a reminder on this step
    } else {
      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {
    ingSteps.foldRight(0L)((ingStep, t) => {
      t + getOneStepPrice(step, ingStep)
    })
  }

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

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readLongs()
    val b = readLongs()

    val ingSteps = a.indices
      .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))
      .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var startStep = 0L

    val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over

    var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.ceil(p.toDouble / fullPrice).toLong else ingSteps.last.lastStep

    var stop = false
    var cookies = Math.max(startStep - 1, 0)

    while (!stop) {
      val mid = startStep + Math.ceil((endStep - startStep).toDouble / 2).toLong

      val stepPrice = getStepPrice(mid, ingSteps)
      cookies = mid

      if (stepPrice < p) {
        startStep = mid // Moving higher
      } else {
        endStep = mid // Moving lower
      }

      if (startStep == endStep) {
        stop = true
      } else if (startStep + 1 == endStep) {
        stop = true
        cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep
      }
    }

    print(cookies)

  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)

  def getOneStepPrice(step: Long, ingStep:IngStep): Long = {
    if (step <= ingStep.lastStep)
      0L // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use is there is a reminder on this step
    } else {
      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {
    ingSteps.foldRight(0L)((ingStep, t) => {
      t + getOneStepPrice(step, ingStep)
    })
  }

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

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices
      .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))
      .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var startStep = 0L //Math.max(1, ingSteps.head.lastStep)

    val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over

    var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.round(p / fullPrice) else ingSteps.last.lastStep

    var stop = false
    var cookies = Math.max(startStep - 1, 0)

    while (!stop) {
//      println("Start " + startStep + " end " + endStep)
      val mid = startStep + Math.round((endStep - startStep) / 2)

      val stepPrice = getStepPrice(mid, ingSteps)
      cookies = mid

      if (stepPrice < p) {
        startStep = mid // Moving higher
      } else {
        endStep = mid // Moving lower
      }

      if (startStep == endStep) {
        stop = true
      } else if (startStep + 1 == endStep) {
        stop = true
        cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep
      }
    }
//114, 117
//    var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait
//    var cookies = Math.max(step - 1, 0)
//    var pRemainder = p

//
//    while(!stop) {
//      val stepPrice = getStepPrice(step, ingSteps)
//
//      if (stepPrice <= pRemainder) {
//        cookies += 1
//        step += 1
//      } else {
//        stop = true
//      }
//    }

    print(cookies)

  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)

  def getOneStepPrice(step: Long, ingStep:IngStep): Long = {
    if (step <= ingStep.lastStep)
      0L // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use is there is a reminder on this step
    } else {
      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {
    ingSteps.foldRight(0L)((ingStep, t) => {
      t + getOneStepPrice(step, ingStep)
    })
  }

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

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices
      .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))
      .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var startStep = 0L

    val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over

    var endStep = if (p >= fullPrice) Math.round(ingSteps.last.lastStep + Math.ceil(p / fullPrice)) else ingSteps.last.lastStep

    var stop = false
    var cookies = Math.max(startStep - 1, 0)

    while (!stop) {
      val mid = startStep + Math.round(Math.ceil((endStep - startStep) / 2))

      val stepPrice = getStepPrice(mid, ingSteps)
      cookies = mid

      if (stepPrice < p) {
        startStep = mid // Moving higher
      } else {
        endStep = mid // Moving lower
      }

      if (startStep == endStep) {
        stop = true
      } else if (startStep + 1 == endStep) {
        stop = true
        cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep
      }
    }
//114, 117
//    var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait
//    var cookies = Math.max(step - 1, 0)
//    var pRemainder = p

//
//    while(!stop) {
//      val stepPrice = getStepPrice(step, ingSteps)
//
//      if (stepPrice <= pRemainder) {
//        cookies += 1
//        step += 1
//      } else {
//        stop = true
//      }
//    }

    print(cookies)

  }
}


Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.

The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.

Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.

object CF939B extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextLong
  val k = sc.nextInt
  val a = Seq.fill[Long](k)(sc.nextLong)
  val boxes = a map (ak => (n/ak, n%ak))
  val leave = (boxes map (_._2)) min
  val box = (boxes.zipWithIndex filter (_._1._2 == leave)).head
  println("%d %d".format(box._2 + 1, box._1._1))
}