A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj.A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.You are to compute the prices each buyer will pay for t-shirts.

The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≤ pi ≤ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers.  The following line contains sequence c1, c2, ..., cm (1 ≤ cj ≤ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served.

Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.

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

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


There are $$$n$$$ people sitting in a circle, numbered from $$$1$$$ to $$$n$$$ in the order in which they are seated. That is, for all $$$i$$$ from $$$1$$$ to $$$n-1$$$, the people with id $$$i$$$ and $$$i+1$$$ are adjacent. People with id $$$n$$$ and $$$1$$$ are adjacent as well.The person with id $$$1$$$ initially has a ball. He picks a positive integer $$$k$$$ at most $$$n$$$, and passes the ball to his $$$k$$$-th neighbour in the direction of increasing ids, that person passes the ball to his $$$k$$$-th neighbour in the same direction, and so on until the person with the id $$$1$$$ gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if $$$n = 6$$$ and $$$k = 4$$$, the ball is passed in order $$$[1, 5, 3, 1]$$$. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $$$1 + 5 + 3 = 9$$$.Find and report the set of possible fun values for all choices of positive integer $$$k$$$. It can be shown that under the constraints of the problem, the ball always gets back to the $$$1$$$-st player after finitely many steps, and there are no more than $$$10^5$$$ possible fun values for given $$$n$$$.

The only line consists of a single integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number of people playing with the ball.

Suppose the set of all fun values is $$$f_1, f_2, \dots, f_m$$$. Output a single line containing $$$m$$$ space separated integers $$$f_1$$$ through $$$f_m$$$ in increasing order.

NoteIn the first sample, we've already shown that picking $$$k = 4$$$ yields fun value $$$9$$$, as does $$$k = 2$$$. Picking $$$k = 6$$$ results in fun value of $$$1$$$. For $$$k = 3$$$ we get fun value $$$5$$$ and with $$$k = 1$$$ or $$$k = 5$$$ we get $$$21$$$.   In the second sample, the values $$$1$$$, $$$10$$$, $$$28$$$, $$$64$$$ and $$$136$$$ are achieved for instance for $$$k = 16$$$, $$$8$$$, $$$4$$$, $$$10$$$ and $$$11$$$, respectively.

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


A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\dots,p_n]$$$, which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) and, moreover, each number appears exactly once. For example, $$$p=[3,1,4,2,5]$$$ is a permutation of length $$$5$$$.For a given number $$$n$$$ ($$$n \ge 2$$$), find a permutation $$$p$$$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $$$2$$$ and $$$4$$$, inclusive. Formally, find such permutation $$$p$$$ that $$$2 \le |p_i - p_{i+1}| \le 4$$$ for each $$$i$$$ ($$$1 \le i < n$$$).Print any such permutation for the given integer $$$n$$$ or determine that it does not exist.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is described by a single line containing an integer $$$n$$$ ($$$2 \le n \le 1000$$$).

Print $$$t$$$ lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -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
   }
}

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


Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.

The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.

In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.

NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.

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

  val Array(n, a, b, k) = readInts(4)
  val shotAt = readLine
  val shootAt = new mutable.ArrayBuilder.ofInt

  var i = 0
  var lastShotAt = -1
  val shotsMade = 0
  while (i < n) {
    if (shotAt(i) == '1') lastShotAt = i
    else {
      if (i - lastShotAt == b) {
        lastShotAt = i
        shootAt += i + 1
      }
    }
    i += 1
  }

  val mustShootAt = shootAt.result.drop(a - 1)

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

  println(mustShootAt.length)
  println(mustShootAt.mkString(" "))

  Console.flush
}


Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $$$a$$$ vanilla cookies and $$$b$$$ chocolate cookies for the party.She invited $$$n$$$ guests of the first type and $$$m$$$ guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type:If there are $$$v$$$ vanilla cookies and $$$c$$$ chocolate cookies at the moment, when the guest comes, then  if the guest of the first type: if $$$v>c$$$ the guest selects a vanilla cookie. Otherwise, the guest selects a chocolate cookie.  if the guest of the second type: if $$$v>c$$$ the guest selects a chocolate cookie. Otherwise, the guest selects a vanilla cookie. After that:  If there is at least one cookie of the selected type, the guest eats one.  Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home. Anna wants to know if there exists some order of guests, such that no one guest gets angry. Your task is to answer her question.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains four integers $$$a$$$, $$$b$$$, $$$n$$$, $$$m$$$ ($$$0 \le a,b,n,m \le 10^{18}, n+m \neq 0$$$).

For each test case, print the answer in one line. If there exists at least one valid order, print "Yes". Otherwise, print "No". You can print each letter in any case (upper or lower).

NoteIn the first test case, let's consider the order $$$\{1, 2, 2\}$$$ of types of guests. Then:  The first guest eats a chocolate cookie. After that, there are $$$2$$$ vanilla cookies and $$$1$$$ chocolate cookie.  The second guest eats a chocolate cookie. After that, there are $$$2$$$ vanilla cookies and $$$0$$$ chocolate cookies.  The last guest selects a chocolate cookie, but there are no chocolate cookies. So, the guest gets angry. So, this order can't be chosen by Anna.Let's consider the order $$$\{2, 2, 1\}$$$ of types of guests. Then:  The first guest eats a vanilla cookie. After that, there is $$$1$$$ vanilla cookie and $$$2$$$ chocolate cookies.  The second guest eats a vanilla cookie. After that, there are $$$0$$$ vanilla cookies and $$$2$$$ chocolate cookies.  The last guest eats a chocolate cookie. After that, there are $$$0$$$ vanilla cookies and $$$1$$$ chocolate cookie. So, the answer to this test case is "Yes".In the fifth test case, it is illustrated, that the number of cookies ($$$a + b$$$) can be equal to zero, but the number of guests ($$$n + m$$$) can't be equal to zero.In the sixth test case, be careful about the overflow of $$$32$$$-bit integer type.

import scala.io.StdIn._

object C extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val Array(a, b, n, m) = readLine().split(" ").map(_.toLong)
    if (m > Math.min(a, b) || n + m > a + b) println("NO")
    else println("YES")
  }
}


Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.It takes the first swimmer exactly $$$a$$$ minutes to swim across the entire pool and come back, exactly $$$b$$$ minutes for the second swimmer and $$$c$$$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $$$0$$$, $$$a$$$, $$$2a$$$, $$$3a$$$, ... minutes after the start time, the second one will be at $$$0$$$, $$$b$$$, $$$2b$$$, $$$3b$$$, ... minutes, and the third one will be on the left side of the pool after $$$0$$$, $$$c$$$, $$$2c$$$, $$$3c$$$, ... minutes.You came to the left side of the pool exactly $$$p$$$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contains test case descriptions, one per line. Each line contains four integers $$$p$$$, $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \leq p, a, b, c \leq 10^{18}$$$), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.

For each test case, output one integer — how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.

NoteIn the first test case, the first swimmer is on the left side in $$$0, 5, 10, 15, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 4, 8, 12, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 8, 16, 24, \ldots$$$ minutes after the start time. You arrived at the pool in $$$9$$$ minutes after the start time and in a minute you will meet the first swimmer on the left side.In the second test case, the first swimmer is on the left side in $$$0, 6, 12, 18, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 10, 20, 30, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$2$$$ minutes after the start time and after $$$4$$$ minutes meet the first swimmer on the left side.In the third test case, you came to the pool $$$10$$$ minutes after the start time. At the same time, all three swimmers are on the left side. A rare stroke of luck!In the fourth test case, all swimmers are located on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$10$$$ minutes after the start time and after $$$8$$$ minutes meet all three swimmers on the left side.

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

  }

}


The city Valera lives in is going to hold elections to the city Parliament.The city has n districts and n - 1 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired.There are n candidates running the elections. Let's enumerate all candidates in some way by integers from 1 to n, inclusive. If the candidate number i will be elected in the city Parliament, he will perform exactly one promise — to repair all problem roads on the way from the i-th district to the district 1, where the city Parliament is located.Help Valera and determine the subset of candidates such that if all candidates from the subset will be elected to the city Parliament, all problem roads in the city will be repaired. If there are several such subsets, you should choose the subset consisting of the minimum number of candidates.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of districts in the city. Then n - 1 lines follow. Each line contains the description of a city road as three positive integers xi, yi, ti (1 ≤ xi, yi ≤ n, 1 ≤ ti ≤ 2) — the districts connected by the i-th bidirectional road and the road type. If ti equals to one, then the i-th road isn't the problem road; if ti equals to two, then the i-th road is the problem road. It's guaranteed that the graph structure of the city is a tree.

In the first line print a single non-negative number k — the minimum size of the required subset of candidates. Then on the second line print k space-separated integers a1, a2, ... ak — the numbers of the candidates that form the required subset. If there are multiple solutions, you are allowed to print any of them.

//package codeforces

import java.util

/**
 * ToDo: describe
 *
 * @author keks
 */
object T369C {
  def main(args: Array[String]) {
    val n = readInt()
    val a = new Array[List[(Int, Int)]](n)
    for (i <- 1 until n) {
      val map = readLine().split(' ').map(_.toInt)
      a(map(0) - 1) = (map(1) - 1, map(2)) :: (if (a(map(0) - 1) == null) Nil else a(map(0) - 1))
      a(map(1) - 1) = (map(0) - 1, map(2)) :: (if (a(map(1) - 1) == null) Nil else a(map(1) - 1))
    }

    val elections = getMinElections(a)
    println(elections.length + "\n" + elections.mkString(" "))
  }

  def getMinElections(a: Array[List[(Int, Int)]]) = {
    val nodes = new util.Stack[(Int, Int)]()
    val isBads = new util.Stack[Int]()
    val isUps = new util.Stack[Int]()

    val visited = new java.util.HashSet[Int]()
    val list = new util.LinkedList[Int]()

    // 1 - gather, 2 - check
    nodes.push((0, 1))
    isBads.push(1)
    isUps.push(0)

    while (!nodes.isEmpty) {
      val e = nodes.pop()
      val isUp = isUps.pop()
      if (e._2 == 1) {
        visited.add(e._1)
        nodes.push((e._1, 2))
        isUps.push(list.size)
        val adj = a(e._1)
        if (adj != null) {
          adj.filter(p => !visited.contains(p._1)).map(p => {
            nodes.push((p._1, 1))
            isUps.push(list.size)
            isBads.push(p._2)
          })
        }
      } else {
        val isBad = isBads.pop()
        if (isUp == list.size && isBad == 2) list.add(e._1 + 1)
      }
    }

    list.toArray
  }
}

//package codeforces

import java.util

/**
 * ToDo: describe
 *
 * @author keks
 */
object T369C {
  def main(args: Array[String]) {
    val n = readInt()
    val a = new Array[List[(Int, Int)]](n)
    for (i <- 1 until n) {
      val map = readLine().split(' ').map(_.toInt)
      a(map(0) - 1) = (map(1) - 1, map(2)) :: (if (a(map(0) - 1) == null) Nil else a(map(0) - 1))
      a(map(1) - 1) = (map(0) - 1, map(2)) :: (if (a(map(1) - 1) == null) Nil else a(map(1) - 1))
    }

    val elections = getMinElections(a)
    println(elections.length + "\n" + elections.mkString(" "))
  }

  def getMinElections(a: Array[List[(Int, Int)]]) = {
    val nodes = new util.Stack[(Int, Int)]()
    val isBads = new util.Stack[Int]()
    val isUps = new util.Stack[Int]()

    val visited = new java.util.HashSet[Int]()
    val list = new util.LinkedList[Int]()

    // 1 - gather, 2 - check
    nodes.push((0, 1))
    isBads.push(1)
    isUps.push(0)

    while (!nodes.isEmpty) {
      val e = nodes.pop()
      val isUp = isUps.pop()
      if (e._2 == 1) {
        visited.add(e._1)
        nodes.push((e._1, 2))
        isUps.push(list.size)
        val adj = a(e._1)
        if (adj != null) {
          adj.filter(p => !visited.contains(p._1)).map(p => {
            nodes.push((p._1, 1))
            isUps.push(list.size)
            isBads.push(p._2)
          })
        }
      } else {
        val isBad = isBads.pop()
        if (isUp != list.size) isBads.push(2) else if (isBad == 2) list.add(e._1 + 1)
      }
    }

    list.toArray
  }
}

//package codeforces

import java.util

/**
 * ToDo: describe
 *
 * @author keks
 */
object T369C {
  def main(args: Array[String]) {
    val n = readInt()
    val a = new Array[List[(Int, Int)]](n)
    for (i <- 1 until n) {
      val map = readLine().split(' ').map(_.toInt)
      a(map(0) - 1) = (map(1) - 1, map(2)) :: (if (a(map(0) - 1) == null) Nil else a(map(0) - 1))
    }

    val elections = getMinElections(a)
    println(elections.length)
    print(elections.mkString(" "))
  }

  def getMinElections(a: Array[List[(Int, Int)]]) = {
    val nodes = new util.Stack[(Int, Int)]()
    val isBads = new util.Stack[Int]()
    val isUps = new util.Stack[Int]()

    var elections = List[Int]()

    // 1 - gather, 2 - check
    nodes.push((0, 1))
    isBads.push(1)
    isUps.push(0)

    while (!nodes.isEmpty) {
      val e = nodes.pop()
      val isUp = isUps.pop()
      if (e._2 == 1) {
        nodes.push((e._1, 2))
        isUps.push(elections.size)
        val adj = a(e._1)
        if (adj != null) {
          adj.map(p => {
            nodes.push((p._1, 1))
            isUps.push(elections.size)
            isBads.push(p._2)
          })
        }
      } else {
        val isBad = isBads.pop()
        if (isUp != elections.size) isBads.push(2) else if (isBad == 2) elections = (e._1 + 1) :: elections
      }
    }

    elections
  }
}


Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "di → ti", that means "replace all digits di in string s with substrings equal to ti". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("replace 3 by an empty string") transforms it to s = 1212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to s by 1000000007 (109 + 7). When you represent s as a decimal number, please ignore the leading zeroes; also if s is an empty string, then it's assumed that the number equals to zero.Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!

The first line contains string s (1 ≤ |s| ≤ 105), consisting of digits — the string before processing all the requests. The second line contains a single integer n (0 ≤ n ≤ 105) — the number of queries. The next n lines contain the descriptions of the queries. The i-th query is described by string "di->ti", where di is exactly one digit (from 0 to 9), ti is a string consisting of digits (ti can be an empty string). The sum of lengths of ti for all queries doesn't exceed 105. The queries are written in the order in which they need to be performed.

Print a single integer — remainder of division of the resulting number by 1000000007 (109 + 7).

NoteNote that the leading zeroes are not removed from string s after the replacement (you can see it in the third sample).

/**
 * Created by Bo You on 2014/9/8.
 */
object Main {

  def input(): (String, List[String]) = {
    val s = readLine()
    val n = readLine().toInt
    var rule = List[String]()
    for (i <- 1 to n) {
      rule = rule.+:(readLine())
    }
    return (s, rule)
  }

  def solve(s: String, rule: List[String]): Long = {

    val MOD = 1000000007
    val D = 10

    def modAdd(x: Int, y: Int): Int = {
      return (x + y) % MOD;
    }
    def modMultiply(x: Int, y: Int): Int = {
      return ((x.toLong * y) % MOD).toInt
    }
    def iter(h: Array[Int], p10: Array[Int], rem: List[String]): (Array[Int], Array[Int]) = {
      def parse(r: String): (Int, Array[Int]) = {
        return (r(0) - '0', r.takeRight(r.length - 3).map(_ - '0').toArray)
      }
      def evaluate(np10: Int, nh: Int, pos: Int, r: Array[Int], p10: Array[Int], h: Array[Int]): (Int, Int) = {
        if (pos == r.length) {
          return (np10, nh)
        } else {
          val d = r(pos)
          return evaluate(modMultiply(np10, p10(d)), modAdd(modMultiply(nh, p10(d)), h(d)), pos + 1, r, p10, h)
        }
      }
      if (rem.isEmpty) {
        return (h, p10)
      } else {
        val (src, dst) = parse(rem.head)
        val (np10, nh) = evaluate(1, 0, 0, dst, p10, h)
        h.update(src, nh)
        p10.update(src, np10)
        return iter(h, p10, rem.tail)
      }
    }

    val (h, p10) = iter((0 to D - 1).toArray, (0 to D - 1).map(_ => 10).toArray, rule)
    var ret = 0L
    for (ch <- s) {
      val d = ch - '0'
      ret = (ret * p10(d) + h(d)) % MOD
    }
    return ret

  }

  def main(args: Array[String]) {
    val (s, rule) = input()
    println(solve(s, rule))
  }

}


String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not.You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.

The input consists of two lines. The first line contains string s, the second line contains string t. The strings have the same length (from 1 to 105 characters) and consist of uppercase English letters.

In the first line print z — the minimum number of replacement operations, needed to get an anagram of string t from string s. In the second line print the lexicographically minimum anagram that could be obtained in z operations.

NoteThe second sample has eight anagrams of string t, that can be obtained from string s by replacing exactly two letters: "ADBADC", "ADDABC", "CDAABD", "CDBAAD", "CDBADA", "CDDABA", "DDAABC", "DDBAAC". These anagrams are listed in the lexicographical order. The lexicographically minimum anagram is "ADBADC".

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

    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では駄目*/
    }

}


Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the grid. Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur:    "." — an empty cell;  "*" — a cell with road works;  "S" — the cell where Igor's home is located;  "T" — the cell where Igor's office is located.  It is guaranteed that "S" and "T" appear exactly once each.

In the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.

NoteThe first sample is shown on the following picture:  In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture:

import io.StdIn.readLine

object B1 extends App {
  val Array(n, m) = readLine.split(' ').map(_.toInt)

  def find(xx: Array[Array[Char]], char: Char): (Int, Int) =
    xx.indices.flatMap { i =>
      val j = xx(i).indexOf(char)
      if (j < 0) None else Some((i, j))
    }.head

  def line(s: Array[Char], in: Int): Range = {
    val end = s.drop(in + 1).prefixLength(c => c != '*')
    val start = s.take(in).view.reverse.prefixLength(c => c != '*')
    (in - start) to (in + end)
  }

  def search(xx: Array[Array[Char]]): Boolean = {
    val (sx, sy) = find(xx, 'S')
    val (tx, ty) = find(xx, 'T')
    val searchIn = line(xx(sx), sy) intersect line(xx(tx), ty)
    searchIn.exists(j => sx.min(tx) to sx.max(tx) forall (i => xx(i)(j) != '*'))
  }

  val ss = Array.fill(n)(readLine.toCharArray)

  println(if (search(ss) || search(ss.transpose)) "YES" else "NO")
}


The Fair Nut likes kvass very much. On his birthday parents presented him $$$n$$$ kegs of kvass. There are $$$v_i$$$ liters of kvass in the $$$i$$$-th keg. Each keg has a lever. You can pour your glass by exactly $$$1$$$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $$$s$$$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $$$s$$$ liters of kvass.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le s \le 10^{12}$$$) — the number of kegs and glass volume. The second line contains $$$n$$$ integers $$$v_1, v_2, \ldots, v_n$$$ ($$$1 \le v_i \le 10^9$$$) — the volume of $$$i$$$-th keg.

If the Fair Nut cannot pour his glass by $$$s$$$ liters of kvass, print $$$-1$$$. Otherwise, print a single integer — how much kvass in the least keg can be.

NoteIn the first example, the answer is $$$3$$$, the Fair Nut can take $$$1$$$ liter from the first keg and $$$2$$$ liters from the third keg. There are $$$3$$$ liters of kvass in each keg.In the second example, the answer is $$$2$$$, the Fair Nut can take $$$3$$$ liters from the first keg and $$$1$$$ liter from the second keg.In the third example, the Fair Nut can't pour his cup by $$$7$$$ liters, so the answer is $$$-1$$$.

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


You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.Given the list of strings, output the lexicographically smallest concatenation.

The first line contains integer n — the number of strings (1 ≤ n ≤ 5·104). Each of the next n lines contains one string ai (1 ≤ |ai| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·104.

Print the only string a — the lexicographically smallest string concatenation.

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

/**
  * Created by whimsy on 16/7/17.
  */

object P632C extends App {
    val n = StdIn.readInt()

    var ab = ArrayBuffer[String]()
    for (i <- 0 until n) ab += StdIn.readLine()
    val answer = ab.sortWith((a, b) => a + b < b + a)
        .foldLeft(new StringBuffer())((z, i) => z.append(i))

    println(answer)

}


This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions:   The length of $$$t$$$ does not exceed the length of $$$s$$$.  $$$t$$$ is a palindrome.  There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( "$$$+$$$" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$5000$$$.

For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.

5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba

NoteIn the first test, the string $$$s = $$$"a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because:  Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$.  It is a palindrome.  "abcdfdcba" $$$=$$$ "abcdfdc" $$$+$$$ "ba", and "abcdfdc" is a prefix of $$$s$$$ while "ba" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" $$$=$$$ "c" $$$+$$$ "" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is "s".

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


Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?

The first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequence t1, t2, ..., tn (1 ≤ ti ≤ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).

Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.

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

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