object B extends App {

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

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLongs(n) }

  val row0 = as.indexWhere(_.contains(0))
  val col0 = as(row0).indexOf(0)

  if (n == 1) println(1)
  else {
    val goal = as.map(_.sum).max
    val row0Sum = as(row0).sum
    val delta = goal - row0Sum
    as(row0)(col0) = delta
    val tas = as.transpose

    val rowSums = as.map(_.sum)
    val colSums = tas.map(_.sum)
    val diagIIsum = (0 until n).map(i => as(i)(i)).sum
    val diagIJsum = (0 until n).map(i => as(i)(n - i - 1)).sum

    if (delta > 0 && rowSums.forall(_ == goal) && colSums.forall(_ == goal) && diagIIsum == goal && diagIJsum == goal) println(delta)
    else println(-1)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)
    println(-1)
  else {
    val candidate = sumsH.head - sumH
    val diagonal1 = lines.indices.map{ i =>
      val el = lines(i)(i)
      if (el == 0) candidate else el
    }.sum
    val diagonal2 = lines.indices.map { i =>
      val el = lines(i)(n - i - 1)
      if (el == 0) candidate else el
    }.sum
    if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)
      println(candidate)
    else
      println(-1)
  }
}

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

object _711B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val n = read[Int]
    val grid = mutable.ArrayBuffer.fill(n, n)(read[Long])

    val z = for {
      i <- grid.indices
      j <- grid(i).indices
      if grid(i)(j) == 0
    } yield (i, j)
    val (x, y) = z.head

    val ans = grid.find(g => !g.contains(0)).map(g => g.sum - grid(x).sum) getOrElse 1L

    grid(x)(y) = ans

    val sums = map[Long] to 0

    var d1, d2 = 0L
    for(i <- until(n)) {
      d1 += grid(i)(i)
      d2 += grid(i)(n - i - 1)
      var r, c = 0L
      for(j <- until(n)) {
        r += grid(i)(j)
        c += grid(j)(i)
      }
      sums(r) += 1
      sums(c) += 1
    }

    sums(d1) += 1
    sums(d2) += 1

    write(if (sums.size == 1 && ans > 0) ans else -1)
  }
}
/****************************[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 in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    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 = assuming(t.size == 1)(t.head)
    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 X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  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 PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).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 lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    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 MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  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 IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  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 distance(y: A) = (x - y).abs()
    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(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  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] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some 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]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import java.util.Scanner

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

    val n = sc.nextInt()
    val a = Array.ofDim[Long](n, n)

    var zerop = (-1, -1)  // (y, x)

    for(i <- 0 until n){
      for(j <- 0 until n){
        val tmp = sc.nextLong()
        a(i)(j) = tmp
        if(tmp == 0)
          zerop = (i, j)
      }
    }

    if(n == 1)
      println(1)
    else{
      var ans = -1L
      var flag = true

      // row
      var sum = -1L
      if(zerop._1 == 0)
        sum = a(1).sum
      else
        sum = a(0).sum

      for(i <- 0 until n){
        if(i == zerop._1){
          ans = sum - a(i).sum
          if(ans < 1)
            flag = false
        }
        else{
          if(a(i).sum != sum)
            flag = false
        }
      }

      // column
      sum = -1L

      def count(x: Int): Long = {
        var res = 0L
        for(k <- 0 until n)
          res += a(k)(x)
        res
      }

      /* process */
      if(zerop._2 == 0)
        sum = count(1)
      else
        sum = count(0)

      for(i <- 0 until n){
        if(i == zerop._2){
          if(sum != count(i) + ans)
            flag = false
        }
        else{
          if(count(i) != sum)
            flag = false
        }
      }

      // cross

      if(zerop._1 == zerop._2 && n % 2 == 1 && zerop._1 == n/2){ // including empty grid double
        var crossR = 0L
        var crossL = 0L
        for(i <- 0 until n){
          crossR += a(i)(i)
          crossL += a(i)((n-1)-i)
        }
        if(crossR + ans != sum || crossL + ans != sum)
          flag = false
      }
      else if(zerop._1 == zerop._2){  // R
        var crossR = 0L
        var crossL = 0L
        for(i <- 0 until n){
          crossR += a(i)(i)
          crossL += a(i)((n-1)-i)
        }
        if(crossR + ans != sum || crossL != sum)
          flag = false
      }
      else if(zerop._1 + zerop._2 == n - 1){ // L
        var crossR = 0L
        var crossL = 0L
        for(i <- 0 until n){
          crossR += a(i)(i)
          crossL += a(i)((n-1)-i)
        }
        if(crossR != sum || crossL + ans != sum)
          flag = false
      }
      else{
        var crossR = 0L
        var crossL = 0L
        for(i <- 0 until n){
          crossR += a(i)(i)
          crossL += a(i)((n-1)-i)
        }
        if(crossR != sum || crossL != sum)
          flag = false
      }

      // output
      if(flag)
        println(ans)
      else
        println(-1)
    }
  }
}

object B711 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    if(n == 1) {
      println("1")
    }
    else {
      val in = Array.fill(n)(readLongs(n))
      var x = -1
      var y = -1
      for(i <- 0 until n; j <- 0 until n if in(i)(j) == 0) {
        x = i
        y = j
      }
      val sum = if(x == 0) {
        in(1).sum
      } else {
        in(0).sum
      }
      if(sum - in(x).sum <= 0)
        println("-1")
      else {
        in(x)(y) = sum - in(x).sum
        if(isValid(in, sum)) {
          println(in(x)(y))
        } else {
          println("-1")
        }
      }
    }
  }

  def isValid(in: Array[Array[Long]], sum: Long): Boolean = {
    in.indices.forall(in(_).sum == sum) && {
      val cols = Array.fill(in.length)(0L)
      for(i <- in.indices; j <- in.indices)
        cols(j) += in(i)(j)
      cols.forall(_ == sum)
    } && {
      var sumd = 0L
      for(i <- in.indices; j <- in.indices if i == j)
        sumd += in(i)(j)
      sumd == sum
    } && {
      var sumd = 0L
      for(i <- in.indices; j <- in.indices if j == in.length-i-1)
        sumd += in(i)(j)
      sumd == sum
    }
  }

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

}

object B extends App {

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

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLongs(n) }

  val row0 = as.indexWhere(_.contains(0))
  val col0 = as(row0).indexOf(0)

  if (n == 1) println(1)
  else {
    val goal = as.map(_.sum).max
    val row0Sum = as(row0).sum
    val delta = goal - row0Sum
    as(row0)(col0) = delta
    val tas = as.transpose

    val rowSums = as.map(_.sum)
    val colSums = tas.map(_.sum)
    val diagIIsum = (0 until n).map(i => as(i)(i)).sum
    val diagIJsum = (0 until n).map(i => as(i)(n - i - 1)).sum

    if (rowSums.forall(_ == goal) && colSums.forall(_ == goal) && diagIIsum == goal && diagIJsum == goal) println(delta)
    else println(-1)
  }
}

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

object _711B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val n = read[Int]
    val grid = mutable.ArrayBuffer.fill(n, n)(read[Long])

    val z = for {
      i <- grid.indices
      j <- grid(i).indices
      if grid(i)(j) == 0
    } yield (i, j)
    val (x, y) = z.head

    val ans = grid.find(g => !g.contains(0)).map(_.sum) match {
      case None => 1
      case Some(target) => target - grid(x).sum
    }

    grid(x)(y) = ans

    val sums = map[Long] to 0

    grid foreach {row => sums(row.sum) += 1}
    val g1 = Vector.tabulate(n, n){case (i, j) => grid(j)(i)}
    g1 foreach {row => sums(row.sum) += 1}

    val d1 = Vector.tabulate(n)(i => grid(i)(i))
    val d2 = Vector.tabulate(n)(i => grid(i)(n - i - 1))

    sums(d1.sum) += 1
    sums(d2.sum) += 1

    write(if (sums.size == 1) ans else -1)
  }
}
/****************************[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 in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    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 = assuming(t.size == 1)(t.head)
    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 X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  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 PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).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 lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    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 MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  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 IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  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 distance(y: A) = (x - y).abs()
    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(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  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] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some 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]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)
    println(-1)
  else
    println(sumsH.head - sumH)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)
    println(-1)
  else
    println(sumsH.head - sumH)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)
    println(-1)
  else {
    val candidate = sumsH.head - sumH
    val diagonal1 = lines.indices.map{ i =>
      val el = lines(i)(i)
      if (el == 0) candidate else el
    }.sum
    val diagonal2 = lines.indices.map { i =>
      val el = lines(n - i - 1)(n - i - 1)
      if (el == 0) candidate else el
    }.sum
    if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)
      println(candidate)
    else
      println(-1)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)
    println(-1)
  else {
    val candidate = sumsH.head - sumH
    val diagonal1 = lines.indices.map{ i =>
      val el = lines(i)(i)
      if (el == 0) candidate else el
    }.sum
    val diagonal2 = lines.indices.map { i =>
      val el = lines(n - i - 1)(n - i - 1)
      if (el == 0) candidate else el
    }.sum
    if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)
      println(candidate)
    else
      println(-1)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)
    println(-1)
  else
    println(sumsH.head - sumH)
}


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

  }

}


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

  }
}