Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:   +  ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.   -  ai — delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.  ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.

The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci — the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 ≤ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.

For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.

NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.   1 and 241.  361.  101 and 361.  361.  4000.

//package merofeev.contests.codeforces.rnd371

import java.util.Scanner

import scala.collection.mutable

/**
  * @author erofeev
  * @since 13.09.16
  */
object CMasks {

  class MyHashMap[A, B](initSize: Int) extends mutable.HashMap[A, B] {
    override def initialSize: Int = initSize // 16 - by default
  }

  def parseBits(i: String): Int = {
    var res = 0
    val irev: String = i.reverse
    for (elem <- irev.indices if irev.charAt(elem) == '1') {
      res |= 1 << elem
    }
    res
  }

  def oddBits(input: Long): Int = {
    var res = 0
    var i = input
    var delim = 0
    for (pos <- 0 to 18) {
      if ((i & 1) == 1) {
        res |= 1 << pos
      }
      i /= 10
    }
    res
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val masks = new Array[Int](1 << 19 + 2)
    var pos = 0
    while (in.hasNextLine) {
      val comm = in.nextLine().split(" ")
      if (comm(0) == "+") {
        val bits: Int = oddBits(comm(1).toLong)
        masks(bits) += 1
      } else if (comm(0) == "-") {
        val bits: Int = oddBits(comm(1).toLong)
        masks(bits) -= 1
      } else if (comm(0) == "?") {
        val bits: Int = parseBits(comm(1))
        println(masks(bits))
      }
      pos += 1
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  var map = Map.empty[String, Int]

  def stringToPattern(number: String): String = {
    val nNumber = "0" * (18 - number.length) + number
    nNumber.map(i => if (i.asDigit % 2 == 0) '0' else '1').mkString
  }

  val a = in.take(n).toList.foldLeft(List.empty[Int]) {
    case (ans, str) if str.startsWith("+") =>
      val pattern = stringToPattern(str.drop(2))
      map += pattern -> (map.getOrElse(pattern, 0) + 1)
      ans
    case (ans, str) if str.startsWith("-") =>
      val pattern = stringToPattern(str.drop(2))
      map += pattern -> (map.getOrElse(pattern, 0) - 1)
      ans
    case (ans, str) if str.startsWith("?") =>
      map.getOrElse(stringToPattern(str.drop(2)), 0) :: ans
  }
  println(a.reverse.mkString("\n"))
}

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

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 C371A(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 C371A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    val store = collection.mutable.HashMap[String, Int]()
    REP(t) { _ =>
      val c = nc()
      c match {
        case '+' =>
          val a = nl()
          val s = calculate(a)
          if(store.contains(s)) {
            store(s) = store(s) + 1
          } else store(s) = 1
        case '-' =>
          val a = nl()
          val s = calculate(a)
          if(store.contains(s)) {
            store(s) = store(s) - 1
          }
        case '?' =>
          val a = nl()
          val s = calculate(a)
          if(store.contains(s)) {
            out.println(store(s))
          } else out.println(0)
      }
    }
  }

  def calculate(n: Long): String = {
    var r = n
    val st = new StringBuilder()
    while (r > 0) {
      val x = r % 10
      st.append(x % 2)
      r /= 10
    }
    while (st.length < 19) {
      st.append("0")
    }
    st.reverse.toString()
  }
}

object CF3713B extends App{

  import scala.collection.mutable.HashMap
  import scala.io.StdIn.{ readLine, readInt }
  case class Query(s: String) {
    lazy val ss = s.split(" ")
    lazy val q = ss(0)
    lazy val value = ss(1)
    lazy val isQuery = q == "?"
    lazy val isPlus = q == "+"
    lazy val isMinus = q == "-"
    lazy val _hashed = value.toCharArray.map(x => x.toInt % 2).mkString("")
    lazy val hashed = _hashed.toLong
  }

  object Query {
    var memo = new HashMap[Long, Integer]

    def query(q: Query): Integer = {
      memo.getOrElse(q.value.toLong, 0)
    }

    def increment(q: Query): Unit = {
      val currentValue = memo.get(q.hashed)
      if(currentValue.isEmpty){
        memo.put(q.hashed, 1)
      }else{
        memo.update(q.hashed, currentValue.get + 1)
      }
    }

    def decrement(q: Query): Unit = {
      val currentValue = memo.get(q.hashed)
      memo.update(q.hashed, currentValue.get - 1)
    }

  }

  val n = readInt()
  0.to(n - 1).foreach(_ => {
    val s = readLine()
    val q = Query(s)
    if(q.isMinus){
      Query.decrement(q)
    }else if(q.isPlus){
      Query.increment(q)
    }else if(q.isQuery){
      println(Query.query(q))
    }
  })
}

import java.util

object CF3713B extends App{

  import scala.collection.mutable.HashMap
  import scala.io.StdIn.{ readLine, readInt }
  case class Query(s: String) {
    lazy val ss = s.split(" ")
    lazy val q = ss(0)
    lazy val value = ss(1)
    lazy val isQuery = q == "?"
    lazy val isPlus = q == "+"
    lazy val isMinus = q == "-"
    lazy val _hashed = value.toCharArray.map(x => x.toInt % 2).mkString("")
    lazy val hashed = _hashed.toLong
  }

  object Query {
    var memo = new HashMap[Long, Int]

    def query(q: Query): Int = {
      memo.getOrElse(q.value.toLong, 0)
    }

    def increment(q: Query): Unit = {
      val currentValue = memo.get(q.hashed)
      if(currentValue.isEmpty){
        memo.put(q.hashed, 1)
      }else{
        memo.update(q.hashed, currentValue.get + 1)
      }
    }

    def decrement(q: Query): Unit = {
      val currentValue = memo.get(q.hashed)
      memo.update(q.hashed, currentValue.get - 1)
    }

  }

  var buffer = new StringBuilder()
  val n = readInt()
  val fs = List("+ 200", "+ 100", "+ 401", "? 1", "? 0")
  0.to(n - 1).foreach(i => {
    val s = readLine()
    val q = Query(s)
    if(q.isMinus){
      Query.decrement(q)
    }else if(q.isPlus){
      Query.increment(q)
    }else if(q.isQuery){
      buffer.append(Query.query(q))
      buffer.append("\n")
    }
  })
  print(buffer.stripLineEnd.toString())
}

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

object _714C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}

    def hash(x: Long) = Integer.parseInt(x.toString.map(c => (((c - '0')%2) + '0').toChar), 2)

    val table = map[Int] to 0

    repeat(read[Int]) {
      val (c, x) = read[(Char, Long)]
      val h = hash(x)
      c match {
        case '+' => table(h) += 1
        case '-' => table(h) -= 1
        case '?' => write(table(h), '\n')
      }
    }

    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

import collection.mutable.HashMap;

object CF3713B extends App {
  val n = readLine.toInt
  val d = new HashMap[Long,Long]()
  for (i <- 0 until n) {
    val spl = readLine.split(" ")
    val m = spl(1).toLong
    val p = toBitsNumber(m)
    spl(0) match {
      case "+" => d += p -> (1L +d.getOrElse(p, 0L))
      case "-" => d += p -> (d(p) - 1)
      case "?" => println(d.getOrElse(m, 0))
    }
  }

  def toBitsNumber(n:Long) : Long = {
    var res : Long = 0
    var k : Long = 1
    var t : Long= n
    while (t > 0) {
      res += k*(t%2)
      k *= 10
      t /= 10
    }
    return res
  }
}

import java.util.Scanner
import scala.collection.mutable.Map

object Main{
  val map: Map[String, Int] = Map()

  def trans(s: String): String = {
    val res = s.toArray
    for(i <- 0 until res.length)
      if(res(i) % 2 == 0)
        res(i) = '0'
      else
        res(i) = '1'
    "0"*(18-res.length) + String.valueOf(res)
  }

  def transH(s: String): String = {
    "0"*(18-s.length) + s
  }

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

    for(k <- 1 to t){
      val c = sc.next(); val s = sc.next()
      if(c == "+"){
        val now = trans(s)
        if(map.contains(now))
          map(now) += 1
        else
          map += (now -> 1)
      }
      else if(c == "-"){
        val now = trans(s)
        map(now) -= 1
      }
      else{ // ?
        var ans = 0
        val hat = transH(s)
        println(map.getOrElse(hat, 0))
      }
    }
  }
}

object CF3713B extends App{

  import scala.collection.mutable.HashMap
  import scala.io.StdIn.{ readLine, readInt }
  case class Query(s: String) {
    lazy val ss = s.split(" ")
    lazy val q = ss(0)
    lazy val value = ss(1)
    lazy val isQuery = q == "?"
    lazy val isPlus = q == "+"
    lazy val isMinus = q == "-"
    lazy val _hashed = value.toCharArray.map(x => x.toInt % 2).mkString("")
    lazy val hashed = String.format("%1$18s", _hashed).replace(" ", "0")
  }

  object Query {
    var memo = new HashMap[String, Integer]

    def query(q: Query): Integer = {
      memo.getOrElse(q.hashed, 0)
    }

    def increment(q: Query): Unit = {
      val currentValue = memo.get(q.hashed)
      if(currentValue.isEmpty){
        memo.put(q.hashed, 1)
      }else{
        memo.update(q.hashed, currentValue.get + 1)
      }
    }

    def decrement(q: Query): Unit = {
      val currentValue = memo.get(q.hashed)
      memo.update(q.hashed, currentValue.get - 1)
    }

  }

  val n = readInt()
  0.to(n - 1).foreach(_ => {
    val s = readLine()
    val q = Query(s)
    if(q.isMinus){
      Query.decrement(q)
    }else if(q.isPlus){
      Query.increment(q)
    }else if(q.isQuery){
      print(Query.query(q))
    }
  })
}

import java.util

object CF3713B extends App{

  import scala.collection.mutable.HashMap
  import scala.io.StdIn.{ readLine, readInt }
  case class Query(s: String) {
    lazy val ss = s.split(" ")
    lazy val q = ss(0)
    lazy val value = ss(1)
    lazy val isQuery = q == "?"
    lazy val isPlus = q == "+"
    lazy val isMinus = q == "-"
    lazy val _hashed = value.toCharArray.map(x => x.toInt % 2).mkString("")
    lazy val hashed = _hashed.toLong
  }

  object Query {
    var memo = new HashMap[Long, Int]

    def query(q: Query): Int = {
      memo.getOrElse(q.value.toLong, 0)
    }

    def increment(q: Query): Unit = {
      val currentValue = memo.get(q.hashed)
      if(currentValue.isEmpty){
        memo.put(q.hashed, 1)
      }else{
        memo.update(q.hashed, currentValue.get + 1)
      }
    }

    def decrement(q: Query): Unit = {
      val currentValue = memo.get(q.hashed)
      memo.update(q.hashed, currentValue.get - 1)
    }

  }

  var buffer = new StringBuilder()
  // val n = readInt()
  val n = 5
  val fs = List("+ 200", "+ 100", "+ 401", "? 1", "? 0")
  0.to(n - 1).foreach(i => {
    // val s = readLine()
    val s = fs(i)
    val q = Query(s)
    if(q.isMinus){
      Query.decrement(q)
    }else if(q.isPlus){
      Query.increment(q)
    }else if(q.isQuery){
      buffer.append(Query.query(q))
      buffer.append("\n")
    }
  })
  print(buffer.stripLineEnd.toString())
}


It is the easy version of the problem. The only difference is that in this version $$$k = 3$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that:  $$$a_1 + a_2 + \ldots + a_k = n$$$  $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$  — the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 10^9$$$, $$$k = 3$$$).

For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.

import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val xs = readLine.split(' ').toList.map(x => x.toInt)
    val n = xs(0)
    val k = xs(1)
    val values = n match {
      case k if k % 2 == 1  => List(1, (k-1)/2, (k-1)/2)
      case k if k % 4 == 2  => List(2, (k-2)/2, (k-2)/2)
      case k if k % 4 == 0 =>  List(k/4, k/4, k/2)
    }
    println(values.map(x => x.toString()).mkString(" "))
  }
}

import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val xs = readLine.split(' ').toList.map(x => x.toInt)
    val n = xs(0)
    val k = xs(1)
    val values = n match {
      case k if k % 2 == 1  => List(1, (k-1)/2, (k-1)/2)
      case k if k % 4 == 2  => List(2, (k-2)/2, (k-2)/2)
      case k if k % 4 == 0 =>  List(k/4, k/4, k/2)
    }
    println(values)
  }
}


You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers:  exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks).  exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively.

For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.

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

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    // Write your solution here
    val t = readInt
    for (_ <- 0 until t) {
      val line = readLine.split(" ").map(_.toLong)
      val (x, y, k) = (line(0), line(1), line(2))
      println(((y + 1) * k - 1 + x - 2) / (x - 1) + k)
    }
  }
}

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

import scala.io.StdIn._

object Main {
  def g(x: Long, y: Long, k: Long): Long = {
    /*
    need k coals
    k coals = y * k sticks
    do stick exchange until you have >= k + y * k
    then add k coal exchanges
     */
    val sticks = BigInt(1)
    val limit = BigInt(k) + BigInt(y) * BigInt(k)

    val countDec: BigDecimal = BigDecimal(limit - sticks) / BigDecimal(-sticks + BigInt(x))
    var count: BigInt = if (countDec.isValidLong) countDec.toBigInt else
    countDec.toBigInt + BigInt(1)

    count += BigInt(k)
    count.toLong

  }

  def main(args: Array[String]): Unit = {
    // Write your solution here
    val t = readInt
    for (_ <- 0 until t) {
      val line = readLine.split(" ").map(_.toLong)
      val (x, y, k) = (line(0), line(1), line(2))
      println(g(x, y, k))
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x, y, k) = readLine().split(" ").map(_.toLong)

    val ans = 1 + k + (k * (y + 1) - 2) / (x - 1)

    println(ans)
  }
}

import scala.io.StdIn._

object task1 extends App {
  val sets = readInt

  //var lst: List[Long] = List()
  (1 to sets).foreach { _ =>
    val xyk = readLine.split(" ").map(_.toInt)
    val x = xyk(0)
    val y = xyk(1)
    val k = xyk(2)
    val sticks = k + k.toLong*y
    //println("Sticks needed " + sticks)
    val rem =(sticks - 1) % (x - 1)
    val steps = if (rem == 0)
        (sticks - 1) /  (x - 1) + k
      else
        (sticks - 1 - rem) / (x - 1) + k + 1

   // println("We get those with " + (steps- xyk(2) ))
    //println(s"And additional ${xyk(2)} to get coal")
    //println()

    //lst = lst ::: List(steps)
    println(steps)

  }
  //lst.foreach { x =>
   //println(f"$x%1.0f")
  //  println(x)
 // }

}
/*
1000000000
1000000000
1000000000 + 1000000000*1000000000

1000000001999999999

 */

import scala.collection.mutable.ArrayBuffer

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

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

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

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

    inputLines.times {
      val x = in.nextInt()
      val y = in.nextInt()
      val k = in.nextInt()

      val totalSticks = (y.toLong * k) + k - 1
      val roundTem    = totalSticks / (x - 1)

      val round = if (totalSticks - (roundTem * (x - 1)) > 0) roundTem + 1 else roundTem

      println(round + k)
    }
  }

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

  /**
    * Util methods
    */

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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

import scala.io.StdIn._

object taskA extends App {
  val sets = readInt

  var lst: List[Int] = List()
  (1 to sets).foreach { _ =>
    val xyk = readLine.split(" ").map(_.toInt)
    val sticks = xyk(2) + xyk(1)*xyk(2)
    //println("Sticks needed " + sticks)
    val steps = (sticks - 1).toFloat / (xyk(0) - 1) match {
      case x if x % 1 > 0 => x + 1 - (x % 1) + xyk(2)
      case x => x + xyk(2)
    }
    //println("We get those with " + (steps- xyk(2) ))
    //println(s"And additional ${xyk(2)} to get coal")

    lst = lst ::: List(steps.toInt)

  }
  lst.foreach { x =>
    println(x)
  }

}

import scala.io.StdIn._

object task1 extends App {
  val sets = readInt

  var lst: List[Long] = List()
  (1 to sets).foreach { _ =>
    val xyk = readLine.split(" ").map(_.toInt)
    val sticks = xyk(2) + xyk(2).toLong*xyk(1)
    //println("Sticks needed " + sticks)
    val steps =(sticks - 1) % (xyk(0) - 1) match {
      case 0 => {
       // println("0")
       // println(sticks-1, ", ", (sticks), ", ")
        (sticks - 1) /  (xyk(0) - 1) + xyk(2)
      }
      case x => {
        println(x)
        (sticks - 1 - x) / (xyk(0) - 1) + xyk(2) + 1
      }
    }
   // println("We get those with " + (steps- xyk(2) ))
    //println(s"And additional ${xyk(2)} to get coal")
    //println()

    lst = lst ::: List(steps)

  }
  lst.foreach { x =>
   //println(f"$x%1.0f")
    println(x)
  }

}
/*
1000000000
1000000000
1000000000 + 1000000000*1000000000

1000000001999999999

 */

import scala.io.StdIn._

object task1 extends App {
  val sets = readInt

  var lst: List[Double] = List()
  (1 to sets).foreach { _ =>
    val xyk = readLine.split(" ").map(_.toInt)
    val sticks = xyk(2) + xyk(1).toDouble*xyk(2)
   // println("Sticks needed " + sticks)
    val steps = ((sticks - 1) % (xyk(0) - 1)) match {
      case 0 => (sticks - 1) /  (xyk(0) - 1) + xyk(2)
      case x => (sticks - 1-x) /  (xyk(0) - 1) + xyk(2) + 1
    }
    //println("We get those with " + (steps- xyk(2) ))
   // println(s"And additional ${xyk(2)} to get coal")
    //println()

    lst = lst ::: List(steps.toDouble)

  }
  lst.foreach { x =>
   println(f"$x%1.0f")
  }

}
/*
1000000000
1000000000
1000000000 + 1000000000*1000000000

1000000001999999999

 */

import scala.io.StdIn._

object taskA extends App {
  val sets = readInt

  var lst: List[Int] = List()
  (1 to sets).foreach { _ =>
    val xyk = readLine.split(" ").map(_.toInt)
    val sticks = xyk(2) + xyk(1)*xyk(2)
    println("Sticks needed " + sticks)
    val steps = (sticks - 1).toFloat / (xyk(0) - 1) match {
      case x if x % 1 > 0 => x + 1 - (x % 1) + xyk(2)
      case x => x + xyk(2)
    }
    println("We get those with " + (steps- xyk(2) ))
    println(s"And additional ${xyk(2)} to get coal")

    lst = lst ::: List(steps.toInt)

  }
  lst.foreach { x =>
    println(x)
  }

}


A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled: An example of such a bar can be seen on the picture.  For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.

We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).

Print n numbers. The i-th of them should be equal to ai.

object P71B extends App {
  val Array(n, k, t) = readLine().split(" ").map(_.toInt)
  val c = (n * t / 100.0)
  print((k + " ") * c.toInt + (((c - c.toInt.toFloat) * k).toInt + " ") * (if (t < 100) 1 else 0) +
    "0 " * (n - c.toInt - 1))
}

object P71B extends App {
  val Array(n,k,t) = readLine.split(" ").map(_.toInt)
  val p = (n * t / 100.0)
  val c = p.toInt
  val r = p - c.toFloat
  print((k + " ") * c + (if (r*k > 0 || t == 0) (r*k).toInt + " " else "") + ("0 " * (n-c-1)))
}

object P71B extends App {

  val Array(n,k,t) = readLine.split(" ").map(_.toInt)

  val p = (n * t / 100.0)
  val c = p.toInt
  val r = p - c.toFloat

  print((k + " ") * c + (r*k).toInt + " " + ("0 " * (n-c-1)))

}

object P71B extends App {

  val Array(n,k,t) = readLine.split(" ").map(_.toInt)

  val c = (n * t / 100.0).toInt

  print((k + " ") * c + "1 " + ("0 " * (n-c-1)))

}

object P71B extends App {

  val Array(n,k,t) = readLine.split(" ").map(_.toInt)

  val c = (n * t / 100.0).toInt

  print((k + " ") * c) + "1 " + ("0 " * (n-c-1))

}

object P71B extends App {
  val Array(n,k,t) = readLine.split(" ").map(_.toInt)
  val p = (n * t / 100.0)
  val c = p.toInt
  val r = p - c.toFloat
  print((k + " ") * c + (if (r*k > 0) (r*k).toInt + " " else "") + ("0 " * (n-c-1)))
}

object P71B extends App {
  val Array(n,k,t) = readLine.split(" ").map(_.toInt)
  val p = (n * t / 100.0)
  val c = p.toInt
  val r = p - c.toFloat
  print((k + " ") * c + (if (r*k > 0) (r*k).toInt + " ") + ("0 " * (n-c-1)))
}


A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black.You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0, 0, 0, 1, 1, 1, 0, 0, 0] can be a photo of zebra, while the photo [0, 0, 0, 1, 1, 1, 1] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not?

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the width of the photo. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 1) — the description of the photo. If ai is zero, the i-th column is all black. If ai is one, then the i-th column is all white.

If the photo can be a photo of zebra, print "YES" (without quotes). Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteThe first two examples are described in the statements.In the third example all pixels are white, so the photo can be a photo of zebra.In the fourth example the width of the first stripe is equal to three (white color), the width of the second stripe is equal to three (black), and the width of the third stripe is equal to two (white). Thus, not all stripes have equal length, so this photo is not a photo of zebra.

object c extends App {
  import scala.io.StdIn._
  val n: Int = Integer.parseInt(readLine())
  val a: Array[Int] = readLine().split(" ").map(Integer.parseInt(_))

  var len: Int = 0
  for (i <- 0 until n) {
    val j: Int = i-1
    if (i > 0 && a(i) != a(j)) {
      len = 0
    }
    len += 1
  }

  var cur: Int = 1
  var bad = false
  for (i <- 1 until n) {
    val j: Int = i-1
    if (a(i) != a(j)) {
      if (cur != len) {
        bad = true
      }
      cur = 1
    } else {
      cur += 1
    }
  }

  if (cur != len || bad) {
    println("NO")
  } else {
    println("YES")
  }
}

import scala.io.StdIn.readInt
object task {
  def main(args: Array[String]): Unit = {
  var n = readInt()
  var arr = new Array[Int](n+1);
  arr = (readLine().+(" 1")).split(" ").map(_.toInt)
  arr(n) = arr(n-1)^1
  var pol = arr(0)
  var it = 0
  while(it<n&&arr(it)==pol){
    it = it + 1
  }
  if (it == n){
    println("YES")
    System.exit(0)
  }
  val size = it
  //println(size)
  var begin = it
  var end = 0
  pol = arr(it)
  for (i <- it to n){
    if (!(arr(i)==pol)){
      end = i
      if (end - begin!=size){
        println("NO")
        //printf("end is %d\nbegin is %d\n" ,end,begin)
        //println(pol)
        //println(i)
        System.exit(0)
      }else{
        //printf("stroke at %d",i)
        pol = arr(i)
        end = i
        begin = i
      }
    }
  }
  println("YES")
  }
}

object CF928A extends App {

  var n = scala.io.StdIn.readInt()
  var s = scala.io.StdIn.readLine()
 var checkPoints = s.split(" ")

  var z = 0
  var count = -1
  var f = 1

  while (z < n)
  {
	var cnt = 0
	var cur = checkPoints(z)

	while (z < n && checkPoints(z) == cur)
	{
		z = z+1
		cnt = cnt+1
	}

	if (count >= 0 && cnt != count)
	{
		f = 0

	}

	count = cnt
  }

	if (f == 0) println("NO") else println("YES")
}

object Main extends App {
 var a = 0
 var b = 0
 val Array(n) = readLine.split(" ").map(_.toLong)
 var s = readLine.split(" ").map(_.toLong)
 if (s(s.size - 1) == 0) {
     s = s :+ 1.toLong
 } else {
     s = s :+ 0.toLong
 }
 var c = s(0)
 var l = 0
 for (i <- s) {
     if (i == c) {
         l = l + 1
     } else {
         if (i == 0) {
             if (a == 0) {
                 a = l
             } else {
                 if (a != l) {
                     println("NO")
                     System.exit(0)
                 }
             }
         }
        if (i == 1) {
             if (b == 0) {
                 b = l
             } else {
                 if (b != l) {
                     println("NO")
                     System.exit(0)
                 }
             }
         }
         l = 1
         if (a != 0 && b != 0) {
             if (a != b) {
                 println("NO")
                 System.exit(0)
             }
         }
     }
     c = i
 }
 println("YES")

}


You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1 ≤ i, j ≤ n). In other words, let's consider all n2 pairs of numbers, picked from the given array.For example, in sequence a = {3, 1, 5} are 9 pairs of numbers: (3, 3), (3, 1), (3, 5), (1, 3), (1, 1), (1, 5), (5, 3), (5, 1), (5, 5).Let's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair (p1, q1) is lexicographically less than pair (p2, q2) only if either p1 < p2, or p1 = p2 and q1 < q2.Then the sequence, mentioned above, will be sorted like that: (1, 1), (1, 3), (1, 5), (3, 1), (3, 3), (3, 5), (5, 1), (5, 3), (5, 5)Let's number all the pair in the sorted list from 1 to n2. Your task is formulated like this: you should find the k-th pair in the ordered list of all possible pairs of the array you've been given.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ n2). The second line contains the array containing n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). The numbers in the array can coincide. All numbers are separated with spaces. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout, streams or the %I64d specificator instead.

In the single line print two numbers — the sought k-th pair.

NoteIn the first sample the sorted sequence for the given array looks as: (1, 1), (1, 2), (2, 1), (2, 2). The 4-th of them is pair (2, 2).The sorted sequence for the array from the second sample is given in the statement. The 2-nd pair there is (1, 3).

//package round111.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 08.03.12
 * Time: 6:54
 * To change this template use File | Settings | File Templates.
 */

object C {
  def main(args: Array[String]) = {
    var Array(n, k) = readLine() split ' ' map (_.toLong)
    k -= 1
    var cur = new Counter(0, 0, -100L)
    val nums = (readLine() split ' ' map (_ toLong) sortWith ((a, b) => (a compareTo b) < 0))
    val count = {
      val counts = nums flatMap (x =>
        if (x == cur.content) {
          cur.size += 1
          Nil
        } else {
          cur = new Counter(cur.start + cur.size, 1, x)
          List(cur)
        })
      counts find (count => k < count.end * n && k >= count.start * n) match {
        case None => {
          println((counts.size, n, counts(0).start, counts(0).end, counts(0).content, counts(0).size))
          new Counter(0, 0, 0L)
        }
        case Some(x) => x
      }
    }
    val first = count.content
    val second = nums(((k - n * count.start) / count.size) toInt)

    val pair = first :: second :: Nil mkString " "

    println(pair)
  }

  class Counter[T](var start: Int, var size: Int, val content: T) {
    def end = start + size
  }

}

//package round111.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 08.03.12
 * Time: 6:54
 * To change this template use File | Settings | File Templates.
 */

object C {
  def main(args: Array[String]) = {
    var Array(n, k) = readLine() split ' ' map (_.toLong)
    k -= 1
    var cur = new Counter[Option[Long]](0, 0, None)
    val nums = (readLine() split ' ' map (_ toLong) sorted)
    val count = {
      val counts = nums flatMap (x =>
        if (Some(x) == cur.content) {
          cur.size += 1
          Nil
        } else {
          cur = new Counter(cur.start + cur.size, 1, Some(x))
          List(cur)
        })
      counts find (count => k < count.end * n && k >= count.start * n) match {
        case None => {
          println((counts.size, n, counts(0).start, counts(0).end, counts(0).content, counts(0).size))
          new Counter(0, 0, None)
        }
        case Some(x) => x
      }
    }
    val first = count.content.get
    val second = nums(((k - n * count.start) / count.size) toInt)

    val pair = first :: second :: Nil mkString " "

    println(pair)
  }

  class Counter[T](var start: Int, var size: Int, val content: T) {
    def end = start + size
  }

}

//package round111.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 08.03.12
 * Time: 6:54
 * To change this template use File | Settings | File Templates.
 */

object C {
  def main(args: Array[String]) = {
    var Array(n, k) = readLine() split ' ' map (_.toLong)
    k -= 1
    var cur = new Counter(0, 0, -100L)
    val nums = (readLine() split ' ' map (_ toLong) sorted)
    val count = {
      val counts = nums flatMap (x =>
        if (x == cur.content) {
          cur.size += 1
          Nil
        } else {
          cur = new Counter(cur.start + cur.size, 1, x)
          List(cur)
        })
      counts find (count => k < count.end * n && k >= count.start * n) match {
        case None => {
          println((counts.size, n, counts(0).start, counts(0).end, counts(0).content, counts(0).size))
          new Counter(0, 0, 0L)
        }
        case Some(x) => x
      }
    }
    val first = count.content
    val second = nums(((k - n * count.start) / count.size) toInt)

    val pair = first :: second :: Nil mkString " "

    println(pair)
  }

  class Counter[T](var start: Int, var size: Int, val content: T) {
    def end = start + size
  }

}

//package round111.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 08.03.12
 * Time: 6:54
 * To change this template use File | Settings | File Templates.
 */

object C {
  val Array(n, k) = readLine() split ' ' map (_.toLong)
  val nums = readLine() split ' ' map (_ toInt) sorted
  val pair = (k - 1) / n :: (k - 1) % n :: Nil map (x => nums(x.toInt)) mkString " "

  def main(args: Array[String]) = println(pair)

}


There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and:  Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$.  Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.

For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).

NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.

//package codeforces.contests._1433

object YetAnotherBookshelf {

  import scala.annotation.tailrec

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val n = io.StdIn.readInt()

      val digits = io.StdIn.readLine.split(" ").map(_.toInt)

      @tailrec
      def loop(ls: List[Int], acc: List[Int] = Nil): List[Int] = {
        if (ls.isEmpty) acc else {
          val afterOnesDropped = ls.dropWhile(_ == 1)
          if (afterOnesDropped.isEmpty) acc else {
            val (zeroes, afterZeroesDropped) = afterOnesDropped.span(_ == 0)
            if (afterZeroesDropped.isEmpty) acc else {
              loop(afterZeroesDropped, zeroes.length :: acc)
            }
          }
        }
      }

      val zeroesInThMiddle = loop(digits.toList.dropWhile(_ == 0))

      println {
        zeroesInThMiddle.sum
      }
    }
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Your task is to say the number of such positive integers $$$x$$$ such that $$$x$$$ divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.For example, if the array $$$a$$$ will be $$$[2, 4, 6, 2, 10]$$$, then $$$1$$$ and $$$2$$$ divide each number from the array (so the answer for this test is $$$2$$$).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 4 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{12}$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the number of such positive integers $$$x$$$ such that $$$x$$$ divides each number from the given array (in other words, the answer is the number of common divisors of all elements in the array).

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

  override def apply(io: IO): io.type = {
    val input = io.read[Set[Long]]
    val g = input.reduce(gcd)
    io.write(countDivisors(g))
  }

  def countDivisors(n: Long) = {
    val divisors = mutable.Set.empty[Long]
    for {
      i <- 1 to sqrt(n.toDouble).toInt
      if n%i == 0
    } {
      divisors += i.toLong
      divisors += n/i
    }
    divisors.size
  }

  @tailrec def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)
}
/****************************[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 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
      }
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val input = io.read[Set[Long]]
    val g = input.reduce(gcd)
    io.write(countDivisors(g))
  }

  def countDivisors(n: Long) = {
    val divisors = mutable.Set.empty[Long]
    for {
      i <- 1 to sqrt(n.toDouble).toInt
      if n%i == 0
    } {
      divisors += i.toLong
      divisors += n/i
    }
    divisors.size
  }

  @tailrec def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)

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

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

  override def apply(io: IO): io.type = {
    val input = io.read[Set[Long]]
    val g = input.reduce(gcd)
    io.write(countDivisors(g))
  }

  def countDivisors(n: Long) = {
    val divisors = mutable.Set.empty[Long]
    for {
      i <- 1 to sqrt(n.toDouble).toInt
      if n%i == 0
    } {
      divisors += i.toLong
      divisors += n/i
    }
    divisors.size
  }

  @tailrec def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)
}
/****************************[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
      }
    }
  }
}

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

  override def apply(io: IO) = {
    val input = io.read[Set[Long]]
    val g = input.reduce(gcd)
    io.write(countDivisors(g))
  }

  def countDivisors(n: Long) = {
    val divisors = mutable.Set.empty[Long]
    for {
      i <- 1 to sqrt(n.toDouble).toInt
      if n%i == 0
    } {
      divisors += i.toLong
      divisors += n/i
    }
    divisors.size
  }

  @tailrec def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)
}
/****************************[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): Any
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out))
}
/***********************************[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
      }
    }
  }
}


One day n friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together. Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them occupies the rectangle of width wi pixels and height hi pixels. On the group photo everybody stands in a line, thus the minimum pixel size of the photo including all the photographed friends, is W × H, where W is the total sum of all widths and H is the maximum height of all the photographed friends.As is usually the case, the friends made n photos — the j-th (1 ≤ j ≤ n) photo had everybody except for the j-th friend as he was the photographer.Print the minimum size of each made photo in pixels.

The first line contains integer n (2 ≤ n ≤ 200 000) — the number of friends.  Then n lines follow: the i-th line contains information about the i-th friend. The line contains a pair of integers wi, hi (1 ≤ wi ≤ 10, 1 ≤ hi ≤ 1000) — the width and height in pixels of the corresponding rectangle.

Print n space-separated numbers b1, b2, ..., bn, where bi — the total number of pixels on the minimum photo containing all friends expect for the i-th one.

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main4 extends App with IOUtils {
  val n = nextInt
  val whs = (1 to n).map { i =>
    nextIntPair
  }

  val sum = whs.map(_._1).sum

  val (maxHeight, secondMaxHeight) = whs.toStream.map(_._2).foldLeft((0, 0)) { (p, x) =>
    if (x > p._1)
      (x, p._1)
    else if (x > p._2)
      (p._1, x)
    else
      (p._1, p._2)
  }

  println(whs.map { case (w, h) =>
    (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)
  }.mkString(" "))
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main4 extends App with IOUtils {
  val n = nextInt
  val whs = (1 to n).map { i =>
    nextIntPair
  }

  val sum = whs.map(_._1).sum

  val (maxHeight, secondMaxHeight) = whs.foldLeft((0, 0)) { (p, x) =>
    if (x._2 > p._1)
      (x._2, p._1)
    else if (x._2 > p._2)
      (p._1, x._2)
    else
      (p._1, p._2)
  }

  println(whs.map { case (w, h) =>
    (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)
  }.mkString(" "))
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main4 extends App with IOUtils {
  val n = nextInt
  val whs = (1 to n).map { i =>
    nextIntPair
  }

  val sum = whs.map(_._1).sum

  val (maxHeight, secondMaxHeight) = whs.view.map(_._2).foldLeft((0, 0)) { (p, x) =>
    if (x > p._1)
      (x, p._1)
    else if (x > p._2)
      (p._1, x)
    else
      (p._1, p._2)
  }

  println(whs.map { case (w, h) =>
    (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)
  }.mkString(" "))
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main4 extends App with IOUtils {
  val n = nextInt
  val (ws, hs) = (1 to n).map { i =>
    nextIntPair
  }.unzip

  val sum = ws.sum

  val (maxHeight, secondMaxHeight) = hs.foldLeft((0, 0)) { (p, x) =>
    if (x > p._1)
      (x, p._1)
    else if (x > p._2)
      (p._1, x)
    else
      (p._1, p._2)
  }

  println((ws zip hs).map { case (w, h) =>
    (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)
  }.mkString(" "))
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main4 extends App with IOUtils {
  val n = nextInt
  val whs = (1 to n).map { i =>
    nextIntPair
  }

  val sum = whs.map(_._1).sum

  val (maxHeight, secondMaxHeight) = whs.map(_._2).foldLeft((0, 0)) { (p, x) =>
    if (x > p._1)
      (x, p._1)
    else if (x > p._2)
      (p._1, x)
    else
      (p._1, p._2)
  }

  println(whs.map { case (w, h) =>
    (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)
  }.mkString(" "))
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main4 extends App with IOUtils {
  val n = nextInt
  val whs = (1 to n).map { i =>
    nextIntPair
  }

  val sum = whs.view.map(_._1).sum

  val (maxHeight, secondMaxHeight) = whs.view.map(_._2).foldLeft((0, 0)) { (p, x) =>
    if (x > p._1)
      (x, p._1)
    else if (x > p._2)
      (p._1, x)
    else
      (p._1, p._2)
  }

  println(whs.map { case (w, h) =>
    (sum - w) * (if (h < maxHeight) maxHeight else secondMaxHeight)
  }.mkString(" "))
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

object B522 extends App {

  val n   = readInt
  val inp =
    (1 to n)
    .map(_ => readLine.split(" ").map(_.toInt))

  val w = inp.map(x => x(0))
  val h = inp.map(x => x(1))

  val isum = w.sum
  val sm = inp.map(x => isum - x(0))

  val max1 = h.max
  val max2 = {if (h.count(_ == max1) > 1) max1 else h.filter(_ != max1 ).max}

  (1 to n).foreach(i => print(sm(i - 1) * {if (h(i - 1) == max1) max2 else max1} + " "))
}

/**
 * Created by yangchaozhong on 3/11/15.
 */
object CF522B extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val w = Array.ofDim[Int](n)
    val h = Array.ofDim[Int](n)

    var sumW = 0
    var maxH = 0
    (0 until n).foreach { i =>
      w(i) = nextInt
      h(i) = nextInt
      sumW += w(i)
      if (h(i) > maxH)
        maxH = h(i)
    }

    var secondH = 0
    var maxTimes = 0
    (0 until n).foreach { i =>
      if (h(i) > secondH && h(i) != maxH) {
        secondH = h(i)
      }

      if (h(i) == maxH)
        maxTimes += 1
    }

    if (maxTimes > 1)
      secondH = maxH

    val res = (0 until n).map { i =>
      val width = sumW - w(i)
      if (h(i) == maxH) {
        width * secondH
      } else {
        width * maxH
      }
    }.mkString(" ")

    out.println(res)
  }

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

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

import scala.collection.mutable

object B {

  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 java.lang.Long.parseLong(next)
  }

  class MultiTreeSet[T <: Comparable[T]] {
    val map = new util.TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  def solve: Int = {
    val n = nextInt
    val friends = new Array[(Int, Int)](n)
    var W = 0
    val H = new MultiTreeSet[Integer]()
    for (i <- 0 until n) {
      friends(i) = (nextInt, nextInt)
      W += friends(i)._1
      H.add(friends(i)._2)
    }
    for (i <- 0 until n) {
      val minW = W - friends(i)._1
      H.remove(friends(i)._2)
      var minH = 0
      minH = H.last
      H.add(friends(i)._2)
      out.print(minW.toLong * minH.toLong + " ")
    }
    return 1
  }

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

/**
 * Created by yangchaozhong on 3/11/15.
 */
object CF522B extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val w = Array.ofDim[Int](n)
    val h = Array.ofDim[Int](n)

    var sumW = 0
    var maxH = 0
    var secondH = 0
    (0 until n).foreach { i =>
      w(i) = nextInt
      h(i) = nextInt
      sumW += w(i)
      if (h(i) > maxH)
        maxH = h(i)
      if (h(i) > secondH && h(i) < maxH)
        secondH = h(i)
    }

    if (secondH == 0)
      secondH = maxH

    val res = (0 until n).map { i =>
      val width = sumW - w(i)
      if (h(i) == maxH) {
        width * secondH
      } else {
        width * maxH
      }
    }.mkString(" ")

    out.println(res)
  }

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

/**
 * Created by yangchaozhong on 3/11/15.
 */
object CF522B extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val w = Array.ofDim[Int](n)
    val h = Array.ofDim[Int](n)

    var sumW = 0
    var maxH = 0
    var secondH = 0
    (0 until n).foreach { i =>
      w(i) = nextInt
      h(i) = nextInt
      sumW += w(i)
      if (h(i) > maxH)
        maxH = h(i)
      if (h(i) > secondH && h(i) < maxH)
        secondH = h(i)
    }

    val res = (0 until n).map { i =>
      val width = sumW - w(i)
      if (h(i) == maxH) {
        width * secondH
      } else {
        width * maxH
      }
    }.mkString(" ")

    out.println(res)
  }

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

/**
 * Created by yangchaozhong on 3/11/15.
 */
object CF522B extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val w = Array.ofDim[Int](n)
    val h = Array.ofDim[Int](n)

    var sumW = 0
    var maxH = 0
    (0 until n).foreach { i =>
      w(i) = nextInt
      h(i) = nextInt
      sumW += w(i)
      if (h(i) > maxH)
        maxH = h(i)
    }

    var secondH = 0
    (0 until n).foreach { i =>
      if (h(i) > secondH && h(i) != maxH) {
        secondH = h(i)
      }
    }

    val res = (0 until n).map { i =>
      val width = sumW - w(i)
      if (h(i) == maxH) {
        width * secondH
      } else {
        width * maxH
      }
    }.mkString(" ")

    out.println(res)
  }

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

/**
 * Created by yangchaozhong on 3/11/15.
 */
object CF522B extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val w = Array.ofDim[Int](n)
    val h = Array.ofDim[Int](n)

    var sumW = 0
    var maxH = 0
    (0 until n).foreach { i =>
      w(i) = nextInt
      h(i) = nextInt
      sumW += w(i)
      if (h(i) > maxH)
        maxH = h(i)
    }

    var secondH = 0
    (0 until n).foreach { i =>
      if (h(i) > secondH && h(i) != maxH) {
        secondH = h(i)
      }
    }

    if (secondH == 0)
      secondH = maxH

    val res = (0 until n).map { i =>
      val width = sumW - w(i)
      if (h(i) == maxH) {
        width * secondH
      } else {
        width * maxH
      }
    }.mkString(" ")

    out.println(res)
  }

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

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

import scala.collection.mutable

object B {

  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 java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val friends = new Array[(Int, Int)](n)
    var W = 0
    var H = mutable.TreeSet[Int]()
    for (i <- 0 until n) {
      friends(i) = (nextInt, nextInt)
      W += friends(i)._1
      H += friends(i)._2
    }
    for (i <- 0 until n) {
      val minW = W - friends(i)._1
      H -= friends(i)._2
      var minH = 0
      if (H.size == 0) {
        minH = friends(i)._2
      } else {
        minH = H.last
      }
      H += friends(i)._2
      out.print(minW.toLong * minH.toLong + " ")
    }
    return 1
  }

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