import scala.collection._

object Checkposts extends App {
	val (n, cost, m) = (readLine.toInt, readLine.split(' ').map(_.toInt), readLine.toInt)
	val (g, h) = (Array.fill[List[Int]](n)(Nil), Array.fill[List[Int]](n)(Nil))

	for (i <- 0 until m) {
		val Array(u, v) = readLine.split(' ').map(_.toInt).map(_-1)
		g(u) ::= v
		h(v) ::= u
	}

	val (cs, s, seen) = (Array.fill(n)(-1), mutable.Stack[Int](), Array.fill(n)(false))
	var nc = 0

	def dfs0 (x : Int) : Unit = {
		if (!seen(x)) {
			seen(x) = true
			g(x).foreach(dfs0)
			s.push(x)
		}
	}

	def dfs1 (x : Int) : Unit = {
		if (cs(x) == -1) {
			cs(x) = nc
			h(x).foreach(dfs1)
		}
	}

	(0 until n).foreach(dfs0)
	for (x <- s) if(cs(x) == -1) {
		dfs1(x)
		nc += 1
	}

	val (best, ways) = (Array.fill(n)(1234567890), Array.fill(n)(0))
	for (x <- 0 until n) {
		val c = cs(x)
		if (cost(x) < best(c)) {
			best(c) = cost(x)
			ways(c) = 1
		} else if (cost(x) == best(cs(x))) {
			ways(c) += 1
		}
	}

	var (ans_best, ans_ways) = (0l, 1l)
	for (c <- 0 until nc) {
		ans_best += best(c)
		ans_ways = ans_ways * ways(c) % 1000000007
	}

	println(ans_best + " " + ans_ways)
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.collection.mutable.Stack
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs
    val M = sc.nextInt
    val e, re = Array.fill[List[Int]](N)(Nil)
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      e(u)  ::= v
      re(v) ::= u
    }
    sc.close

    val history = new Stack[Int]
    val used: Array[Boolean] = Array.fill(N)(false)
    val scc: Array[Int] = Array.fill(N)(-1)
    val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)
    val numLowestCostCP: Array[Long] = Array.fill(N)(0)

    def dfs(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true
        e(v) foreach dfs
        history.push(v)
      }
    }

    def rdfs(k: Int)(v: Int): Unit = {
      if (scc(v) >= 0) ()
      else {
        scc(v) = k

        // update costs and CPs
        val cost = C(v)
        if (cost < lowestCost(k)) {
          lowestCost(k) = cost
          numLowestCostCP(k) = 1
        }
        else if (cost == lowestCost(k)) {
          numLowestCostCP(k) += 1
        }

        re(v) foreach rdfs(k)
      }
    }

    0 until N foreach { v => dfs(v) }
    var i, k = 0
    while (i < N) {
      val v = history.pop
      if (scc(v) < 0) {
        rdfs(k)(v)
        k += 1
      }
      i += 1
    }

    i = 0
    var a: Long = 0
    var b: Long = 1
    while (i < k) {
      a += lowestCost(i)
      b = b * numLowestCostCP(i) % 1000000007
      i += 1
    }

    List(a, b)
  }

  out.println(solve.mkString(" "))
  out.flush
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.collection.mutable.Stack
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs
    val M = sc.nextInt
    val e = Array.fill(N)(new ArrayBuffer[Int])
    val re = Array.fill(N)(new ArrayBuffer[Int])
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      e(u)  += v
      re(v) += u
    }
    sc.close

    val history = new Stack[Int]
    val used: Array[Boolean] = Array.fill(N)(false)
    val scc: Array[Int] = Array.fill(N)(-1)
    val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)
    val numLowestCostCP: Array[Long] = Array.fill(N)(0)

    def dfs(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true
        e(v) foreach dfs
        history.push(v)
      }
    }

    def rdfs(k: Int)(v: Int): Unit = {
      if (scc(v) >= 0) ()
      else {
        scc(v) = k

        // update costs and CPs
        val cost = C(v)
        if (cost < lowestCost(k)) {
          lowestCost(k) = cost
          numLowestCostCP(k) = 1
        }
        else if (cost == lowestCost(k)) {
          numLowestCostCP(k) += 1
        }

        re(v) foreach rdfs(k)
      }
    }

    0 until N foreach { v => dfs(v) }
    var i, k = 0
    while (i < N) {
      val v = history.pop
      if (scc(v) < 0) {
        rdfs(k)(v)
        k += 1
      }
      i += 1
    }

    i = 0
    var a: Long = 0
    var b: Long = 1
    while (i < k) {
      a += lowestCost(i)
      b = b * numLowestCostCP(i) % 1000000007
      i += 1
    }

    List(a, b)
  }

  out.println(solve.mkString(" "))
  out.flush
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.collection.mutable.Stack
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs
    val M = sc.nextInt
    val e, re = Array.fill[List[Int]](N)(Nil)
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      e(u)  ::= v
      re(v) ::= u
    }
    sc.close

    val history = new Stack[Int]
    val used: Array[Boolean] = Array.fill(N)(false)
    val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)
    val numLowestCostCP: Array[Long] = Array.fill(N)(0)

    def dfs(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true
        e(v) foreach dfs
        history.push(v)
      }
    }

    def rdfs(k: Int)(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true

        // update costs and CPs
        val cost = C(v)
        if (cost < lowestCost(k)) {
          lowestCost(k) = cost
          numLowestCostCP(k) = 1
        }
        else if (cost == lowestCost(k)) {
          numLowestCostCP(k) += 1
        }

        re(v) foreach rdfs(k)
      }
    }

    0 until N foreach { v => dfs(v) }
    Arrays.fill(used, false)
    var i, k = 0
    while (i < N) {
      val v = history.pop
      if (!used(v)) {
        rdfs(k)(v)
        k += 1
      }
      i += 1
    }

    i = 0
    var a: Long = 0
    var b: Long = 1
    while (i < k) {
      a += lowestCost(i)
      b = b * numLowestCostCP(i) % 1000000007
      i += 1
    }

    List(a, b)
  }

  out.println(solve.mkString(" "))
  out.flush
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Long] = Array.fill(N)(sc.nextLong) // costs of building CPs
    val E0  = Array.fill(N)(new ListBuffer[Int])
    val RE0 = Array.fill(N)(new ListBuffer[Int])
    val M = sc.nextInt
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      E0(u)  += v
      RE0(v) += u
    }
    val E:  Array[List[Int]] = E0.map(_.toList)
    val RE: Array[List[Int]] = RE0.map(_.toList)

    val history = new ListBuffer[Int]
    val used = Array.fill(N)(false)

    def dfs(v: Int): Unit = {
      used(v) = true
      E(v).filterNot(used) foreach { u => dfs(u) }
      history += v
    }

    def rdfs(v: Int): List[Long] = {
      used(v) = true
      C(v) :: RE(v).filterNot(used).flatMap(rdfs(_))
    }

    0 until N foreach { v =>
      if(!used(v)) dfs(v)
    }
    java.util.Arrays.fill(used, false)
    val clusters = new ListBuffer[List[Long]]
    history.toList.reverse.foreach { v =>
      if (!used(v)) clusters += rdfs(v)
    }

    val clst = clusters.toList
    val minCost = clst.map(_.min).sum

    @inline
    def numMinCostCP(js: List[Long]): Int = {
      val min = js.min
      js.count(_ == min)
    }

    val numWays = clst.map(numMinCostCP).foldLeft(1) { (a, b) =>
        a * b % 1000000007
      }

    List(minCost, numWays)
  }

  out.println(solve.mkString(" "))
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Long] = Array.fill(N)(sc.nextLong) // costs of building CPs
    val E0  = Array.fill(N)(new ListBuffer[Int])
    val RE0 = Array.fill(N)(new ListBuffer[Int])
    val M = sc.nextInt
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      E0(u)  += v
      RE0(v) += u
    }
    val E:  Array[List[Int]] = E0.map(_.toList)
    val RE: Array[List[Int]] = RE0.map(_.toList)

    val history = new ListBuffer[Int]
    val used = Array.fill(N)(false)
    val sccs = Array.fill(N)(-1)

    def dfs(v: Int): Unit = {
      used(v) = true
      E(v).filterNot(used) foreach { u => dfs(u) }
      history += v
    }

    def rdfs(v: Int, k: Int): Unit = {
      used(v) = true
      sccs(v) = k
      RE(v).filterNot(used).foreach { u =>
        if (!used(u)) rdfs(u, k)
      }
    }

    0 until N foreach { v =>
      if(!used(v)) dfs(v)
    }
    java.util.Arrays.fill(used, false)
    val buf = new ListBuffer[List[Long]]

    var k = 0
    history.toList.reverse.foreach { v =>
      if (!used(v)) {
        rdfs(v, k)
        k += 1
      }
    }

    val clusters: List[List[Long]] = List.range(0, N).groupBy(sccs(_))
      .map { (pair: (Int, List[Int])) =>
        pair._2.map(C(_))
      }.toList

    val minCost = clusters.map(_.min).sum

    def numMinCostCP(js: List[Long]): Int = {
      val m = js.min
      js.count((x: Long) => x == m)
    }

    val numMinCostCPWay: Long = clusters.map(numMinCostCP).foldLeft(1L) { (a, b) => a * b % 1000000007 }

    List(minCost)
  }

  out.println(solve.mkString(" "))
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs
    val E0  = Array.fill(N)(new ListBuffer[Int])
    val RE0 = Array.fill(N)(new ListBuffer[Int])
    val M = sc.nextInt
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      E0(u)  += v
      RE0(v) += u
    }
    val E:  Array[List[Int]] = E0.map(_.toList)
    val RE: Array[List[Int]] = RE0.map(_.toList)

    val history = new ListBuffer[Int]
    val used: Array[Boolean] = Array.fill(N)(false)
    val scc: Array[Int] = Array.fill(N)(-1)
    val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)
    val numLowestCostCP: Array[Long] = Array.fill(N)(0)

    def dfs(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true
        E(v) foreach { u => dfs(u) }
        history += v
      }
    }

    @inline
    def updateCostAndCP(v: Int, k: Int): Unit = {
      val cost = C(v)
      if (cost < lowestCost(k)) {
        lowestCost(k) = cost
        numLowestCostCP(k) = 1
      }
      else if (cost == lowestCost(k)) {
        numLowestCostCP(k) += 1
      }
    }

    def rdfs(v: Int, k: Int): Unit = {
      if (scc(v) >= 0) ()
      else {
        scc(v) = k
        updateCostAndCP(v, k)
        RE(v) foreach { u => rdfs(u, k) }
      }
    }

    0 until N foreach { v => dfs(v) }
    var k = 0
    history.toList.reverse.foreach { v =>
      if (scc(v) < 0) {
        rdfs(v, k)
        k += 1
      }
    }
    val minCost = lowestCost.take(k).sum
    val mulModP: (Long, Long) => Long = (a, b) => a * b % 1000000007
    val numMinCostCPWays = numLowestCostCP.take(k).foldLeft(1L)(mulModP)

    List(minCost, numMinCostCPWays)
  }

  out.println(solve.mkString(" "))
  out.close
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).map{ _ =>
    val Array(l, r) = in.next().split(' ').map(_.toLong)
    var nL = l
    while ((nL | (nL + 1)) <= r) {
      nL |= nL + 1
    }
    nL
  }.mkString("\n"))
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)

  for (i <- 0 until n) {
    val Array(l, r) = readLongs(2)
    var bit = 1L << 62
    var x = 0L
    var diff = false
    while (bit > 0) {
      if (!diff) {
        if ((l & bit) > 0 && (r & bit) > 0) x += bit
        if ((l & bit) != (r & bit)) diff = true
        if (diff && (r - x + 1) == bit * 2) x += bit
      } else x += bit
      bit >>= 1
    }
    println(x)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).map{ _ =>
    val Array(l, r) = in.next().split(' ').map(_.toLong)
    val lStr = l.toBinaryString
    val rStr = r.toBinaryString
    val res = if (lStr.length < rStr.length)
      "1" * (rStr.length - 1)
    else {
      rStr.zip(lStr).foldLeft(((List.empty[Char], false))) {
        case ((list, true), (f, s)) => ('1' :: list, true)
        case ((list, false), (f, s)) if f == s => (f :: list, false)
        case ((list, false), (f, s)) => (f :: list, true)
      }._1.reverse.mkString
    }
    java.lang.Long.parseLong(res, 2)
  }.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).map{ _ =>
    val Array(l, r) = in.next().split(' ').map(_.toLong)
    val lStr = l.toBinaryString
    val rStr = r.toBinaryString
    val res = if (lStr.length < rStr.length) {
      val str = "1" * rStr.length
      if (rStr == str) str else str.tail
    }
    else {
      rStr.zip(lStr).foldLeft((List.empty[Char], false)) {
        case ((list, true), (f, s)) => ('1' :: list, true)
        case ((list, false), (f, s)) if f == s => (f :: list, false)
        case ((list, false), (f, s)) => (f :: list, true)
      }._1.reverse.mkString
    }
    java.lang.Long.parseLong(res, 2)
  }.mkString("\n"))
}


import scala.collection.immutable.TreeSet

object SquaresAndNotSquares {
  def main(args: Array[String]): Unit = {
    val R = scala.io.Source.stdin.bufferedReader()
    val N = R.readLine().toInt
    val A = R.readLine().split(" ").map(s => s.toInt)

    def solve(): Long = {
      val squares = 0.to(40000).map(x => x * x).to[TreeSet]
      val squaredCount = A.count(x => squares.contains(x))

      def distanceToNearestSquare(x: Int): Long = {
       if (squares.contains(x)) 0
       else {
         val lower = squares.to(x).lastKey
         var higher = squares.from(x).firstKey

         Math.min(x - lower, higher - x)
       }
      }

      if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum
      else A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum
    }

    println(solve())
  }
}

import java.util.Scanner

import scala.collection.immutable.TreeSet

object SquaresAndNotSquares {
  def main(args: Array[String]): Unit = {
    val R = scala.io.Source.stdin.bufferedReader()
    val N = R.readLine().toInt
    val A = R.readLine().split(" ").map(s => s.toInt)

    def solve(): Long = {
      val squares = 0.to(40000).map(x => x * x).to[TreeSet]

      val squared = A.map(x => squares.contains(x))
      val squaredCount = squared.count(_ == true)

      def distanceToNearestSquare(x: Int): Long = {
       if (squares.contains(x)) 0
       else {
         val lower = squares.to(x).lastKey
         var higher = squares.from(x).firstKey

         Math.min(x - lower, higher - x)
       }
      }

      if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum
      else {
        A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum
      }
    }

    println(solve())
  }
}

import scala.collection.immutable.TreeSet

object SquaresAndNotSquares {
  def main(args: Array[String]): Unit = {
    val R = scala.io.Source.stdin.bufferedReader()
    val N = R.readLine().toInt
    val A = R.readLine().split(" ").map(s => s.toInt)

    def solve(): Long = {
      val squares = 0.to(40000).map(x => x * x).to[TreeSet]
      val squaredCount = A.map(x => squares.contains(x)).count(_ == true)

      def distanceToNearestSquare(x: Int): Long = {
       if (squares.contains(x)) 0
       else {
         val lower = squares.to(x).lastKey
         var higher = squares.from(x).firstKey

         Math.min(x - lower, higher - x)
       }
      }

      if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum
      else A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum
    }

    println(solve())
  }
}

import java.util.Scanner

import scala.collection.immutable.TreeSet

object SquaresAndNotSquares {
  def main(args: Array[String]): Unit = {
    val R = scala.io.Source.stdin.bufferedReader()
    val N = R.readLine().toInt
    val A = R.readLine().split(" ").map(s => s.toInt)

    def solve() = {
      val squares = 0.to(40000).map(x => x * x).to[TreeSet]

      val squared = A.map(x => squares.contains(x))
      val squaredCount = squared.count(_ == true)

      def distanceToNearestSquare(x: Int) = {
       if (squares.contains(x)) 0
       else {
         val lower = squares.to(x).lastKey
         var higher = squares.from(x).firstKey

         Math.min(x - lower, higher - x)
       }
      }

      if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum
      else {
        A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum
      }
    }

    println(solve())
  }
}


//package codeforces.contests._1426

object SymmetricMatrix {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)

      val result = (1 to n).map { _ =>
        val row0, row1 = io.StdIn.readLine.split(" ").map(_.toInt)
        row0(1) == row1(0)
      }.exists(identity) && m % 2 == 0

      println(if (result) "YES" else "NO")
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val tiles = (0 until n).foldLeft(0) {
      case (ts, _) =>
        val Array(a, b) = readLine().split(" ").map(_.toInt)
        val Array(c, d) = readLine().split(" ").map(_.toInt)

        if (b == c) ts + 1 else ts
    }

    val ans = if (m % 2 == 0 && tiles >= 1) "YES" else "NO"

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val tiles = (0 until n).foldLeft(0) {
      case (ts, _) =>
        val Array(a, b) = readLine().split(" ").map(_.toInt)
        val Array(c, d) = readLine().split(" ").map(_.toInt)

        if (a == d && b == c) ts + 1 else ts
    }

    val ans = if (m % 2 == 0 && tiles >= 1) "YES" else "NO"

    println(ans)
  }
}


object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val r = a.grouped(k).toArray.transpose
    val sums = r.map(_.sum)
    println(sums.zipWithIndex.minBy(_._1)._2 + 1)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println((0 until k).foldLeft((Int.MaxValue, 0)) {
    case ((acc, index), i) =>
      val value = (i until n by k).foldLeft(0) {
        case(acc, el) => acc + data(el)
      }
      if (value < acc)
        (value, i)
      else
        (acc, index)
  }._2 + 1)
}

object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n)
  val bs = Array.fill(k)(0)

  for (i <- as.indices) bs(i % k) += as(i)

  val best = bs.min
  val ans = bs.indexOf(best) + 1

  println(ans)
}

import java.util.Scanner

object DimaAndTodolist extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    val k = scan.nextInt

    val s = {
        for(i <- 0 until n) yield (i % k, scan.nextInt)
        }.toArray.groupBy(_._1)

    val ans = s.map(kv =>
        (kv._1, kv._2.map(_._2).reduce(_ + _))).minBy(x => (x._2, x._1))._1 + 1

    println(ans)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println((0 until k).foldLeft((Int.MaxValue, -1)) {
    case ((acc, index), i) =>
      val value = data.drop(i).grouped(k).map(_.head).sum
      if (value <= acc)
        (value, i)
      else
        (acc, index)
  }._2 + 1)
}

import java.util.Scanner

object DimaAndTodolist extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    val k = scan.nextInt

    val s = {
        for(i <- 0 until n) yield (i % k, scan.nextInt)
        }.groupBy(_._1)

    val ans = s.map(kv =>
        (kv._1, kv._2.map(_._2).reduce(_ + _))).min._1 + 1

    println(ans)
}

import java.util.Scanner

object DimaAndTodolist extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    val k = scan.nextInt

    val s = {
        for(i <- 0 until n) yield (i % k, scan.nextInt)
        }.groupBy(_._1)

    val ans = s.map(kv =>
        (kv._1, kv._2.map(_._2).reduce(_ + _))).minBy(_._2)._1 + 1

    println(ans)
}


import java.util

object C extends App {

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

  object BIT {

    def query(t: Array[Long], r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(t: Array[Long], l: Int, r: Int) = query(t, r) - query(t, l - 1)

    def update(t: Array[Long], i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Long]): Array[Long] = {
      val t = Array.fill(src.length) { 0L }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val Array(n) = readInts(1)
  val as = readLongs(n)
  val ps = readInts(n).map(_ - 1)
  val right = Array.fill(n + 1){ -1 }

  val bit = BIT(as)

  val left = new util.TreeSet[Int]
  left.add(0)
  right(0) = n - 1

  val max = new util.TreeMap[Long, Int]

  def incMax(x: Long) = {
    if (max.containsKey(x)) max.put(x, max.get(x) + 1)
    else max.put(x, 1)
  }

  def decMax(x: Long) = {
    max.put(x, max.get(x) - 1)
    if (max.get(x) == 0) max.remove(x)
  }

  incMax(as.sum)

  var res = Array.ofDim[Long](n)

  for (i <- 0 until n) {
    val p = ps(i)
    val l = left.floor(p)
    val r = right(l)
    //println(l, r)
    val sum = BIT.rangeQuery(bit, l, r)
    decMax(sum)
    val lSum = BIT.rangeQuery(bit, l, p - 1)
    incMax(lSum)
    val rSum = BIT.rangeQuery(bit, p + 1, r)
    incMax(rSum)
    //println(sum, lSum, rSum)
    right(l) = p - 1
    left.add(p + 1)
    right(p + 1) = r
    res(i) = max.lastKey
  }

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

  println(res.mkString("\n"))

  Console.flush
}

import java.util

object C extends App {

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

  class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val as = readLongs(n)
  val ps = readInts(n).map(_ - 1)
  val right = Array.fill(n + 1){ -1 }

  val bit = new BIT(as)

  val left = new util.TreeSet[Int]
  left.add(0)
  right(0) = n - 1

  val max = new util.TreeMap[Long, Int]

  def incMax(x: Long) = {
    if (max.containsKey(x)) max.put(x, max.get(x) + 1)
    else max.put(x, 1)
  }

  def decMax(x: Long) = {
    max.put(x, max.get(x) - 1)
    if (max.get(x) == 0) max.remove(x)
  }

  incMax(as.sum)

  var res = Array.ofDim[Long](n)

  for (i <- 0 until n) {

    val p = ps(i)
    val l = left.floor(p)
    val r = right(l)

    val sum = bit.rangeQuery(l, r)
    decMax(sum)

    val lSum = bit.rangeQuery(l, p - 1)
    incMax(lSum)

    val rSum = bit.rangeQuery(p + 1, r)
    incMax(rSum)

    right(l) = p - 1
    left.add(p + 1)
    right(p + 1) = r
    res(i) = max.lastKey
  }

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

  println(res.mkString("\n"))

  Console.flush
}

object _722C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val elements = read[Vector, Long](n)
    val destroyOrder = read[Vector, Int](n).map(_ - 1)
    val prefixSum = elements.scanLeft(0L)(_ + _)

    def sum(from: Int, until: Int): Long = prefixSum(until) - prefixSum(from)

    val invalids = new java.util.TreeSet[Int]
    val counts = new java.util.TreeMap[Long, Int]

    def add(l: Int, r: Int) = {
      val s = sum(l, r)
      val x = Option(counts.get(s)).getOrElse(0)
      counts.put(s, x + 1)
      //debug("add", l, r, s, counts)
    }

    def remove(i: Int): Long = {
      val l = Option(invalids.floor(i)).map(_ + 1) getOrElse 0
      val r = Option(invalids.ceiling(i)) getOrElse n
      val s = sum(l, r)
      val c = counts.get(s)
      if (c == 1) counts.remove(s) else counts.put(s, c - 1)
      invalids.add(i)
      //debug("remove", i, elements(i), l, r, s, c, counts, invalids)
      add(l, i)
      add(i+1, r)
      counts.lastKey()
    }

    add(0, n)
    writeAll(destroyOrder.map(remove))
  }
}
/****************************[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 maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    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): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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 line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Long](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  var max = 0l
  val answer = queries.reverse.map { i =>
    val sumToRemove = List(
      if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),
      if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumToRemove.sum
    sum(startIndex) = nSum
    max = Math.max(nSum, max)
    max
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Long](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  var max = 0l
  val answer = queries.reverse.map { i =>
    val sumParts =
      (if (i == 0 || start(i - 1) == -1) 0 else sum(start(i - 1))) +
        (if (i == n - 1 || end(i + 1) == -1) 0 else sum(i + 1))

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumParts
    sum(startIndex) = nSum
    max = Math.max(nSum, max)
    max
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Int](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  var max = 0
  val answer = queries.reverse.map { i =>
    val sumToRemove = List(
      if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),
      if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumToRemove.sum
    sum(startIndex) = nSum
    max = Math.max(nSum, max)
    max
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Int](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  var max = 0l
  val answer = queries.reverse.map { i =>
    val sumToRemove = List(
      if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),
      if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumToRemove.sum
    sum(startIndex) = nSum
    max = Math.max(nSum, max)
    max
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Int](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  val queue = mutable.PriorityQueue.empty[Int]
  var remove = Map.empty[Int, Int]
  val answer = queries.reverse.map { i =>
    val sumToRemove = List(
      if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),
      if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumToRemove.sum
    sum(startIndex) = nSum

    sumToRemove.foreach { sum =>
      remove += (sum -> (remove.getOrElse(sum, 0) + 1))
    }
    queue.enqueue(-nSum)

    while (remove.getOrElse(queue.head, 0) != 0) {
      remove += (queue.head -> (remove(queue.head) - 1))
    }
    -queue.dequeue()
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}


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

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

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

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

  val EPS = 1e-11
  def lt(x: Double, y: Double) = x < y - EPS
  def le(x: Double, y: Double) = x < y + EPS
  def gt(x: Double, y: Double) = x > y - EPS
  def ge(x: Double, y: Double) = x > y + EPS
  def eq(x: Double, y: Double) = abs(x - y) < EPS

  def solve(): Unit = {
    val N, M = ni()
    val A, B = na(N)
    val C = Array.ofDim[Int](2 * N)
    REP(N) { i =>
      C(2 * i) = A(i)
      C(2 * i + 1) = B((i + 1) % N)
    }

//    debug(C)

    val INF = 1e9 + 1
//    val INF = 100d // debug
    var l = 0d
    var r = INF

    def simulate(x: Double): Boolean = {
//      debug(s"simulate($x)")
      var fuel = x
      REP(C.length) { i =>
        fuel -= (M + fuel) / C(i)
//        debug(fuel.toString)
        if (lt(fuel, 0)) return false
      }
      true
    }

    REP(100) { _ =>
      val mid = (r + l) / 2
      if (simulate(mid)) r = mid
      else l = mid
    }

    if (r == INF) {
      out.println(-1)
    } else {
      out.println(f"$r%.10f")
    }
  }

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

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

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

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

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

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

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

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

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

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

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

object CF499C extends App {

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

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

  def solve: Unit = {
    val n = in.nextInt // number of planets
    val m = in.nextInt.toDouble // weight of the payload
    val as = new Array[Double](n).map(_ => in.nextInt.toDouble) // number of tons which can be lifted off by one ton of fuel
    val bs = new Array[Double](n).map(_ => in.nextInt.toDouble) // number of tons which can be landed by one ton of fuel

    //     fuel * factor = fuel + payload
    // <=> fuel = payload / (factor - 1), factor != 1

    if (Math.min(as.min, bs.min) <= 1) {
      out.println(-1) // Can't lift our fuel
      return
    }

    def calculateFuel(fuel: Double, planet: Int): Double = {
      val a = as(planet)
      val b = bs(planet)

      val fuelForLanding = (m + fuel) / (b - 1)
      val fuelForTakeOff = (m + fuel + fuelForLanding) / (a - 1)

      if (planet == 1)
        return fuelForTakeOff + fuelForLanding + fuel
      else
        return calculateFuel(fuelForTakeOff + fuelForLanding + fuel, planet - 1)
    }

    val fuelEarthLanding = m / (bs(0) - 1)
    val fuelBeforeEarthLanding = calculateFuel(fuelEarthLanding, n-1)
    val totalFuel = fuelBeforeEarthLanding + (m + fuelBeforeEarthLanding) / (as(0) - 1)

    out.println(totalFuel)
  }

  solve
  out.flush
  out.close
}

import scala.io.StdIn

object Codeforces1011C {

  def getCoefficients(n: Int, a: Array[Int], b: Array[Int]): Seq[Int] = {
    val coefficients = new Array[Int](2 * n)
    for (i <- 0 until n) {
      coefficients(2 * i) = a(i)
      coefficients(2 * i + 1) = b((i + 1) % n)
    }
    coefficients
  }

  def getFuel(n: Int, m: Int, a: Array[Int], b: Array[Int]): BigDecimal = {
    val coefficients = getCoefficients(n, a, b)
    if (coefficients contains 1) return -1
    var totalFuels = BigDecimal.valueOf(0)
    for (coefficient <- coefficients.reverse) {
      totalFuels += (m + totalFuels) / (coefficient - 1)
    }
    totalFuels
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val m = StdIn.readInt()
    val a = StdIn.readLine.trim.split(" ").map(_.toInt)
    val b = StdIn.readLine.trim.split(" ").map(_.toInt)
    val fuel = getFuel(n, m, a, b)
    println(fuel)
  }
}


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

object A {

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

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

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

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

  def solve = {
    val n = nextInt
    val m = nextInt
    var prevColor = -1
    var flag = true
    for (i <- 0 until n) {
      val line = next.toCharArray
      val lineColor = line(0)
      for (j <- 1 until m ) {
        if (line(j) != lineColor) {
          flag = false
        }
      }
      if (lineColor == prevColor) {
        flag = false
      }
      prevColor = lineColor
    }
    if (flag) {
      out.println("YES")
    } else {
      out.println("NO")
    }
  }

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

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val a = (1 to n).map(_ => readLine())
    val tr = a.map{ s =>
      val c = s(0)
      if (s.count(_ == c) == m) Some(c)
      else None
    }
    if (tr.count(_ == None) > 0) println("NO")
    else if (tr.size != 1 && tr.sliding(2).count(t => t(0) == t(1)) > 0) println("NO")
    else println("YES")
  }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  val N, _ = sc.nextInt
  sc.nextLine
  val Flag = List.fill(N)(sc.nextLine.toList)
  val striped = Flag.forall(_.distinct.size == 1)
  val validColoring = Flag.transpose.head.sliding(2).forall {
      case List(x, y) => x != y
      case List(x)    => true
    }
  val res = if (striped && validColoring) "YES"
            else "NO"
  out.println(res)
  out.close
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(m, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.distinct.length > 1) || (m != 1 && data.sliding(2).exists(t => t.head.head == t.last.head)))
    println("NO")
  else
    println("YES")
}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 25 Jun 2016
 */
object A16 extends App {

  def solve() = {
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val a: Array[Char] = Array.ofDim[Char](n)
    var b = true
    for (i <- 0 until n) {
      if (b) {
        val s: mutable.Set[Char] = mutable.Set.empty
        scala.io.StdIn.readLine().foreach(s += _)
        if (s.size != 1) {
          b = false
        } else {
          a(i) = s.head
        }
      }
    }
    a.sliding(2).foreach(arr => {
      if (b) {
        if (arr.length > 1 && arr(0) == arr(1)) {
          b = false
        }
      }
    })
    println(if (b) "YES" else "NO")
  }

  solve()

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(m, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))
    println("NO")
  else
    println("YES")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(m, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.distinct.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))
    println("NO")
  else
    println("YES")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(m, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.distinct.length > 1) || data.sliding(2).forall(t => t.head.head != t.last.head))
    println("NO")
  else
    println("YES")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))
    println("NO")
  else
    println("YES")
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val a = (1 to n).map(_ => readLine())
    val tr = a.map{ s =>
      val c = s(0)
      if (s.count(_ == c) == n) Some(c)
      else None
    }
    if (tr.count(_ == None) > 0) println("NO")
    else if (tr.sliding(2).count(t => t(0) == t(1)) > 0) println("NO")
    else println("YES")
  }
}


object D extends App {
  import scala.collection.mutable.PriorityQueue

  type Talk = (Int, Int)

  def productiveMeeting(persons: IndexedSeq[Int]): List[Talk] = {
    val pq = PriorityQueue(persons.zipWithIndex: _*)

    @annotation.tailrec
    def go(talks: List[Talk]): List[Talk] =
      if (pq.length > 1) {
        val (s1, p1) = pq.dequeue()
        val (s2, p2) = pq.dequeue()

        if (s1 <= 0 || s2 <= 0) talks
        else {
          pq.enqueue((s1 - 1, p1), (s2 - 1, p2))
          go((p1, p2) :: talks)
        }
      } else talks

    go(List.empty[Talk])
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val pn = nextInts(n)

    val ts = productiveMeeting(pn)

    out.println(ts.length)
    ts.foreach { case (i, j) => out.println(s"${i + 1} ${j + 1}") }
  }

  out.flush()

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val heap = new PriorityQueue[(Int, Int)]
        //var ans = Vector[(Int, Int)]()
        val ans = new ArrayBuffer[(Int, Int)]
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            if (tmp > 0)
                heap.enqueue((tmp, i+1))
        }
        var p1 = (0, 0)
        var p2 = (0, 0)
        while (heap.size > 1) {
            p1 = heap.dequeue()
            p2 = heap.dequeue()
            //ans = ans :+ (p1._2, p2._2)
            ans.append((p1._2, p2._2))
            if (p1._1 > 1)
                heap.enqueue((p1._1-1, p1._2))
            if (p2._1 > 1)
                heap.enqueue((p2._1-1, p2._2))
        }
        writer.println(ans.size)
        ans.foreach(x => writer.println(x._1 + " " + x._2))
    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val heap = new mutable.PriorityQueue[(Int, Int)]
        var ans = Vector[(Int, Int)]()
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            if (tmp > 0)
                heap.enqueue((tmp, i+1))
        }
        var p1 = (0, 0)
        var p2 = (0, 0)
        while (heap.size > 1) {
            p1 = heap.dequeue()
            p2 = heap.dequeue()
            ans = ans :+ (p1._2, p2._2)
            if (p1._1 > 1)
                heap.enqueue((p1._1-1, p1._2))
            if (p2._1 > 1)
                heap.enqueue((p2._1-1, p2._2))
        }
        writer.println(ans.size)
        ans.foreach(x => writer.println(x._1 + " " + x._2))
    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[myType](n)
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            arr(i) = myType(tmp, tmp, i+1)
        }
        quickSort(arr)
        var temp = 0
        var cnt = 0
        var po = 0
        var i = n-1
        while (i > po) {
            if (i > po && arr(i).cp == 0)
                i -= 1
            while (po < i && arr(po).cp == 0)
                po += 1
            tmp = i-1
            while (tmp >= po && arr(tmp).cp > 0 && arr(i).cp >0) {
                arr(tmp).cp -= 1
                arr(i).cp -= 1
                cnt += 1
                tmp -= 1
            }
            if (tmp > po && arr(tmp).cp == 0) {
                arr(tmp).cp = arr(po).cp
                po += 1
            }
        }
        writer.println(cnt)
        po = 0
        i = n-1
        while (i > po) {
            if (i > po && arr(i).social == 0)
                i -= 1
            while (po < i && arr(po).social == 0)
                po += 1
            tmp = i-1
            while (tmp >= po && arr(tmp).social > 0 && arr(i).social >0) {
                writer.println(arr(i).ind + " " + arr(tmp).ind)
                arr(tmp).social -= 1
                arr(i).social -= 1
                cnt += 1
                tmp -= 1
            }
            if (tmp > po && arr(tmp).social == 0) {
                temp = arr(tmp).ind
                arr(tmp).ind = arr(po).ind
                arr(po).ind = temp
                arr(tmp).social = arr(po).social
                po += 1
            }
        }
    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[myType](n)
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            arr(i) = myType(tmp, tmp, i+1)
        }
        quickSort(arr)
        var cnt = 0
        var po = n-2
        for (i <- (0 until n).reverse) {
            if (i == po)
                po -= 1
            while (po >= 0 && arr(i).cp > 0 && arr(po).cp > 0) {
                tmp = min(arr(i).cp, arr(po).cp)
                arr(i).cp -= tmp
                arr(po).cp -= tmp
                cnt += tmp
                if (arr(po).cp == 0) {
                    po -= 1
                }
            }
        }
        writer.println(cnt)
        po = n-2
        for (i <- (0 until n).reverse) {
            if (i == po)
                po -= 1
            while (po >= 0 && arr(i).social > 0 && arr(po).social > 0) {
                tmp = min(arr(i).social, arr(po).social)
                for (k <- 1 to tmp)
                    writer.println(arr(po).ind + " " + arr(i).ind)
                arr(i).social -= tmp
                arr(po).social -= tmp
                cnt += tmp
                if (arr(po).social == 0) {
                    po -= 1
                }
            }
        }

    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[myType](n)
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            arr(i) = myType(tmp, tmp, i+1)
        }
        quickSort(arr)
        var cnt = 0
        var po = n-2
        for (i <- (0 until n).reverse) {
            while (po >= 0 && arr(i).cp > 0 && arr(po).cp > 0) {
                tmp = min(arr(i).cp, arr(po).cp)
                arr(i).cp -= tmp
                arr(po).cp -= tmp
                cnt += tmp
                if (arr(po).cp == 0) {
                    po -= 1
                }
            }
        }
        writer.println(cnt)
        po = n-2
        for (i <- (0 until n).reverse) {
            while (po >= 0 && arr(i).social > 0 && arr(po).social > 0) {
                tmp = min(arr(i).social, arr(po).social)
                for (k <- 1 to tmp)
                    writer.println((po+1) + " " + (i+1))
                arr(i).social -= tmp
                arr(po).social -= tmp
                cnt += tmp
                if (arr(po).social == 0) {
                    po -= 1
                }
            }
        }

    }
    writer.flush()
}


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

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

    val t = StdIn.readLine().toInt

    for (_ <- 1 to t) {
      val n = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      var cnt = 1
      val res = Array.fill(str.length)(0)
      val q0, q1 = mutable.Queue[Int]()

      for (i <- 0 until n) {
        if (str(i) == '0') {
          if (q1.isEmpty) {
            res(i) = cnt
            cnt += 1
          } else {
            res(i) = res(q1.dequeue())
          }
          q0.enqueue(i)
        } else {
          if (q0.isEmpty) {
            res(i) = cnt
            cnt += 1
          } else {
            res(i) = res(q0.dequeue())
          }
          q1.enqueue(i)
        }
      }
      println(res.max)
      println(res.mkString(" "))
    }
  }
}

//package codeforces.contests._1399

object BinaryStringToSubsequences {
  def main(args: Array[String]): Unit = {
    for (t <- 1 to io.StdIn.readInt) {
      val _ = io.StdIn.readInt()
      val input = io.StdIn.readLine.toList

      var id = 0

      def getUniqueId: Int = {
        id += 1
        id
      }

      @scala.annotation.tailrec
      def loop(ls: List[Char], zeroIds: List[Int] = Nil, oneIds: List[Int] = Nil, result: List[Int] = Nil): List[Int] = {
        ls match {
          case Nil => result.reverse
          case '0' :: tail => oneIds match {
            case Nil =>
              val id = getUniqueId
              loop(tail, id :: zeroIds, Nil, id :: result)
            case id :: oneTail =>
              loop(tail, id :: zeroIds, oneTail, id :: result)
          }
          case '1' :: tail => zeroIds match {
            case Nil =>
              val id = getUniqueId
              loop(tail, Nil, id :: oneIds, id :: result)
            case id :: zeroTail =>
              loop(tail, zeroTail, id :: oneIds, id :: result)
          }
        }
      }

      println {
        val ans = loop(input)
        s"$id\n${ans.mkString(" ")}"
      }
    }
  }
}

import scala.collection.mutable
import scala.io.Source

object BinaryStringToSubsequences1399D extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//          val lines: Iterator[String] =
//            Source.fromString("1\n5\n11000\n1\n1\n2\n00\n2\n10\n2\n01\n2\n11\n3\n000\n3\n100\n3\n010\n3\n110\n3\n001\n3\n101\n3\n011\n3\n111\n4\n0000\n4\n1000\n4\n0100\n4\n1100\n4\n0010\n4\n1010\n4\n0110\n4\n1110\n4\n0001\n4\n1001\n4\n0101\n4\n1101\n4\n0011\n4\n1011\n4\n0111\n4\n1111\n5\n00000\n5\n10000\n5\n01000\n5\n11000\n5\n00100\n5\n10100\n5\n01100\n5\n11100\n5\n00010\n5\n10010\n5\n01010\n5\n11010\n5\n00110\n5\n10110\n5\n01110\n5\n11110\n5\n00001\n5\n10001\n5\n01001\n5\n11001\n5\n00101\n5\n10101\n5\n01101\n5\n11101\n5\n00011").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { case (ar, max) =>
    println(max)
    println(ar mkString " ")
  }

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      (Array(1),1)
    } else {
      val s = lines.next.toCharArray
      solve(s)
    }
  }

  private def solve(s: Array[Char]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val ones = mutable.Stack[Int]()
    val zeros = mutable.Stack[Int]()
    def updGroup(v: Char, gr: Int) = v match {
      case '0' => zeros push gr
      case '1' => ones push gr
    }
    updGroup(s.head, 1)
    def findFirstAvailable(lastVal: Char) = lastVal match {
      case '0' => if (ones.isEmpty) None else Some(ones.pop)
      case '1' => if (zeros.isEmpty) None else Some(zeros.pop)
    }
    def removeGroupOfPrevSet(v: Char): Unit = v match {
      case '0' => ones.pop
      case '1' => zeros.pop
    }
    var cg = 1
    var largestG = 1
    var i = s.head
    for (j <- s.tail) {
      if (i == j) {
        cg = findFirstAvailable(j).getOrElse({
          largestG = largestG + 1
          largestG
        })
        sol += cg
      }
      else {
        removeGroupOfPrevSet(j)
        sol += cg
      }
      updGroup(j, cg)
      i = j
    }
    (sol.toArray, largestG)
  }
}

import scala.collection.mutable
import scala.io.Source

object BinaryStringToSubsequences1399D extends App {

//  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
          val lines: Iterator[String] =
            Source.fromString("1\n5\n11000\n1\n1\n2\n00\n2\n10\n2\n01\n2\n11\n3\n000\n3\n100\n3\n010\n3\n110\n3\n001\n3\n101\n3\n011\n3\n111\n4\n0000\n4\n1000\n4\n0100\n4\n1100\n4\n0010\n4\n1010\n4\n0110\n4\n1110\n4\n0001\n4\n1001\n4\n0101\n4\n1101\n4\n0011\n4\n1011\n4\n0111\n4\n1111\n5\n00000\n5\n10000\n5\n01000\n5\n11000\n5\n00100\n5\n10100\n5\n01100\n5\n11100\n5\n00010\n5\n10010\n5\n01010\n5\n11010\n5\n00110\n5\n10110\n5\n01110\n5\n11110\n5\n00001\n5\n10001\n5\n01001\n5\n11001\n5\n00101\n5\n10101\n5\n01101\n5\n11101\n5\n00011").getLines
  val ntc: Int = lines.next.toInt
  (0 until ntc map { _ =>
    handleTC()
  }).zipWithIndex.foreach({ case(ar,i) =>
    //      println(s"# $i")
    println(ar.max)
    println(ar mkString " ")
  })

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      Array(1)
    } else {
      val s = lines.next.split("")
      solve(s)
    }
  }

  private def solve(s: Array[String]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val groupLasts = mutable.Map[Int, String](1 -> s.head)
    def findLeastDiff(lastVal: String) = {
      groupLasts.find { case (_, v) => v != lastVal }.map(_._1)
    }
    var cg = 1
    var largestG = 1
    s.zip(s.tail).foreach { case (i, j) =>
      if (i == j) {
        cg = findLeastDiff(j).getOrElse({
          largestG = largestG + 1
          largestG
        })
        sol += cg
      }
      else sol += cg
      groupLasts(cg) = j
    }
    sol.toArray
  }
}

import scala.collection.mutable
import scala.io.Source

object BinaryStringToSubsequences1399D extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//        val lines: Iterator[String] =
//          Source.fromString("4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { ar =>
    println(ar.max)
    println(ar mkString " ")
  }

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      Array(1)
    } else {
      val s = lines.next.split("").map(_ == "1")
      solve(s)
    }
  }

  private def solve(s: Array[Boolean]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)
    def findLeastDiff(lastVal: Boolean) = {
      groupLasts.find { case (_, v) => v != lastVal }.map(_._1)
    }
    var cg = 1
    s.zip(s.tail).foreach { case (i, j) =>
      if (i == j) {
        cg = findLeastDiff(j).getOrElse(cg + 1)
        sol += cg
      }
      else sol += cg
      groupLasts(cg) = j
    }
    sol.toArray
  }
}

import scala.collection.mutable
import scala.io.Source

object BinaryStringToSubsequences1399D extends App {

//  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
        val lines: Iterator[String] =
          Source.fromString("4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { ar =>
    println(ar.max)
    println(ar mkString " ")
  }

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      Array(1)
    } else {
      val s = lines.next.split("").map(_ == "1")
      solve(s)
    }
  }

  private def solve(s: Array[Boolean]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)
    def findLeastDiff(lastVal: Boolean) = {
      groupLasts.find { case (_, v) => v != lastVal }.map(_._1)
    }
    var cg = 1
    s.zip(s.tail).foreach { case (i, j) =>
      if (i == j) {
        cg = findLeastDiff(j).getOrElse(cg + 1)
        sol += cg
      }
      else sol += cg
      groupLasts(cg) = j
    }
    sol.toArray
  }
}

import scala.collection.mutable
import scala.io.Source

object BinaryStringToSubsequences1399D extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//        val lines: Iterator[String] =
//          Source.fromString("1\n5\n11000\n1\n1\n2\n00\n2\n10\n2\n01\n2\n11\n3\n000\n3\n100\n3\n010\n3\n110\n3\n001\n3\n101\n3\n011\n3\n111\n4\n0000\n4\n1000\n4\n0100\n4\n1100\n4\n0010\n4\n1010\n4\n0110\n4\n1110\n4\n0001\n4\n1001\n4\n0101\n4\n1101\n4\n0011\n4\n1011\n4\n0111\n4\n1111\n5\n00000\n5\n10000\n5\n01000\n5\n11000\n5\n00100\n5\n10100\n5\n01100\n5\n11100\n5\n00010\n5\n10010\n5\n01010\n5\n11010\n5\n00110\n5\n10110\n5\n01110\n5\n11110\n5\n00001\n5\n10001\n5\n01001\n5\n11001\n5\n00101\n5\n10101\n5\n01101\n5\n11101\n5\n00011").getLines
  val ntc: Int = lines.next.toInt
  (0 until ntc map { _ =>
    handleTC()
  }).zipWithIndex.foreach({ case(ar,i) =>
      println(s"# $i")
      println(ar.max)
      println(ar mkString " ")
    })

  private def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      Array(1)
    } else {
      val s = lines.next.split("").map(_ == "1")
      solve(s)
    }
  }

  private def solve(s: Array[Boolean]) = {
    val sol = mutable.ArrayBuffer[Int](1)
    val groupLasts = mutable.SortedMap[Int, Boolean](1 -> s.head)
    def findLeastDiff(lastVal: Boolean) = {
      groupLasts.find { case (_, v) => v != lastVal }.map(_._1)
    }
    var cg = 1
    s.zip(s.tail).foreach { case (i, j) =>
      if (i == j) {
        cg = findLeastDiff(j).getOrElse(groupLasts.size + 1)
        sol += cg
      }
      else sol += cg
      groupLasts(cg) = j
    }
    sol.toArray
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt

    def take(str: String): Int = {
      str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1
    }

    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      import scala.collection.mutable.ListBuffer
      val temp = ListBuffer[Int]()
      val res = Array.fill(str.length)(-1)
      var i = 1
      var s = str
      var index = 0
      while (s.nonEmpty) {
        val n = take(s)
        for (ii <- index until index + n) {
          res(ii) = i
        }
        index += n
        val (h, t) = s.splitAt(n)
        temp += h.last - '0'
        if (t.nonEmpty) {
          val li = temp.indexOf((t.head - '0') ^ 1)
          if (li >= 0) {
            i = li + 1
            temp(li) = 1 ^ temp(li)
          } else {
            i = temp.length + 1
          }
        }
        s = t
      }
      println(res.max)
      println(res.mkString(" "))
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt

    def take(str: String): Int = {
      str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1
    }

    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      import scala.collection.mutable.ListBuffer
      val temp = ListBuffer[Int]()
      val res = Array.fill(str.length)(-1)
      var i = 1
      var s = str
      var index = 0
      while (s.nonEmpty) {
        val n = take(s)
        for (ii <- index until index + n) {
          res(ii) = i
        }
        index += n
        val (h, t) = s.splitAt(n)
        temp += h.last - '0'
        if (t.nonEmpty) {
          val li = temp.indexOf((t.head - '0') ^ 1)
          if (li >= 0) {
            i = li + 1
          } else {
            i = temp.length + 1
          }
        }
        s = t
      }
      println(res.max)
      println(res.mkString(" "))
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt

    def take(str: String): Int = {
      str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1
    }

    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      import scala.collection.mutable.ListBuffer
      val temp = ListBuffer[Int]()
      val res = Array.fill(str.length)(-1)
      var i = 1
      var s = str
      var index = 0
      while (s.nonEmpty) {
        val n = take(s)
        for (ii <- index until index + n) {
          res(ii) = i
        }
        index += n
        val (h, t) = s.splitAt(n)
        temp += h.last - '0'
        if (t.nonEmpty) {
          val li = temp.indexOf((t.head - '0') ^ 1)
          if (li >= 0) {
            i = li + 1
          } else {
            i = temp.length + 1
          }
        }
        s = t
      }
      println(res.mkString(" "))
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt

    def take(str: String): Int = {
      str.zip(str.tail).takeWhile(c => c._1 != c._2).length + 1
    }

    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val str = StdIn.readLine()
      import scala.collection.mutable.ListBuffer
      val temp = ListBuffer[Int]()
      val res = Array.fill(str.length)(-1)
      var i = 1
      var s = str
      var index = 0
      while (s.nonEmpty) {
        val n = take(s)
        for (ii <- index until index + n) {
          res(ii) = i
        }
        index += n
        val (h, t) = s.splitAt(n)

        if (t.nonEmpty) {
          val li = temp.indexOf((t.head - '0') ^ 1)
          if (li >= 0) {
            i = li + 1
            temp(li) = 1 ^ temp(li)
          } else {

            i = res.max + 1
            temp += h.last - '0'
          }
        }

        s = t
      }
      println(res.max)
      println(res.mkString(" "))
    }
  }
}


object Main {
  import java.io.{BufferedReader, InputStreamReader}

  val x = 0
  def main(args: Array[String]): Unit = {
    val reader = new InputReader()
    val t = reader.nextInt()
    (1 to t).foreach { i =>
      val n = reader.nextString()
      if (n.length > 2)
        System.out.println(n.min)
      else
        System.out.println(n.charAt(1))
    }

  }

  class InputReader() {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var line: Array[String] = null
    var cur: Int = 0

    def nextString(): String = {
      while (line == null || cur >= line.length) {
        cur = 0
        line = reader.readLine().split(""" """)
      }
      cur += 1
      line(cur - 1)
    }

    def nextInt(): Int = {
      nextString().toInt
    }

    def nextLong(): Int = {
      nextString().toInt
    }

  }

}

import java.io.BufferedReader
import java.io.InputStreamReader

object Main {

  def main(args: Array[String]): Unit = {
    val reader = new InputReader()
    val t = reader.nextInt()
    (1 to t).foreach { i =>
      val n = reader.nextString()
      if (n.length > 2)
        System.out.println(n.min)
      else
        System.out.println(n.charAt(1))
    }

  }

  class InputReader() {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var line: Array[String] = null
    var cur: Int = 0

    def nextString(): String = {
      while (line == null || cur >= line.length) {
        cur = 0
        line = reader.readLine().split(""" """)
      }
      cur += 1
      line(cur - 1)
    }

    def nextInt(): Int = {
      nextString().toInt
    }

    def nextLong(): Int = {
      nextString().toInt
    }

  }

}

/*
https://codeforces.com/contest/1684/problem/0

1234 => 2134 => 213 => 312 => 31 => 13 => 1
1234 => 1324 => 132 => 123 => 12 => 21 => 2

1) 2d. XY => YX => Y
2) > 2d. XYZAm => XmZAY =>... => XmZ => ZmX => Zm => mZ

 */

import scala.io.StdIn

object many_digitals{

    def main(args: Array[String]): Unit = {
        def solving(n: String) = {
            if (n.length == 2) {
                println(n(1))
            }
            else {
                val answer = n.split("").map(x => x.toInt).min
                println(answer)
            }
        }

        val t = StdIn.readLine().toInt
        val in = new Array[String](t)
        for (i <- 0 until(t)) {
            //        val n = StdIn.readLine().toInt
            in(i) = StdIn.readLine()
        }

        in.foreach(solving _)

    }
}