import scala.io.StdIn.readLine

object task extends App {
  val t: Int = readLine.toInt
  (1 to t).foreach { _ =>
    val n = readLine.toLong
    println("2")
    printf(s"$n ${n-1}\n");
    for (i <- n to 3 by -1) {
      printf(s"$i ${i - 2}\n")
    }
  }
}

import scala.collection.mutable

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val res = new StringBuilder
      val even, odd = mutable.PriorityQueue.empty[Int]
      for (i <- 1 to n) {
        if (i % 2 == 0) even.enqueue(i)
        else odd.enqueue(i)
      }

      while (even.size > 1 || odd.size > 1) {
        if (even.size > 1 && odd.size > 1) {
          val aE, bE = even.dequeue()
          val cE = (aE + bE) / 2
          val aO, bO = odd.dequeue()
          val cO = (aO + bO) / 2
          val c = if (cO > bE) {
            res.append(s"$aO $bO\n")
            even.enqueue(aE, bE)
            cO
          } else {
            res.append(s"$aE $bE\n")
            odd.enqueue(aO, bO)
            cE
          }
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        } else if (odd.size > 1) {
          val a, b = odd.dequeue()
          res.append(s"$a $b\n")
          val c = (a + b) / 2
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        } else if (even.size > 1) {
          val a, b = even.dequeue()
          res.append(s"$a $b\n")
          val c = (a + b) / 2
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        }
      }

      if (even.size == 1 && odd.size == 1) {
        val a = even.dequeue()
        val b = odd.dequeue()
        res.append(s"$a $b\n")
        val c = (a + b + 1) / 2
        if (c % 2 == 0) even.enqueue(c)
        else odd.enqueue(c)
      }

      val x = if (even.nonEmpty) even.dequeue() else odd.dequeue()

      out.println(x)
      out.print(res.toString())
    }

    out.flush()
  }

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

import scala.io.StdIn.readLine

object task extends App {
  val t: Int = readLine.toInt
  (1 to t).foreach { _ =>
    val n = readLine.toLong
    println(2)
    for (i <- n to 3 by -1) {
      println(s"$i ${i - 2}")
      println(s"${i-1} ${i - 1}")
    }
  }
}

import scala.io.StdIn.readLine

object task extends App {
  val t: Int = readLine.toInt
  (1 to t).foreach { _ =>
    val n = readLine.toLong
    println("2")
    for (i <- n to 3 by -1) {
      if (i > 3) printf(s"$i ${i - 2}\n${i-1} ${i - 1}\n")
      else printf(s"$i ${i - 2}\n")
    }
  }
}

import scala.io.StdIn.readLine

object task extends App {
  val t: Int = readLine.toInt
  (1 to t).foreach { _ =>
    val n = readLine.toLong
    println("2")
    for (i <- n to 3 by -1) {
      if (i > 3) println(s"$i ${i - 2}\n${i-1} ${i - 1}")
      else println(s"$i ${i - 2}")
    }
  }
}

import scala.collection.mutable

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val res = new StringBuilder
      val even, odd = mutable.PriorityQueue.empty[Int]
      for (i <- 1 to n) {
        if (i % 2 == 0) even.enqueue(i)
        else odd.enqueue(i)
      }

      while (even.size > 1 || odd.size > 1) {
        if (even.size > 1 && odd.size > 1) {
          val aE, bE = even.dequeue()
          val cE = (aE + bE) / 2
          val aO, bO = odd.dequeue()
          val cO = (aO + bO) / 2
          val c = if (cO > aE) {
            res.append(s"$aO $bO\n")
            even.enqueue(aE, bE)
            cO
          } else {
            res.append(s"$aE $bE\n")
            odd.enqueue(aO, bO)
            cE
          }
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        } else if (odd.size > 1) {
          val a, b = odd.dequeue()
          res.append(s"$a $b\n")
          val c = (a + b) / 2
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        } else if (even.size > 1) {
          val a, b = even.dequeue()
          res.append(s"$a $b\n")
          val c = (a + b) / 2
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        }
      }

      if (even.size == 1 && odd.size == 1) {
        val a = even.dequeue()
        val b = odd.dequeue()
        res.append(s"$a $b\n")
        val c = (a + b + 1) / 2
        if (c % 2 == 0) even.enqueue(c)
        else odd.enqueue(c)
      }

      val x = if (even.nonEmpty) even.dequeue() else odd.dequeue()

      out.println(x)
      out.print(res.toString())
    }

    out.flush()
  }

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


object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//    val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val m = in.nextInt()
      println(math.ceil(m / 2d).toInt)
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

import scala.io.StdIn._

object A extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val i = readInt()
    println((i - 1) / 2 + 1)
  }

}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//    val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val m = in.nextInt()
      if (m == 1 || m == 2) println(1) else println(2)
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}


import scala.io.StdIn

object Chocolate_1139B {
  // https://codeforces.com/problemset/problem/1139/B
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val cTypes = StdIn.readLine().split(" ").map(_.toInt)

    val (_, res) = cTypes.foldRight((Int.MaxValue, 0L)) {
      case (curr: Int, (prev: Int, sum: Long)) =>
        if (curr <= 0 || prev <= 0) {
          (0, sum)
        } else if (prev > curr) {
          (curr, sum + curr)
        } else {
          // prev <= curr && prev != 0
          (prev - 1, sum + prev - 1)
        }
    }

    println(res)
  }

}

//package codeforces.contest1139

object Chocolates {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)

    println(arr.foldRight((Int.MaxValue, 0l)) { case (current, (maximum: Int, sum: Long)) =>
      val chocolates = (current min (maximum - 1)) max 0
      (chocolates, sum + chocolates)
    }._2)
  }
}

object B1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val array = stdin.readLine.trim.split(" ").map(_.toLong)
    var sum = 0L
    sum += array(n-1)
    for (i <- 1 until n){
      val temp = math.max(math.min(array(n-i-1) , array(n-i)-1), 0)
      sum += temp
      array(n-i-1) = temp
    }
    println(sum)
  }
}

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 java.util.Arrays

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    var ans = 0L

    var next = 1e9.toInt + 1
    REP_r(N) { i =>
      next = if (A(i) < next) {
        A(i)
      } else {
        max(0, next - 1)
      }
      debug(s"next:$next")
      ans += next
    }

    out.println(ans)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

object B1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val array = stdin.readLine.trim.split(" ").map(_.toLong).reverse
    val cal = (a: Long,b: Long) => math.max(math.min(b , a-1), 0)
    var ans = array(0)
    for (i <- 1 until n){
      array(i) = cal(array(i-1), array(i))
      ans = ans + array(i)
    }
    println(ans)
  }
}

//package codeforces.contest1139

object Chocolates {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)

    println(arr.foldRight((Int.MaxValue, 0)) { case (current, (maximum: Int, sum: Int)) =>
      val chocolates = (current min (maximum - 1)) max 0
      (chocolates, sum + chocolates)
    }._2)
  }
}

object B1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val array = stdin.readLine.trim.split(" ").map(_.toLong).reverse
    val temp = (a: Long,b: Long) => math.max(math.min(b , a-1), 0)
    var ans = 0L
    for (i <- 1 until n){
      ans = ans + temp(array(i-1), array(i))
    }
    println(ans)
  }
}

object B1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val array = stdin.readLine.trim.split(" ").map(_.toLong).reverse
    val ans = array.foldLeft(0L)((a,b) => math.max(math.min(b , a-1), 0))
    println(ans)
  }
}


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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n = read[Int]
    val prices, frontColors, backColors = read[Vector, Int](n)
    val favColors = read[Seq[Int]]

    val sortedPrices = prices.zipWithIndex.sortBy(_.key)

    // map from color -> Seq[(price, idx)]
    val table = map[Int] to mutable.ListBuffer.empty[(Int, Int)]

    for {
      entry @ (price, idx) <- sortedPrices
      color <- Seq(frontColors(idx), backColors(idx)).distinct
    } table(color).append(entry)

    val isUsed = mutable.Set.empty[Int]

    def fetchBestPrice(color: Int): Int = {
      table(color).headOption match {
        case None => -1
        case Some((price, idx)) =>
          table(color).remove(n = 0, count = 1)
          if (isUsed(idx)) {
            fetchBestPrice(color)
          } else {
            isUsed += idx
            price
          }
      }
    }

    writeAll(favColors.map(fetchBestPrice))
  }
}
/****************************[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
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  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
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  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 indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    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")

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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 scala.collection.mutable

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) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  case class Shirt(p: Int, a: Int, b: Int)

  val Array(n) = readInts(1)
  val ps, as, bs = readInts(n)

  val shirts = Array.tabulate(n){ i => Shirt(ps(i), as(i) - 1, bs(i) - 1)}.sortBy(_.p)

  val Array(m) = readInts(1)
  val cs = readInts(m)

  val res = Array.fill(m){ -1 }
  val ptr = Array.fill(3)(0)
  val used = new mutable.BitSet(n)

  for (i <- 0 until m) {
    val c = cs(i) - 1
    while (ptr(c) < n && (used(ptr(c)) || (shirts(ptr(c)).a != c && shirts(ptr(c)).b != c))) ptr(c) += 1
    if (ptr(c) < n) {
      used += ptr(c)
      res(i) = shirts(ptr(c)).p
    }
  }

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

  println(res.mkString(" "))

  Console.flush
}

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

	override def apply(io: IO): io.type = {
		val n = io.read[Int]
		val p = io.read[Array, Int](n)
		val a = io.read[Array, Int](n)
		val b = io.read[Array, Int](n)
		val m = io.read[Int]
		val qries = io.read[Seq, Int](m)
		var x = new Array[Int](n)
		for { i <- 0 to n-1 } { x(i) = i }
		x = x.sortWith((v1, v2) => p(v1) < p(v2) )
		var pts = new Array[Int](3)
		//pts = pts.map(value => 1)
		val ans = mutable.ArrayBuffer.empty[Int]
		for { qry <- qries } {
			while (pts(qry-1) < n && a(x(pts(qry-1))) != qry && b(x(pts(qry-1))) != qry) {
				pts(qry-1) += 1
			}
			if(pts(qry-1) < n) {
				val id = x(pts(qry-1))
				ans += p(id)
				a(id) = -1
				b(id) = -1
				pts(qry-1) += 1
			} else {
				ans += -1
			}
		}
		//x = x.map(value => p(value))
		//io.writeAll(x)
		//io.writeLine()
		io.writeAll(ans)
		io.writeLine()
		io
	}
}
/****************************[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 = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
	import scala.collection.mutable

	type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

	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)

	implicit class GenericExtensions[A](a: A) {
		def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
	}

	implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
		def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

		def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

		def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
	}

	implicit class PairExtensions[A, B](p: (A, B)) {
		def key = p._1
		def value = p._2
		def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
	}

	implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
		def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
	}

	implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
		def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
	}

	implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
		def notContains(x: A): Boolean = !(s contains x)
		def toMutable = mutable.Set.empty[A] ++ s
	}

	implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
		def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
		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)}
	}

	implicit class BooleanExtensions(x: Boolean) {
		def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
		def toEnglish = if(x) "Yes" else "No"
	}

	def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

	def map[K] = new {
		def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
		def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

	object Read {
		implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
		implicit val string                                                   : Read[String]       = new Read(_.next())
		implicit val int                                                      : Read[Int]          = string.map(_.toInt)
		implicit val long                                                     : Read[Long]         = string.map(_.toLong)
		implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
		implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
		implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
		implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
		implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
		implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
		implicit val boolean                                                  : Read[Boolean]      = string map {s =>
			s.toLowerCase match {
				case "yes" | "true" | "1" => true
				case "no" | "false" | "0" => false
				case _ => s.toBoolean
			}
		}
	}
}


import scala.collection.mutable

object C extends App {

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

  val Array(n) = readInts(1)

  val divs0 = mutable.Set.empty[Int]
  val lim = Math.sqrt(n).toInt + 2
  var d = 1
  while (d < lim) {
    if (n % d == 0) {
      divs0 += d
      val d2 = n / d
      if (d2 != d) divs0 += d2
    }
    d += 1
  }

  val res = Array.ofDim[Long](divs0.size)
  val divs = divs0.toArray
  for (i <- divs.indices) {
    val d = divs(i)
    val max = n - d + 1
    val dd = n.toLong / d
    res(i) = (1 + max) * dd / 2
  }

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

  println(res.sorted.mkString(" "))

  Console.flush
}

//package codeforces.contest1091

import scala.collection.SortedSet

object NewYearAndTheSphereTransmission {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val sqrt: Int = math.sqrt(n).floor.toInt

    println((1 to sqrt).foldLeft(SortedSet[Long]())((set, i) => {
      if (n % i == 0) {
        set + calculateSumOfSeries(1, n + 1 - i, i) + calculateSumOfSeries(1, n + 1 - n / i, n / i)
      } else set
    }).mkString(" "))

  }

  def calculateSumOfSeries(a: Int, an: Int, d: Int): Long = {
    val n = (an - a) / d + 1
    1l * n * (a + an) / 2
  }
}


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

import scala.collection.immutable
import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C640B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t =ni()
    REP(t) { _ =>
      val n = ni()
      if(n >= 4) {
        val x = if(n % 2 == 0) n - 1 else n
        x to 1 by -2 foreach(i => out.print(s"$i "))
        out.print("4 2 ")
        if(n >= 6) {
          6 to n by 2 foreach(i => out.print(s"$i "))
        }
        out.println()
      } else {
        out.println(-1)
      }
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn

/**
* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
*/

object Main {
   def main(args: Array[String]): Unit = {
      val count = StdIn.readInt()
      for (_ <- 0 until count) {
         val n = StdIn.readInt()
         val result = solution(n, 0, n - 1, Array.ofDim(n))
         if (result.isEmpty)
            print("-1")
         else
            result.foreach(x => print(x + " "))
         println()
      }
   }

   @tailrec
   def solution(n: Int, left: Int, right: Int, result: Array[Int]): Array[Int] = {
      if (n < 4) Array.empty
      else if (n == 4) {
         updateInPlace(result, left, 3)
         updateInPlace(result, left + 1, 1)
         updateInPlace(result, left + 2, 4)
         updateInPlace(result, left + 3, 2)
      }
      else if (n % 2 == 0) solution(n - 1, left + 1, right, updateInPlace(result, left, n))
      else solution(n - 1, left, right - 1, updateInPlace(result, right, n))
   }

   def updateInPlace(array: Array[Int], index: Int, element: Int) = {
      array.update(index, element)
      array
   }
}


object Solution {

  import InOut._
  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt: Int = Integer.parseInt(nextToken)

    def nextLong: Long = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int): Array[Int] = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int): Array[Long] = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int): Array[BigInt] = Array.fill(n) {
      nextBig
    }

    def nextLine: String = in.readLine
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to nextInt){
      val p,a,b,c = nextLong
      val arr = for(i <- List(a,b,c)) yield if(p%i == 0) 0 else if(p > i) i*(p/i+1)-p else i-p
      out.println(arr.min)
    }
    out.flush()

  }

}

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

    for (_ <- 1 to nextInt) {
      val p, a, b, c = nextLong
      val a0 = (a - p % a) % a
      val b0 = (b - p % b) % b
      val c0 = (c - p % c) % c

      out.println(a0 min b0 min c0)
    }

    out.flush()
  }

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

object Solution {

  import InOut._
  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt: Int = Integer.parseInt(nextToken)

    def nextLong: Long = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int): Array[Int] = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int): Array[Long] = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int): Array[BigInt] = Array.fill(n) {
      nextBig
    }

    def nextLine: String = in.readLine
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to nextInt){
      val p,a,b,c = nextLong
      val arr = for(i <- List(a,b,c)) yield if(p > i) i+i*(p/i)-p else i-p
      out.println(arr.min)
    }
    out.flush()

  }

}


import scala.io.Source
import java.io.PrintWriter
import java.io.File
import scala.util.control.Breaks

object CF254c {

    def main(args: Array[String]): Unit = {
            doIt();
    }
    def doIt(){
        /*val sc = new Scanner(System.in);
        val s = sc.next().toCharArray();
        val t = sc.next().toCharArray();*/
        val reader = Source.fromFile("input.txt").getLines;
        val s = reader.next().toCharArray();
        val t = reader.next().toCharArray();
        val writer = new PrintWriter(new File("output.txt" ));
        val loop = new Breaks;
        var as = new Array[Int](26);
        var at = new Array[Int](26);
        var cnts = new Array[Int](26);
        val len = s.length;
        for(e <- s){ //foreach
            as(e - 'A') += 1; //配列は()。++は駄目
            cnts(e - 'A') += 1;
        }
        for(e <- t) at(e - 'A') += 1; //{}は省略可能
        var count = 0;
        for(i <- 0 until len){ //0 .. len - 1
            var idx = s(i) - 'A';
            if(at(idx) < as(idx)){
                loop.breakable{
                    for(j <- 0 until as.length)
                        if(as(j) < at(j) && ((j < idx) || cnts(idx) <= as(idx) - at(idx) )){
                            s(i) = (j + 'A').toChar;
                            as(j) += 1;
                            as(idx) -= 1;
                            count += 1;
                            loop.break;
                        }
                }
            }
            cnts(idx) -= 1;
        }
        writer.println(count);
        writer.println(s.mkString);
        writer.close();
        /*println(count);
        println(s.mkString); //toStringでは駄目*/
    }

}

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

object test5 extends App {
	val sc=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")

	val S=sc.nextLine.toCharArray()
    val T=sc.nextLine
    val n=S.length
    val s_counts=new Array[Int](26)
    val t_counts=new Array[Int](26)

    0 until n foreach{i=>
    	s_counts(S(i)-'A')+=1
    	t_counts(T(i)-'A')+=1
    }
    var count=0

    0 until n foreach{i=>
    	s_counts(S(i)-'A')-t_counts(S(i)-'A') match{
    		case x if x>0 =>process(i)
    		case _ =>
    	}
    }
    out.println(count)
    out.println(S.mkString)
    out.close

    def process(i:Int){
    	val next=find
    	val c=S(i)

    	if(t_counts(c-'A')==0 || next<c){
    		S(i)=next
    		count+=1
    		s_counts(c-'A')-=1
    		s_counts(next-'A')+=1
    	}
    	else{
    		s_counts(c-'A')-=1
    		t_counts(c-'A')-=1
    	}
    }

    def find():Char={
    	for(i<-0 until 26)
    	{
    		if(t_counts(i)>s_counts(i)) return ('A'+i).toChar;
    	}

    	return None.get
    }
}

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

object test5 extends App {
	val sc=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")

	val S=sc.nextLine.toCharArray()
    val T=sc.nextLine
    val n=S.length
    val s_counts=new Array[Int](26)
    val t_counts=new Array[Int](26)

    0 until n foreach{i=>
    	s_counts(S(i)-'A')+=1
    	t_counts(T(i)-'A')+=1
    }
    var count=0

    for(i<-0 until n if s_counts(S(i)-'A')-t_counts(S(i)-'A')>0)
    	process(i)

    out.println(count)
    out.println(S.mkString)
    out.close

    def process(i:Int){
    	val next=find
    	val c=S(i)

    	if(t_counts(c-'A')==0 || next<c){
    		S(i)=next
    		count+=1
    		s_counts(c-'A')-=1
    		s_counts(next-'A')+=1
    	}
    	else{
    		s_counts(c-'A')-=1
    		t_counts(c-'A')-=1
    	}
    }

    def find():Char={
    	for(i<-0 until 26)
    	{
    		if(t_counts(i)>s_counts(i)) return ('A'+i).toChar;
    	}

    	return None.get
    }
}

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

object test5 extends App {
	val sc=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")

	val S=sc.nextLine.toCharArray()
    val T=sc.nextLine
    val n=S.length
    val s_counts=new Array[Int](26)
    val t_counts=new Array[Int](26)

    0 until n foreach{i=>
    	s_counts(S(i)-'A')+=1
    	t_counts(T(i)-'A')+=1
    }
    var count=0

    0 until n foreach{i=>
    	s_counts(S(i)-'A')-t_counts(S(i)-'A') match{
    		case x if x>0 =>process(i)
    		case _ =>
    	}
    }
    out.println(count)
    out.println(S.mkString)

    def process(i:Int){
    	val next=find
    	val c=S(i)

    	if(t_counts(c-'A')==0 || next<c){
    		S(i)=next
    		count+=1
    		s_counts(c-'A')-=1
    		s_counts(next-'A')+=1
    	}
    	else{
    		s_counts(c-'A')-=1
    		t_counts(c-'A')-=1
    	}
    }

    def find():Char={
    	for(i<-0 until 26)
    	{
    		if(t_counts(i)>s_counts(i)) return ('A'+i).toChar;
    	}

    	return None.get
    }
}

//import java.util.Scanner
import scala.io.Source
import java.io.PrintWriter
import java.io.File

object CF254c {

    def main(args: Array[String]): Unit = {
            doIt();
    }
    def doIt(){
        /*val sc = new Scanner(System.in);
        val s = sc.next().toCharArray();
        val t = sc.next().toCharArray();*/
        val reader = Source.fromFile("input.txt").getLines;
        val s = reader.next().toCharArray();
        val t = reader.next().toCharArray();
        val writer = new PrintWriter(new File("output.txt" ));
        var as = new Array[Int](26);
        var at = new Array[Int](26);
        var cnts = new Array[Int](26);
        val len = s.length;
        for(e <- s){ //foreach
            as(e - 'A') += 1; //配列は()。++は駄目
            cnts(e - 'A') += 1;
        }
        for(e <- t) at(e - 'A') += 1; //{}は省略可能
        var count = 0;
        for(i <- 0 until len){ //0 .. len - 1
            var idx = s(i) - 'A';
            if(at(idx) < as(idx)){
                for(j <- 0 until as.length)
                    if(as(j) < at(j) && ((j < idx) || cnts(idx) <= as(idx) - at(idx) )){
                        s(i) = (j + 'A').toChar;
                        as(j) += 1;
                        as(idx) -= 1;
                        count += 1;
                    }
            }
            cnts(idx) -= 1;
        }
        writer.println(count);
        writer.println(s.mkString);
        writer.close();
        /*println(count);
        println(s.mkString); //toStringでは駄目*/
    }

}


object CF_526_2_B {
  def solve(n: Int, s: Long, vs: Seq[Int]): Long = {
    val minKegVol = vs.min.toLong
    val totalVol = vs.map(_.toLong).sum
    // amount taken before minKeg starts emptying
    val b = totalVol - n * minKegVol
    val excess = s - b
    if (excess <= 0) minKegVol
    else {
      val taken= ceil(excess, n)
      val left = minKegVol - taken
      if (left < 0) -1 else left
    }
  }

  // Specify Input and Output formats here:
  def formatIn(i: Input) = (i.int, i.long, {i.nextLine; i.intSeq()})
  def formatOut(out: Long) = out.toString

//     ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
    def solveVals = (solve _).tupled(formatIn(this))
    def solveStr = formatOut(solveVals)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
}

import scala.io.StdIn

object Codeforces1084B {

  def getLeastKeg(n: Int, s: Long, v: Seq[Long]): Long = {
    val minKeg = v.min
    val totalKvass = v.sum
    if (totalKvass < s) return -1
    val extraKvass = totalKvass - minKeg * n
    if (extraKvass >= s) return minKeg
    val additionalKvass = s - extraKvass
    val perKegRemoval = (additionalKvass / n) + (if (additionalKvass % n == 0) 0 else 1)
    minKeg - perKegRemoval
  }

  def main(args: Array[String]): Unit = {
    val Array(n, s) = StdIn.readLine().trim.split(" ").map(_.toLong)
    val v = StdIn.readLine().trim.split(" ").map(_.toLong)
    val leastKeg = getLeastKeg(n.toInt, s, v)
    println(leastKeg)
  }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = nl()
    val A = na(N)
    Sorting.quickSort(A)
    reverse(A)
    val sum = sumL(A)
    val ms = A.min

    def ok(x: Int): Boolean = {
      x <= ms && (sum - x.toLong * N >= S)
    }

    val MAX =1e9.toInt + 1
    var l = -1
    var r = MAX
    while(r - l > 1) {
      val mid = (l + r) / 2
      if(ok(mid)) l = mid
      else r = mid
    }

    if (l <= -1 || l > ms) out.println(-1)
    else out.println(l)
  }

  def reverse(as: Array[Int]): Unit = {
    REP(as.length / 2) { i =>
      val t = as(i)
      as(i) = as(as.length - 1 - i)
      as(as.length - 1 - i) = t
    }
  }

  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[Int](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object CF_526_2_B {
  def solve(n: Int, s: Long, vs: Seq[Int]): Long = {
    val minKegVol = vs.min
    val totalVol = vs.map(_.toLong).sum
    // amount taken before minKeg starts emptying
    val b = totalVol - n * minKegVol
    val excess = s - b
    if (excess <= 0) minKegVol
    else {
      val taken = ceil(excess, n)
      val left = minKegVol - taken
      if (left < 0) -1 else left
    }
  }

  // Specify Input and Output formats here:
  def formatIn(i: Input) = (i.int, i.long, {i.nextLine; i.intSeq()})
  def formatOut(out: Long) = out.toString

//     ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
    def solveVals = (solve _).tupled(formatIn(this))
    def solveStr = formatOut(solveVals)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
}

object CF_526_2_B {
  def solve(n: Int, s: Long, vs: Seq[Int]): Long = {
    val minKegVol = vs.min
    val totalVol = vs.sum
    // amount taken before minKeg starts emptying
    val b = totalVol - n * minKegVol
    val excess = s - b
    if (excess <= 0) minKegVol
    else {
      val taken = ceil(excess, n)
      val left = minKegVol - taken
      if (left < 0) -1 else left
    }
  }

  // Specify Input and Output formats here:
  def formatIn(i: Input) = (i.int, i.long, {i.nextLine; i.intSeq()})
  def formatOut(out: Long) = out.toString

//     ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
    def solveVals = (solve _).tupled(formatIn(this))
    def solveStr = formatOut(solveVals)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
}

import scala.io.StdIn

object Codeforces1084B {

  def getLeastKeg(n: Int, s: Long, v: Seq[Long]): Long = {
    val minKeg = v.min
    val totalKvass = v.sum
    if (totalKvass < s) return -1
    val extraKvass = totalKvass - minKeg * n
    if (extraKvass >= s) return minKeg
    val additionalKvass = s - extraKvass
    val flatPerKegRemoval = additionalKvass / n
    val minKegCount = v.count(keg => keg == minKeg)
    val nonMinKegCount = n - minKegCount
    if (nonMinKegCount > additionalKvass % n)
      minKeg - flatPerKegRemoval - 1
    else
      minKeg - flatPerKegRemoval
  }

  def main(args: Array[String]): Unit = {
    val Array(n, s) = StdIn.readLine().trim.split(" ").map(_.toLong)
    val v = StdIn.readLine().trim.split(" ").map(_.toLong)
    val leastKeg = getLeastKeg(n.toInt, s, v)
    println(leastKeg)
  }
}


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

  override def solve(io: IO) = io.repeat {
    val s = io.read[String]
    val n = s.length

    var k = 0
    while(k < n/2 && s(k) == s(n - k - 1)) {
      k += 1
    }

    val prefix = s.substring(0, k)
    val middle = s.substring(k, n-k)
    val suffix = s.substring(n-k, n)

    def pick(str: String) =
      (str.length to 0 by -1)
        .iterator
        .flatMap(i => Set(str.take(i), str.takeRight(i)))
        .filter(x => x == x.reverse)
        .next()

    val ans = prefix + pick(middle) + suffix
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  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)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    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 {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  val M = 16769023L
  val B = 37L
  val maxN = 1000001
  val POW = ((0 to maxN).scanLeft(1L){case (h,_) => (h*B)%M}).toArray
  val hashForward: Array[Long] = Array.fill(maxN)(0L)
  val hashBackward: Array[Long] = Array.fill(maxN)(0L)
  var N = 0
  def calcHash(a: Int,b: Int,hash: Array[Long]): Long = {
    //println(s"HASHING: $a : $b")
    ((hash(b)-(hash(a)*POW(b-a))%M)+M)%M
  }

  def isPal(left: Int,right: Int): Boolean = {
    val L = (left+right)
    val L_2 = L/2
    //println(s"left: $left : right: $right  :: L_2: $L_2")
    val hLeft = if(left>=right) {
        f(L_2,0,L_2)
    }else {
        f(left,N-right,L_2)
    }

    val hRight = if(left>=right) {
      g(right,N-left,L_2)
    }else{
      g(L_2,0,L_2)
    }

    hLeft == hRight
  }

  def f(i_incl: Int, j_incl: Int, length: Int): Long = fg(i_incl,j_incl,length,(a,b) => calcHash(a,b,hashForward))
  def g(i_incl: Int, j_incl: Int, length: Int): Long = fg(i_incl,j_incl,length,(a,b) => calcHash(a,b,hashBackward))

  def fg(i_incl: Int, j_incl: Int, length: Int, ch: (Int,Int) => Long): Long = {
    //println(s"fg $i_incl $j_incl length: $length")
    val leftHash = ch(0,i_incl)
    val d = length-i_incl
    val centerHash = ch(j_incl,j_incl+d)
    //println(s"$leftHash*POW($d) + $centerHash")
    ((leftHash*POW(d))%M + centerHash)%M
  }

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val numCases = in.nextInt()
    (1 to numCases).foreach{ _ =>
      val s = in.next()
      val sr = s.reverse
      N = s.length
      hashForward(0) = 0L
      s.zipWithIndex.foreach{
        case (ch,i) =>
          val v = ch.toInt-'a'.toInt+1
          hashForward(i+1)  = (hashForward(i) *B+v)%M
      }

      hashBackward(0) = 0L
      sr.zipWithIndex.foreach{
        case (ch,i) =>
          val v = ch.toInt-'a'.toInt+1
          hashBackward(i+1) = (hashBackward(i)*B+v)%M
      }

/*
      println(isPal(0,1))
      println(isPal(1,0))
      println(isPal(0,0))
      println(isPal(1,1))
      println(isPal(2,2))
      println(isPal(3,3))
      println(isPal(4,4))
      println(isPal(5,4))
      println(isPal(4,5))
*/

      var maxH = -1
      var isEqual = true
      (0 until N).foreach{ i =>
        if(s(i) == s(N-i-1) && isEqual){
          maxH = i
        }else{
          isEqual = false
        }
      }

      val L = if(maxH== -1) 0 else (Math.min(N/2,maxH+1))

      assert(isPal(L,L))

      val r0 = (0 to (N-2*L)).flatMap{d =>
        if(isPal(L+d,L)){
          Some(d)
        }else{
          None
        }
      }.last

      val r1 = (0 to (N-2*L)).flatMap{d =>
        if(isPal(L,L+d)){
          Some(d)
        }else{
          None
        }
      }.last

      //println(s"$L: $r0 - $r1")
      //println(hashForward.take(11).mkString(" - "))
      //println(hashBackward.take(11).mkString(" - "))
      val ans = if(r0>=r1){
        //println(isPal(L+r0,L))
        s.substring(0,L+r0)+s.substring(N-L)
      }else{
        //println(isPal(L,L+r1))
        s.substring(0,L)+s.substring(N-(L+r1))
      }
      out.println(ans)

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


object main extends App with fastIO {

  val Array(n) = readLine split(" ") map(_.toInt)
  var a = readLine split(" ") map(_.toInt) toList

  import scala.collection.mutable.ArrayBuffer

  var left = a.foldLeft(ArrayBuffer[Int]())((s, v) => s += (v + (if (s.length > 0) s(s.length - 1) else 0)))
  var right = a.foldRight(ArrayBuffer[Int]())((v, s) => s += (v + (if (s.length > 0) s(s.length - 1) else 0))).reverse

  var count = (left zip right).count(v => v._1 <= v._2)
  println(count + " " + (n - count))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def nextInt :Int = { in.nextToken; in.nval.toInt }
  def nextLong :Long = { in.nextToken; in.nval.toLong }
  def nextDouble :Double = { in.nextToken; in.nval.toDouble }
  def readLine = bf.readLine

  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)

  def flush = out.flush
}

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

object C {

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

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

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

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

  def solve = {
    val n = nextInt
    val time = new Array[Int](n)
    val sumTimeA = new Array[Int](n)
    val sumTimeB = new Array[Int](n)
    time(0) = nextInt
    sumTimeA(0) = time(0)
    for (i <- 1 until n) {
      time(i) = nextInt
      sumTimeA(i) = sumTimeA(i - 1) + time(i)
    }
    sumTimeB(0) = time(n - 1)
    for (i <- 1 until n) {
      sumTimeB(i) = sumTimeB(i - 1) + time(n - i - 1)
    }
    var aInd = 0
    var bInd = 0
    var aNum = 0
    var bNum = 0
    while (aNum + bNum != n) {
      if (sumTimeA(aInd) < sumTimeB(bInd)) {
        aInd += 1
        aNum += 1
      } else if (sumTimeA(aInd) > sumTimeB(bInd)) {
        bInd += 1
        bNum += 1
      } else {
        if (aInd == n - bInd - 1) {
          aNum += 1
        } else {
          aInd += 1
          bInd += 1
          aNum += 1
          bNum += 1
        }
      }
    }
    out.println(aNum + " " + bNum)

  }

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

object P6C {
    def main(args : Array[String]) {
        val n = readLine.toInt
        var t = readLine.split(' ').map{_.toInt}.toVector
        var (a, b) = (0, 0)
        while (t.size > 2) (t.head, t.last) match {
            case (p, q) if p < q => {t = t.init.tail :+ (q - p); a = a + 1}
            case (p, q) if p > q => {t = (p - q) +: t.init.tail; b = b + 1}
            case _ => {t = t.init.tail; a = a + 1; b = b + 1}
        }
        a = a + 1
        if (t.size == 2) b = b + 1
        println(a + " " + b)
    }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val count = (1 to n).foldLeft(0, 0, 0){
    case((lIndex, lSum, rSum), _) if lSum <= rSum =>
      (lIndex + 1, lSum + data(lIndex), rSum)
    case((lIndex, lSum, rSum), i) =>
      (lIndex, lSum, rSum + data(n - i + lIndex))
  }._1
  println(s"$count ${n - count}")
}

import java.util.Scanner

object CAliceBob extends App {

  val scanner = new Scanner(System.in)

  val n = scanner.nextInt()

  val in = for (x <- 0 until n) yield scanner.next().toInt

  var a = 0
  var b = in.size - 1
  var as = 0
  var bs = 0

  while(a <= b) {
    if (as <= bs) {
      as += in(a)
      a += 1
    } else {
      bs += in(b)
      b -= 1
    }
  }

  println(a + " " + (in.size - a))

}

object C6 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    var arr = readInts(n)
    var a, x, y = 0
    var b = n-1
    while(a <= b) {
      if(x <= y) {
        x += arr(a)
        a += 1
      } else {
        y += arr(b)
        b -= 1
      }
    }
    println(s"$a ${n-a}")
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val count = (1 to n).foldLeft(-1, 0, 0){
    case((lIndex, lSum, rSum), _) if lSum <= rSum => (lIndex + 1, lSum + data(lIndex + 1), rSum)
    case((lIndex, lSum, rSum), _) => (lIndex, lSum, rSum + data(n - 1 - lIndex))
  }._1 + 1
  println(s"$count ${n - count}")
}

object P5E {
    def main(args: Array[String]) {
        val n = readLine.toInt
        val a = readLine split ' ' map {_.toInt}
        var answer = 0L
        for (a <- Array(a, a.reverse)) {
            case class Node(x : Int, i : Int, r : Int)
            val s = new java.util.ArrayDeque[Node]
            for (i <- 0 to n - 1) {
                val x = a(i)
                while (!s.isEmpty && s.getLast.x < x) s.removeLast
                val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0
                s addLast Node(x, i, r + 1)
            }
            for (i <- 0 to n - 1) yield {
                while (!s.isEmpty && s.getFirst.i <= i) s.removeFirst
                val x = a(i)
                while (!s.isEmpty && s.getLast.x < x) {
                    s.removeLast
                    answer = answer + 2
                }
                val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0
                answer = answer + (r min s.size)
                s addLast Node(x, n, r + 1)
            }
        }
        val v = {
            val a1 = a.max
            val z1 = a count {_ == a1}
            if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {
                val b = a filter {_ != a1}
                val a2 = b.max
                b count {_ == a2}
            }
        }
        println((answer >>> 1) - v)
    }
}


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

object _644C extends CodeForcesApp {
  override def apply(io: IO) = {
    val ans = io[Iterable[String]]
      .map(s => s.splitAt(s.indexOf('/', 7).nonNegative getOrElse s.length))
      .toMultiMap.mapValues(_.toSet).invert.values.filter(_.size > 1).toVector
    (io += ans.size).appendLine()
    ans.foreach(group => (io ++= group).appendLine())
    io
  }
}
/****************************[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](val t: Traversable[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: Traversable[A] = {
      val elems = mutable.Set.empty[A]
      t collect {case i if !elems.add(i) => i}
    }
    def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}
    def mapTo[B](f: 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
  }
  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 IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {
    def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s
  }
  implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))
    def swap: Traversable[(B, A)] = t.map(_.swap)
  }
  implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.swap.toMultiMap.mapValues(_.toSet)
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
  }
  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) //e.g. students.indexOf("Greg").nonNegative
  }
  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)
  }
  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
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.{Growable, CanBuild}

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with Growable[Any] {
  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 parse: IO.Parser[A]): A = parse.apply(this)
  def apply[C[_], A: IO.Parser](n: Int)(implicit builder: CanBuild[A, C[A]]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  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

  override def +=(obj: Any) = {
    if (isNewLine) isNewLine = false else print(separator)
    print(obj)
    this
  }
  def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t

  def appendLine(): this.type = {
    println()
    isNewLine = true
    this
  }

  override def clear() = flush()
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}

object IO {
  class Parser[A](val apply: IO => A) {
    def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
  }
  implicit def collection[C[_], A: Parser](implicit cbf: CanBuild[A, C[A]])  : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

object Solution{
  import scala.io.StdIn
  val url = "(http://[\\w\\.]+)(/?.*)".r

  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val groups = Vector.fill(n)(StdIn.readLine() match {
      case url(host, path) => (host, path)
    }).groupBy(_._1)
      .mapValues(_.map(_._2).toSet)
      .toVector
      .map(_.swap)
      .groupBy(_._1)
      .values
      .map(_ map (_._2))
      .filter(_.size > 1)

    println(groups.size)
    groups.foreach(srvs => println(srvs.mkString(" ")))
  }

}

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

  val Array(n) = readInts(1)

  case class Url(host: String, path: String)

  val urls = Array.fill(n) {
    val s = readLine.drop(7)
    val break = s.indexOf('/')
    if (break == -1) Url(s, "") else Url(s.take(break), s.drop(break))
  }.distinct

  val pathsByHosts = urls.groupBy(_.host).map {
    case (host, hotsUrls) => host -> hotsUrls.map(_.path).sorted.mkString(" ")
  }

  val hostsByPathSets = pathsByHosts.groupBy(_._2).map {
    case (paths, pathHosts) => pathHosts.keys
  }.filter(_.size > 1)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(hostsByPathSets.size)
  hostsByPathSets.foreach(hs => println(hs.map("http://" + _).mkString(" ")))
  Console.flush
}