Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.

First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.

If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.

NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.

object A extends App {
  def protect(p: Array[Array[Char]], r: Int, c: Int): Boolean = {
    for (i <- 0 until r)
      for (j <- 0 until c)
        if (p(i)(j) == 'S') {
          if (
            p(i)(0 max (j - 1)) == 'W' ||
            p(i)((c - 1) min (j + 1)) == 'W' ||
            p(0 max (i - 1))(j) == 'W' ||
            p((r - 1) min (i + 1))(j) == 'W'
          ) {
            return false
          }
          else {
            if (p(i)(0 max (j - 1)) == '.') p(i)(0 max (j - 1)) = 'D'
            if (p(i)((c - 1) min (j + 1)) == '.') p(i)((c - 1) min (j + 1)) = 'D'
            if (p(0 max (i - 1))(j) == '.') p(0 max (i - 1))(j) = 'D'
            if (p((r - 1) min (i + 1))(j) == '.') p((r - 1) min (i + 1))(j) = 'D'
          }
        }
    true
  }

  val Array(r, c) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val p = Array.fill(r)(new Array[Char](c))
  for (i <- 0 until r) {
    val line = scala.io.StdIn.readLine()
    for (j <- 0 until c)
      p(i)(j) = line(j)
  }

  val s = protect(p, r, c)
  if (s) {
    println("Yes")
    println(p.map(_.mkString("")).mkString("\n"))
  } else println("No")

}

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

  override def apply(io: IO): io.type = {
    val r, c = io.read[Int]
    val pasture = io.read[Vector, String](r).map(_.replace('.', 'D'))

    def isWolf(i: Int)(j: Int) = pasture.lift(i).flatMap(_.lift(j)).contains('W')

    val ans = (0 until r) X (0 until c) find { case (i, j) =>
      pasture(i)(j) == 'S' && (isWolf(i-1)(j) || isWolf(i+1)(j) || isWolf(i)(j-1) || isWolf(i)(j+1))
    }

    io.write(if(ans.isDefined) "No" else pasture.mkString("Yes\n", "\n", ""))
  }
}
/****************************[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}
  type Point = java.awt.geom.Point2D.Double
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(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 = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(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]).withDefaultValue(b().result())
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    //def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 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 getBit(i: Int): Long = (x >> i) & 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 Point(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 isPrime(n: Int): Boolean = BigInt(n).isProbablePrime(31)
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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


User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below.  At first, the score is 0.  For each block of contiguous "o"s with length x the score increases by x2.  For each block of contiguous "x"s with length y the score decreases by y2.   For example, if a = 6, b = 3 and ainta have arranged the cards in the order, that is described by string "ooxoooxxo", the score of the deck equals 22 - 12 + 32 - 22 + 12 = 9. That is because the deck has 5 blocks in total: "oo", "x", "ooo", "xx", "o".User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards.

The first line contains two space-separated integers a and b (0 ≤ a, b ≤ 105; a + b ≥ 1) — the number of "o" cards and the number of "x" cards.

In the first line print a single integer v — the maximum score that ainta can obtain. In the second line print a + b characters describing the deck. If the k-th card of the deck contains "o", the k-th character must be "o". If the k-th card of the deck contains "x", the k-th character must be "x". The number of "o" characters must be equal to a, and the number of "x " characters must be equal to b. If there are many ways to maximize v, print any. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

import java.util
import scala.collection.mutable.ArrayBuffer

object Main {
  var tokenizer = new util.StringTokenizer("")

  def readToken() = {
    while (!tokenizer.hasMoreTokens) tokenizer = new java.util.StringTokenizer(readLine)
    tokenizer.nextToken
  }

  val a = readToken.toInt
  val b = readToken.toInt
  var bestA, bestB = 0
  var bestVal: Long = -(1L << 60)

  def getBestA(n: Int): Long = {
    val head = a - n + 1
    head.toLong * head + n - 1
  }

  def getBestB(n: Int): Long = {
    val small = (b / n).toLong
    val big = small + 1
    val bigCount = b % n
    val smallCount = n - bigCount
    big * big * bigCount + small * small * smallCount
  }

  def genAnswerString() = {
    val s = new StringBuilder
    val head = a - bestA + 1
    val small = b / bestB
    val big = small + 1
    val bigCount = b % bestB

    var i = 0
    var j = 0
    var flag = 0
    if (bestB > bestA) flag = 1

    while (i < bestA || j < bestB) {
      flag match {
        case 0 =>
          if (i == 0) {
            s ++= "o" * head
          } else {
            s += 'o'
          }
          i += 1
        case 1 =>
          if (j < bigCount) {
            s ++= "x" * big
          } else {
            s ++= "x" * small
          }
          j += 1
      }
      flag = 1 - flag
    }
    s
  }

  def check(i: Int, j: Int) {
    if (1 <= j && j <= b) {
      val v = getBestA(i) - getBestB(j)
      //println(i, j, v)
      if (v > bestVal) {
        bestVal = v
        bestA = i
        bestB = j
      }
    }
  }

  def main(args: Array[String]) {
    if (a == 0) {
      println(-b.toLong * b)
      println("x" * b)
      return
    }

    if (b == 0) {
      println(a.toLong * a)
      println("o" * a)
      return
    }

    for (i <- 1 to a) {
      check(i, i - 1)
      check(i, i)
      check(i, i + 1)
    }
    println(bestVal)
    println(genAnswerString)
  }
}

import java.util

object Main {
  def main(args: Array[String]) {
    val a = Array(10, 20)
    val b = Array(100, 200)
    println(a ++ b)
  }

  var st = new util.StringTokenizer("")
  def readToken() = {
    while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)
    st.nextToken
  }
}


Given an integer $$$n$$$, find the maximum value of integer $$$k$$$ such that the following condition holds:  $$$n$$$ & ($$$n-1$$$) & ($$$n-2$$$) & ($$$n-3$$$) & ... ($$$k$$$) = $$$0$$$  where & denotes the bitwise AND operation.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, output a single integer — the required integer $$$k$$$.

NoteIn the first testcase, the maximum value for which the continuous & operation gives 0 value, is 1.In the second testcase, the maximum value for which the continuous & operation gives 0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0.   $$$5 \, \& \, 4 \neq 0$$$,  $$$5 \, \& \, 4 \, \& \, 3 = 0$$$. Hence, 3 is the answer.

import scala.annotation.tailrec
import scala.io.StdIn
object CF1527A {
    def main(args: Array[String]): Unit = {
        val t = StdIn.readInt
        val list = List.fill(t)(0).map(_ => StdIn.readInt);
        @tailrec
        def bitLength(i: Int = 0, n: Int): Int = {
            if (n < 2) i
            else bitLength(i + 1, n / 2);
        }
        val bl: (Int => Int) = bitLength(0, _)
        @tailrec
        def bitMax(i: Int, acc: Int = 1): Int = {
            if (i <= 0) acc
            else bitMax(i - 1, acc * 2);
        }
        val bm: (Int => Int) = bitMax(_, 1) - 1
        println(list.map(bl).map(bm).mkString("\n"))
    }
}


The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.The Berland capital's map is represented by an n × m rectangular table. Each cell of the table on the map represents some districts of the capital. The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map. Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.

The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 100) — the number of rows and columns in the table, correspondingly. Each of the next n lines contains m characters — the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".". It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements.

Print two integers — the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.

object SeriesofCrimes181A  extends App {

    import java.io.{InputStream, PrintStream}
    import java.util.Scanner
    solve(System.in,System.out)
    def solve(in: InputStream, out: PrintStream): Unit = {
        val scanner = new Scanner(in)
      val n = scanner.nextInt()
      val m = scanner.nextInt()

      val city = (1 to n).map(_ => scanner.next).toArray

      val rowOnly1Asterisk = (city.zipWithIndex filter {case (s,_) => s.filter(_ == '*').length==1}).head._2 + 1
      val rowsWithAsterisk = city.filter(_.filter(_ == '*').length>=1)
      val row1 = rowsWithAsterisk.head
      val row2 = rowsWithAsterisk.tail.head

      val colOnly1Asterisk = row1.zip(row2).zipWithIndex.filter{
        case (('*','.'),_) => true
        case (('.','*'),_) => true
        case _ => false

      }.head._2 + 1
      out.println(s"$rowOnly1Asterisk $colOnly1Asterisk")

    }
}


Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.

The first line contains two integers n and m — the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1 ≤ a, b ≤ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.

Print the single number — the number of groups of students that will be kicked out from the club.

NoteIn the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = Array.fill[List[Int]](n){Nil}
  (1 to m).foreach { _ =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    data(a) ::= b
    data(b) ::= a
  }
  var zero = data.indices.filter(i => data(i).length == 1)
  var i = 0
  while (zero.nonEmpty) {
    i += 1
    zero.foreach {j =>
      data(j).foreach { k => data(k) = data(k).filter(_ != j)}
      data(j) = Nil
    }
    zero = data.indices.filter(i => data(i).length == 1)
  }
  println(i)

}

object StudentsAndShoelaces129B extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val m = scanner.nextInt()
    val nodes = (1 to n).map(Node)
    val edges = (1 to m).map{ _ =>
      val a = nodes(scanner.nextInt()-1)
      val b = nodes(scanner.nextInt()-1)
      UndirectedEdge(a,b)
    }
    val g = new Graph(nodes,edges)

    def findNumGroups(graph: Graph): Int = {
      val badGuys = graph.findBadGuys()
      if(badGuys.isEmpty)
        0
      else 1 + findNumGroups(graph.kickBadGuys(badGuys))
    }

    out.println(findNumGroups(g))

  }
  class Graph(val nodes: Seq[Node],val edges: Seq[UndirectedEdge]){
    val mapNeighbours = nodes.map(n => n -> edges.filter(e => e.a == n || e.b==n).map{case UndirectedEdge(a,b) => if(a==n) b else a}).toMap
    def findBadGuys(): Seq[Node] =  mapNeighbours.filter{case (_,neighbours) => neighbours.length == 1}.keys.toSeq
    def kickBadGuys(badGuys: Seq[Node]): Graph = {
      val goodGuys = nodes.filterNot(n => badGuys.contains(n))
      val newEdges = edges.filterNot{case UndirectedEdge(a,b) => badGuys.contains(a) || badGuys.contains(b)}
      new Graph(goodGuys,newEdges)
    }

  }
  case class Node(node: Int)
  case class UndirectedEdge(a: Node, b: Node)
}


Given a string $$$s$$$ of length $$$n$$$ and integer $$$k$$$ ($$$1 \le k \le n$$$). The string $$$s$$$ has a level $$$x$$$, if $$$x$$$ is largest non-negative integer, such that it's possible to find in $$$s$$$:  $$$x$$$ non-intersecting (non-overlapping) substrings of length $$$k$$$,  all characters of these $$$x$$$ substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings). A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$), denoted as $$$s[i \dots j]$$$ = "$$$s_{i}s_{i+1} \dots s_{j}$$$".For example, if $$$k = 2$$$, then:  the string "aabb" has level $$$1$$$ (you can select substring "aa"),  the strings "zzzz" and "zzbzz" has level $$$2$$$ (you can select two non-intersecting substrings "zz" in each of them),  the strings "abed" and "aca" have level $$$0$$$ (you can't find at least one substring of the length $$$k=2$$$ containing the only distinct character). Zuhair gave you the integer $$$k$$$ and the string $$$s$$$ of length $$$n$$$. You need to find $$$x$$$, the level of the string $$$s$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the value of $$$k$$$. The second line contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.

Print a single integer $$$x$$$ — the level of the string.

NoteIn the first example, we can select $$$2$$$ non-intersecting substrings consisting of letter 'a': "(aa)ac(aa)bb", so the level is $$$2$$$.In the second example, we can select either substring "a" or "b" to get the answer $$$1$$$.

import scala.collection.mutable

object Problem_1105B {
  // Salem and Sticks

  def main(args: Array[String]) {
    val scan = scala.io.StdIn

    //Get inputs
    val inputs: Array[Int] = scan.readLine().split(" ").map(_.toInt)
    val targetArr: String = scan.readLine()
    val n = inputs(0)
    val k = inputs(1)
    val occMap = Array.fill(256)(0)

    var x = 0
    while (x < n - k + 1) {
      val tempChar = targetArr(x)
      if (targetArr.substring(x, x + k).count(_ == tempChar) == k) {
        occMap(tempChar) += 1
        x += k
      }
      else{
        while(targetArr(x) == targetArr(x+1)){
          x+=1
        }
        x+=1
      }

    }
    val ans = occMap.max
    println(ans)
  }

}

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val S = ns(N)

    var ans = 0
    REP(26) { i =>
      val c = 'a' + i
      var cnt = 0
      var lvl = 0
      REP(N) { j =>
        if (S(j) == c) {
          cnt += 1
          if (cnt == K) {
            cnt = 0
            lvl += 1
          }
        } else {
          cnt = 0
        }
      }
      ans = max(ans, lvl)
    }

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn

object ZahirGame {

  def main(args: Array[String]): Unit = {
    val k = StdIn.readLine().split(" ").tail.head.toInt
    val in = StdIn.readLine()

    def step(acc : (List[Char], Int), c: Char): (List[Char], Int) = acc match {
      case (Nil, _) => (List(c), 1)
      case (l, n) if l.head == c || n == 0 => (c :: l, n + 1)
      case (l, n) => (c :: l.drop(n % k), 1)
    }

    val (resWithLast, residue) = in.foldLeft[(List[Char], Int)]((List(), 0))(step)
    val res = resWithLast.drop(residue % k).sorted.foldLeft[Map[Char, Int]](Map()) { (acc, c) =>
      acc + (c -> (acc.getOrElse(c, 0) + 1))
    }
    println(if (res.isEmpty) 0 else res.values.max / k)
  }
}


One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.

The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.

Print a single integer — the number of problems the friends will implement on the contest.

NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution.

object Main {
  def main(args: Array[String]): Unit = {
    val n = readLine.toInt
    var sum = 0
    var i = 0
    while(i < n) {
      val Array(m, n, d) = readLine.split(" ").map(_.toInt)
//      println(m +","+ n +","+ d)
      if(m + n + d >= 2) sum = sum + 1
      i = i + 1
    }
    println(sum)
  }
}

import scala.io.StdIn._

object CF_231A_Team {
  def main(args: Array[String]): Unit = {
    println((for (i <- 1 to readInt) yield readLine().split(" ").map(_.toInt).sum >= 2).count(_ == true))
  }
}

import scala.io.StdIn

object  Test {
  def main(args1: Array[String]) {
//    val args = StdIn.readLine().split(" ")
//    var (x: Long, y: Long) = (args(0).toLong, args(1).toLong)

    val count = StdIn.readInt

    var ret = 0L
    for (i <- 0 until count) {
      val a = StdIn.readLine().split(" ")
      val sum = a.filter(s => s.equals("1")).length
      if (sum > 1) {
        ret += 1
      }
    }
    println(ret)
  }

}

object TwoThreeOneA {
	def main(args : Array[String]) : Unit = {
		var sol=0
		var n=readInt
		for(i<-0 until n){
			var ones=readLine.split(' ').count(_=="1")
			if(ones>1){
				sol+=1
			}
		}
		println(sol)
	}
}

import scala.io.StdIn._

object Team {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val problems =
      for {
        _ <- 0 until n
        x = readLine().split(" ").map(_.toInt).reduce(_ + _)
      } yield x
    val ans = problems.filter(_ > 1).length
    println(ans)
  }
}

object CF231A extends App {
    import scala.io.StdIn.readLine
    val n = readLine.toInt
    var count=0
    for (_ <- 1 to n) {
      if (readLine.split(" ").map(_.toInt).count(x => x > 0)>1)
        count+=1
    }
    print(count)
}

object Team extends App{

    val probNum = scala.io.StdIn.readInt()

    var solutions = 0

    for (x <- 1 to probNum) {
        val confLvl = scala.io.StdIn.readLine().split(" ").map(k => k.toInt)
        if (confLvl.sum >= 2) solutions += 1
        else solutions

        //confLvl.sum

    }

    println(solutions)
}

object Team extends App{

    val probNum = scala.io.StdIn.readInt()

    val confLvl = for (i <- 1 to probNum) yield {
        if (scala.io.StdIn.readLine().split(" ").map(k => k.toInt).sum >= 2) 1
        else 0
    }

    println(confLvl.sum)
}

object TaskA231 {
  def main(args: Array[String]): Unit = {
    val n = scala.io.StdIn.readInt
    var l = List[String]()
    for (i <- 0 until n) l = scala.io.StdIn.readLine :: l
    println(l.count(_.count(_ == '1') >= 2))
  }
}

object CF0231A extends App {

  val n = readInt()

  var count = 0

  (1 to n).foreach(v => {

    val str = readLine().split(" ").map(_.toInt).filter(_>0).size
    if (str >= 2) count += 1
  })

  println(count)

}

object task231A {
  def main(args:Array[String]) {
    var rv:Int=0;
    for (l <- io.Source.stdin.getLines.toList.drop(1)) {
      val Array(a,b,c)=l.split(" ").map(_.toInt)
      if (a+b+c>1) { rv+=1; }
    }
    println(rv)
  }
}

object pratise {
    def main(args : Array[String]) {
        val n = readInt
        val res = (1 to n).count(_ => readLine().split(" ").map(_.toInt).sum>1)
        println(res)
    }
}

object cf extends App{
  val t = readInt()
  var res = 0
  for (i <- 0 to t-1) {
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)
    val r = a+b+c
    if (r > 1) res += 1
  }
  println(res)
}

import scala.io.StdIn.readLine
object Solution {
    def reduceMembers(s: Iterable[Array[Int]]) = s map (_ reduceLeft (_ + _))
    def reduceProblems(s: Iterable[Int]) = s count (_ >= 2)
    def readLines(n: Int) = Iterator.continually(readLine).take(n).toIterable
    def main(args: Array[String]) = {
        val n = readLine.toInt
        val problemMembers = readLines(n) map (_ split " " map (_.toInt))
        println(reduceProblems(reduceMembers(problemMembers)))
    }
}

object Solution231A extends App {

  def solution() {
    val n = _int
    val res = 1.to(n).map(_ => _int + _int + _int).filter(i => i > 1).size
    println(res)
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

object Competition extends App {

  import scala.io.StdIn._

  val k = readInt()

  def input(n: Int)= (1 to n).map(_ => readLine().split(" ").toSeq).toSeq

  def sumUp(seq: Seq[String]) = seq.map(Integer.parseInt).sum

  println(input(k).map(sumUp).count(_ > 1))
}

object Cf231A extends App {
  val n = readInt()
  var res = 0
  for (i <- 1 to n) {
    res = res + (if (readLine.split(" ").map(_.toInt).sum >= 2) 1 else 0)
  }
  println(res)
}

object A extends App {
    import scala.io.StdIn._
    val n = readInt
    var i = 0
    var t = 0
    for (i <- 0 until n) {
        val x = (readLine().split(' ')).map(_.toInt)
        if (x.sum >= 2)
            t += 1
    }
    println(t)
}

import scala.collection.mutable._
import scala.math._
import scala.util.control.Breaks.break
import scala.util.control.Breaks.breakable
import java.util._
object Main extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  println(
    (for(i <- 1 to n) yield {
      (for(j <- 1 to 3) yield sc.nextInt).foldLeft(0)(_ + _) >= 2
    }).count(_ == true)
  )
}

object Problems_231A {
    def main(args: Array[String]) = {
        println((1 to readInt).count(_ => readLine.split(" ").map(_.toInt).sum >= 2))
    }
}

import java.util.Scanner

object A extends App {
  val sc = new Scanner(System.in)

  val n = sc.nextInt
  val ones = for {
    i <- 1 to n
    p = sc.nextInt
    q = sc.nextInt
    r = sc.nextInt
    if p + q + r >= 2
  } yield 1
  println(ones.length)
}

// http://codeforces.com/problemset/problem/231/A

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Team {
    def main(args: Array[String]): Unit = {
        val n: Int = readInt()
        var count: Int = 0
        for(i <- 1 to n) {
            if (readLine().split(" ").map(_.toInt).sum >= 2) {
                count += 1
            }
        }
        println(count)
    }
}

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val n = StdIn.readLine().toInt

  var cnt = 0

  1 to n foreach { _ =>
    val Array (x, y, z) = StdIn.readLine().split(" ").map(_.toInt)

    def f(x: Int) = if (x>0) 1 else 0

    cnt += (if (f(x) +  f(y) + f(z) > 1) 1 else 0)
  }

  println(cnt)

}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val ans = (0 until n).map { k =>
       val s = readLine.split(" ").map(_.toInt).sum
       if (s >= 2) 1 else 0
    }.sum
    println(ans)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(Range(0, n).map(_ => in.next().split(" ").map(_.toInt).sum).count(_ > 1))
}

object P231a extends App {
  val n = readLine.toInt
  val problems = (1 to n).map(_ => readLine.split(" ").map(_.toInt))
  val implementings = problems.filter(_.sum >= 2)
  println(implementings.size)
}

object Main {
  def main(args: Array[String]) {
    val std = scala.io.StdIn
    val n = std.readInt()
    var result = 0
    for (i <- 0 until n) {
      val r = std.readLine().split(" ").map(_.toInt).sum
      if (r>=2) result += 1
    }
    println(result)
  }
}

import scala.io.StdIn

object Team extends App {

  val ques = StdIn.readInt()
  var solve = 0
  for (i <- Range(0, ques)) {
    if (impl(StdIn.readLine().split(" ").map(_.toInt)))
      solve += 1
  }
  print(solve)

  def impl(soln: Array[Int]): Boolean = {
    soln.count(_ == 1) >= 2
  }
}

import scala.io.StdIn
object solution extends App{

   val rounds = StdIn.readInt
   var count = 0
  for(round <- 1 to rounds){
       val views = StdIn.readLine.split(" ").map(_.toInt).sum
       if( views >= 2) count += 1
  }
   println(count)

}

import scala.io.StdIn
object Team extends App
{
    println((1 to StdIn.readInt()).count(_ => StdIn.readLine().split(' ').map(_.toInt).sum >=2))
}

object HelloWorld {
   def main(args: Array[String]) {
      val n = readInt
      var c = 0
      for (i <- 0 until n) {
          c += (if(readLine.split(" ").map(_.toInt).count(_ == 1) > 1) 1 else 0)
      }
      println(c)
   }
}

import scala.io.StdIn

object p231a extends  App{

  def sumline(): Int ={
    val s = StdIn.readLine()
    var count = 0

    for (c <- s.toCharArray){
      if (c=='1') {
        count+=1
      }
    }
    if (count>=2) {
      return 1;
    }
    return 0
  }

  private val num = StdIn.readLine().toInt

  var sum = 0

  for (i <- 0 until num){
    sum += sumline()
  }

  print(sum)

}

object A231 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = new Array[Int](n)
    for(i <- 0 until n) {
      val Array(a, b, c) = readInts(3)
      input(i) = a + b + c
    }
    println(input.count(_ > 1))
  }
}

import java.util.Scanner

/**
 * User: Takayuki
 * Date: 12/10/08
 */
object A extends App {
	val in = new Scanner(System.in)
	val n = in.nextInt()
	var res = 0
	for (i <- 0 until n) {
		if (in.nextInt() + in.nextInt() + in.nextInt() >= 2) {
			res += 1
		}
	}
	println(res)
}

object Hello {
    def main(args: Array[String]): Unit = {
      val n = readLine toInt
      var ans = 0
      for (i <- 1 to n) {
        val Array(a, b, c): Array[Int] = readLine split (' ') map (_ toInt)
        if (a + b + c > 1)
          ans = ans + 1
      }
      println(ans)
    }
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random
import scala.util.matching.Regex

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

  val N = sc.nextInt

  def solve: Int = {
    @tailrec
    def loop(acc: Int, i: Int): Int =
      if (i == N) acc
      else {
        val P, V, T = sc.nextInt
        if (P + V + T >= 2) loop(acc + 1, i + 1)
        else loop(acc, i + 1)
      }
    loop(0, 0)
  }

  out.println(solve)
  out.close
}

object Team {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in)
		val n = scanner.nextInt()
		var count = 0
		for (i <- 1 to n) {
		  val first = scanner.nextInt()
		  val second = scanner.nextInt()
		  val third = scanner.nextInt()
		  if (first + second + third >= 2)
		    count = count + 1
		}
		println(count)
	}
}

import scala.io.StdIn

object A231 {
    def main(args: Array[String]) =
        println((for (i <- 1 to StdIn.readLine().toInt if StdIn.readLine().split(" ").map(_.toInt).sum > 1) yield i).length)
}

object Codeforces231A extends App{

  def Checkline(ques:String):Boolean={
    var conv=ques.split(" ")
    var conve=conv.map(_.toInt)
    var res=conve(0)+conve(1)+conve(2)
    if (res/2==1){
      return true
    }
    else{
      return false
    }
  }

  var ans:Int=0
  val s:Int=scala.io.StdIn.readInt
  for (i <- 1 to s){
    val k:String=scala.io.StdIn.readLine
    if (Checkline(k)==true){
      ans+=1
    }
  }
  println(ans)

}

import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)

  def ans = (for(_ <- 1 to readInt) yield readInts.reduce(_ + _)).count(_ > 1)

  def main(a: Array[String]) {
    println(ans)
  }
}

/**
 * Created by vol on 9/18/14.
 */
object A231 extends App {
  val n = readInt()

  def loop(n:Int, i:Int, acc:Int):Int = {
    if (n == i) acc
    else  {
      val count = readLine().split(" ").map(_.toInt).count((e:Int) => e == 1)
      if (count >= 2) loop(n, i + 1, acc + 1) else loop(n, i + 1, acc)
    }
  }

  println(loop(n, 0, 0))

}

object test5 extends App {
    val n=readLine.toInt

    val list=for(i<-1 to n) yield{
    	if(readLine.split(" ").map(_.toInt).sum>=2) 1 else 0
    }
    println(list.sum)
}

object Main {
  def main(args: Array[String]) {
    var n = readInt()
    val tasks = (1 to n).map { unusded =>
      val arr = readLine().split(" ").map(_.toInt)
      arr.sum
    }
    println(tasks.filter(_ >= 2).size)
  }
}

import scala.io.StdIn._

object Solution extends App {

  def solve() = {
    val n = readInt()
    val results = (1 to n).map { _ =>
      val answers = readLine().split(" ").map(_.toInt)
      answers.count(_ == 1) > 1
    }

    println(results.count(_ == true))
  }

  solve()
}

import scala.collection.immutable.Range
import java.lang.String

object Olymp{
  def main(args: Array[String]): Unit = {
    val n = readLine toInt
    var ans = 0
    for (i <- 1 to n) {
      val Array(a, b, c): Array[Int] = readLine split (' ') map (_ toInt)
      if (a+b+c > 1)
        ans = ans + 1;
    }
    println(ans)
  }
}

object main extends App{
    println( (1 to readInt).count(_ => readLine.split(' ').map(_.toInt).sum >=2 ) )

}

object Team {
  def main(args: Array[String]) = {
        val input = Iterator.continually(scala.io.StdIn.readLine()).takeWhile(_ != null).drop(1)

        val solution = input.map(_.split(" ").map(_.toInt).sum).count(_ > 1)

        println(solution)
    }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object Team {
  def main(args: Array[String]) {
    val n = readInt
    val problems = for {
      i <- 1 to n
      line = readLine
    } yield line
    println(
      problems.map(l => l.split(' ').map(_.toInt).toList.sum).count(_ >= 2)
    )
  }
}

import scala.io.StdIn

object Problem231A extends App {

  val n = StdIn.readInt()

  val total = (1 to n).map(_ => StdIn.readLine()).map(_.split(" ").map(_.toInt).sum).filter(_ > 1).size
  println(total)

}

import scala.io.StdIn
object A {
  def main(args: Array[String]): Unit = {
    var ans:StringBuilder=new StringBuilder()
//    var t=StdIn.readInt();
    var t=1
    while(t>0)
      {

        var n:Int=StdIn.readInt()
//        var a:Array[String]=StdIn.readLine().split(" ")
//        var b:Array[String]=StdIn.readLine().split(" ")
//        var c:Array[String]=StdIn.readLine().split(" ")

        var res=0;
        for(i <- 0 until n)
          {
            var a:Array[String]=StdIn.readLine().split(" ")
            var count=0
            if(a(0).equals("1"))
              {
                count+=1;
              }
            if(a(1).equals("1"))
            {
              count+=1
            }
            if(a(2).equals("1"))
              {
                count+=1
              }

            if(count>=2)
              {
                res+=1
              }
          }
        ans.append(res).append("\n")

        t-=1;
      }
    println(ans.toString());

  }
}

object Main{
    def main(args:Array[String]){
        var p =0
        for(_<-1 to readLine.toInt){
            var n = 0
            for(v<-readLine.split(" ").map(x=>x.toInt)){
                if(v==1)
                    n+=1
            }
            if(n>=2)
                p+=1
        }
        println(p)
    }
}

object Problems_231A {
    def main(args: Array[String]) = {
        println((1 to readInt).count(_ => readLine.split(" ").map(_.toInt).sum >= 2))
    }
}

object test
{
    def main(args : Array[String])
    {
        val n = readInt
        var ans = 0
        for(i <- 0 to n-1)
            if(readLine().split(" ").map(_.toInt).count(x => x==1) >=2)
                ans +=1;
        print (ans)
    }
}

object test extends App
{
    print ((1 to readInt).count(x => readLine().split(' ').map(_.toInt).sum >=2))
}

object Main {

  def main(args: Array[String]): Unit = {
    var res = 0;
    for(i <- 1 to readInt()){
      if(readLine().split(' ').map(_.toInt).sum>=2)res += 1
    }
    println(res)
  }

}

object Main {

  def main(args: Array[String]): Unit = {
    println((for(i <- 1 to readInt())yield if(readLine().split(' ').map(_.toInt).sum>=2) 1 else 0).sum)
  }

}

import scala.io.StdIn._

object Team_231A extends App {
  val n = readInt
  val p = (for (x <- 1 to n) yield (readLine.split(" ").map(_.toInt)))

  val ans = p.foldLeft(0)((acc, cp) => {
    acc +
    (if (cp.count(_ == 1) > 1) 1 else 0)
  })

  println(ans)
}

object codeforces {
  def main(args: Array[String]): Unit = {
    val n: Int = scala.io.StdIn.readLine().toInt
    var count: Int = 0
    for (_ <- 0 until n){
      val word: String = scala.io.StdIn.readLine()
//      println(word)
      val line = word.split(" ")
      var num: Int = 0
      for (i <- word){
        if (i == '1'){
          num+=1
        }
      }
      if (num >= 2){
        count+=1
      }
    }
    println(count)
  }
}

import scala.io.Source

object Cf231a extends App {
  println(Source.stdin.getLines().drop(1).map(_.split(" ").filter(!_.isEmpty()).map(_.toInt)).map(x => if (x.sum >= 2) 1 else 0).sum)
}

object Team {
  import io.StdIn.{readLine => rl}
  def main(args : Array[String]) {
    val gls = io.Source.stdin.getLines
    println(gls drop(1) count(((x) => 1 < x.split(" ").map(_.toInt).reduce(_ + _))))
  }
}

object main extends App{
    println((1 to readInt).count(_ => readLine.split(' ').map(_.toInt).sum >=2) )
}

object main extends App{
    val n = readLine().toInt
    var cnt = 0
    for(i <- 1 to n){
        val Array(a,b,c) = readLine.split(' ').map(_.toInt)
        if(a + b + c >=2) cnt += 1
    }
    print(cnt)
}

object A00231 extends App {
  def parseInt(str: String, count: Int): Seq[Int] = {
    val scanner = new java.util.Scanner(str)
    val res = (1 to count) map (_ => scanner.nextInt())
    scanner.close()
    res
  }
  def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)

  def oneIntLine = {
    val Seq(count) = scanInts(1);
    count
  }

  val cnt = oneIntLine
  var res = 0
  for (i <- 1 to cnt) {
    if (scanInts(3).sum > 1) res += 1
  }
  println(res)
}

object CF0231A extends App {

  val n = readInt()

  var count = 0

  (1 to n).foreach(v => {

    val str = readLine().split(" ").map(_.toInt).filter(_>0).size
    if (str > 2) count += 1
  })

  println(count)

}

object Main {
  def main(args: Array[String]) {
    var n = readInt()
    val tasks = (1 to n).map { unusded =>
      val arr = readLine().split(" ").map(_.toInt)
      println(arr)
      arr.sum
    }
    println(tasks)
    println(tasks.filter(_ >= 2).size)
  }
}

object Main {
  def main(args: Array[String]) {
    var n = readInt()
    val tasks = (1 to n).map { unusded =>
      val arr = readLine().split(" ").map(_.toInt)
      arr.sum
    }
    println(tasks.filter(2 >=).size)
  }
}

import scala.io.StdIn

object Problem231A extends App {

  val n = StdIn.readInt()

  val total = (1 to n).map(_ => StdIn.readLine()).map(_.split(" ").map(_.toInt).sum).filter(_ > 1).sum
  println(total)

}

object Team {
  import io.StdIn.{readLine => rl}
  def main(args : Array[String]) {
    val gls = io.Source.stdin.getLines
    gls drop(1)
    println(gls count(x => 1 < x.map(_.toInt).reduce(_ + _)))
  }
}


Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. That is, a glass goes from position i to position pi. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.

The first line contains three integers: n, s, t (1 ≤ n ≤ 105; 1 ≤ s, t ≤ n) — the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p1, p2, ..., pn (1 ≤ pi ≤ n) — the shuffling operation parameters. It is guaranteed that all pi's are distinct. Note that s can equal t.

If the marble can move from position s to position t, then print on a single line a non-negative integer — the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, sn, tn) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt - 1)
  val s = sn - 1
  var c = s
  val t = tn - 1
  var i = 0
  val marked = Array.ofDim[Boolean](n)
  while (!marked(c) && c != t) {
    marked(c) = true
    c = data(c)
    i += 1
  }
  if (c == t)
    println(i)
  else
    println(-1)

}

object CF285B extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val s = in.nextInt
  val t = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt
  def sol(x: Int, c: Int): Int =
    if (x == t) c
    else {
      val next = v(x-1)
      if (c > n || next == s) -1
      else sol(next, c+1)
    }

  out.println(sol(s, 0))
  out.flush
}

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

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

  val N = sc.nextInt
  val S, T = sc.nextInt - 1
  val P = Array.fill(N)(sc.nextInt - 1)

  var n = 0
  var i = S
  breakable {
    while (true) {
      if (i == T) break
      else if (P(i) == -1) {
        n = -1
        break
      }
      else {
        val j = i
        i = P(i)
        P(j) = -1
        n = n + 1
      }
    }
  }

  out.println(n)
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val Array(n, s, t) = readInts
  val a = readInts
  @tailrec
  def rec(moves: Int, pos: Int): Int = if(pos == s && moves != 0) -1 else if(pos == t) moves else rec(moves + 1, a(pos - 1))
  def ans = rec(0, s)

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) = {
    val nst = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val n = nst(0)
    val s = nst(1)
    val t = nst(2)

    var cur = s
    var step = 0

    for {
      _ <- 1 to n
      if step != -1
      if cur != t
    } {
      val next = a(cur - 1)
      if (next == s) step = -1
      else {
        step += 1
        cur = next
      }
    }

    println(step)
  }
}


Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed.    Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally:   if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$);  if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots:   1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.

For each test case print:   YES if there is a sequence of shots leading to a given matrix;  NO if such a sequence does not exist.  The letters in the words YES and NO can be printed in any case.

NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.

import scala.util.control.Breaks

object Polygon {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val t = in.readLine().toInt
    for (t <- 0 until t) {
      val n = in.readLine().toInt
      val arr = Array.ofDim[Int](n, n)
      for (i <- 0 until n) {
        val row = in.readLine()
        for (j <- 0 until n) {
          arr(i)(j) = row(j) - 48
        }
      }
      var flag = false
      Breaks.breakable {
        for (i <- 0 until n) {
          for (j <- 0 until n) {
            if (arr(i)(j) == 1 && i != arr.length-1 && j != arr(0).length-1 && arr(i + 1)(j) != 1 && arr(i)(j + 1) != 1) {
              flag = true
              Breaks.break()
            }
          }
        }
      }
      println(if(flag) "NO" else "YES")
    }
  }
}

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      a = Array.ofDim[Int](n,n)
      conn = Array.fill[Boolean](n,n)(false)
      REP(n) { i =>
        val s = ns(n)
        REP(n) { j =>
          a(i)(j) = s(j) - '0'
          if(j == n-1 && a(i)(j) == 1) conn(i)(j) = true
          if(i == n-1 && a(i)(j) == 1) conn(i)(j) = true
        }
      }

      vis = Array.fill[Int](n,n)(0)
      REP(n) { i =>
        if(a(i)(n-1) == 1) {
          var j = 1
          while (n-j-1 >=0 && a(i)(n-j-1) == 1) {
            conn(i)(n-j-1) = true
            j += 1
          }
        }
        if(a(n-1)(i) == 1) {
          var j = 1
          while (n-j-1 >=0 && a(n-j-1)(i) == 1) {
            conn(n-j-1)(i) = true
            j += 1
          }
        }
      }
      var yes = true
      REP_r(n-1) { i =>
        REP_r(n-1) { j =>
          if(a(i)(j) == 1 && !conn(i)(j)) {
            conn(i)(j) = conn(i+1)(j) | conn(i)(j+1)
          }
          if(a(i)(j) == 1 && !conn(i)(j)) yes = false
        }
      }
      if(yes)
        out.println("YES")
      else out.println("NO")
    }
  }
  var a: Array[Array[Int]] = _
  var conn: Array[Array[Boolean]] = _
  var vis: Array[Array[Int]] = _
}

object E extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readInt()
    val pn = (0 until n).foldLeft(Array.ofDim[Array[Byte]](n)) { (pn, i) =>
      pn(i) = scala.io.StdIn.readLine().split("").map(_.toByte)
      pn
    }

    val ans = pn.init.zipWithIndex.forall {
      case (p, i) =>
        p.zip(p.tail).corresponds(pn(i + 1).init) {
          case ((u, r), d) =>
            u == 0 || d == 1 || r == 1
        }
    }

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


Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.

The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.  It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).

In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.

import scala.util.Sorting._
import math._
import scala.Array

object Contest extends App {
  val n = readInt()
  val arr = readLine().split(" ").map(_.toInt).reverse
  var cur = 0
  var ans: StringBuilder = new StringBuilder
  for (i <- arr){
    if (abs(cur - i) < abs(cur + i)){
      ans.append("-")
      cur -= i
    }
    else{
      ans.append("+")
      cur += i
    }
  }
  ans = ans.reverse
  if (cur < 0){
    var t: StringBuilder = new StringBuilder
    for (c <- ans)
      if (c == '+') t.append("-") else t.append("+")
    ans = t
  }
  println(ans)
}

object test5 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val c=new Array[Char](n)

    var sum=0
    def solve()={
        for(i<-n-1 to 0 by -1){
            if(sum>0){
                sum-=a(i)
                c(i)='-'
            }
            else{
                sum+=a(i)
                c(i)='+'
            }
        }
    }

    solve()

    if(sum>0){
        println(c.mkString)
    }
    else{
        println(c.map(c=>if(c=='+') '-' else '+').mkString)
    }
}

object test5 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val c=new Array[Char](n)

    var sum=0

    for(i<-n-1 to 0 by -1){
        if(sum>0){
            sum-=a(i)
            c(i)='-'
        }
        else{
            sum+=a(i)
            c(i)='+'
        }
    }

    if(sum>0){
        println(c.mkString)
    }
    else{
        println(c.map(c=>if(c=='+') '-' else '+').mkString)
    }
}

object test5 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val c=new Array[Char](n)

    def solve()={
        for(i<-n-2 to 0 by -1){
            if(sum>0){
                sum-=a(i)
                c(i)='-'
            }
            else{
                sum+=a(i)
                c(i)='+'
            }
        }
    }
    var sum=a.last
    c(n-1)='+'
    solve()

    if(sum>0){
        println(c.mkString)
    }
    else{
        println(c.map(c=>if(c=='+') '-' else '+').mkString)
    }
}

object D {
  def main(args: Array[String]) {
    val n = readLine.toInt;
    var a = readLine.split(" ").toList.map(_.toLong)

    a = {
      var sum = 0L
      a.reverse.map { v =>
        if (sum >= 0) {
          sum -= v
          -v
        } else {
          sum += v
          v
        }
      }.reverse
    }

    if (a.sum < 0) {
      a = a.map(-_)
    }
    a.foreach { v =>
      if (v >= 0) {
        print("+")
      } else {
        print("-")
      }
    }
  }
}

import scala.util.Sorting._
import math._
import scala.Array

object Contest extends App {
  val n = readInt()
  val arr = readLine().split(" ").map(_.toInt).reverse
  var cur = 0
  var ans = ""
  for (i <- arr){
    if (abs(cur - i) < abs(cur + i)){
      ans += "-"
      cur -= i
    }
    else{
      ans += ans
      cur += i
    }
  }
  ans = ans.reverse
  if (cur < 0){
    var t = ""
    for (c <- ans)
      if (c == '+') t += "-" else t += "+"
    ans = t
  }
  println(ans)
}

object test5 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val c=new Array[Char](n)

    def solve()={
        for(i<-n-2 to 0 by -1){
            if(sum>0){
                sum-=a(i)
                c(i)='-'
            }
            else{
                sum+=a(i)
                c(i)='+'
            }
        }
    }
    var sum=a.last
    c(n-1)='+'
    solve()

    if(sum>=0 && sum<=a.head){
        println(c.mkString)
        exit(0)
    }

    sum= -a.last
    c(n-1)='-'
    solve()
    if(sum>=0 && sum<=a.head){
        println(c.mkString)
    }
    else println("fuck")
}

object test5 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val c=new Array[Char](n)

    def solve()={
        for(i<-n-2 to 0 by -1){
            if(sum>0){
                sum-=a(i)
                c(i)='-'
            }
            else{
                sum+=a(i)
                c(i)='+'
            }
        }
    }
    var sum=a.last
    c(n-1)='+'
    solve()

    if(sum>=0 && sum<=a.head){
        println(c.mkString)
        exit(0)
    }

    sum= -a.last
    c(n-1)='-'
    solve()
    println(c.mkString)
}

object D {
  def main(args: Array[String]) {
    val n = readLine.toInt;
    var a = readLine.split(" ").toList.map(_.toLong)

    var sum = 0L

    a = a.reverse.map { v =>
      if (sum >= 0) {
        sum -= v
        -v
      } else {
        sum += v
        v
      }
    }.reverse

    if (a.sum < 0) {
      a.map(-_)
    }
    a.foreach { v =>
      if (v >= 0) {
        print("+")
      } else {
        print("-")
      }
    }
  }
}


Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.

The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).

The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.

object A749 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    println(n/2)
    if(n%2 == 1) {
      println("3" ++ " 2" * ((n-2)/2))
    } else {
      println("2 " * (n/2))
    }
  }

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

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object _749A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]

    val ans = if (n%2 == 0) {
      Vector.fill(n/2)(2)
    } else {
      Vector.fill((n-3)/2)(2) :+ 3
    }

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

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

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

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

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

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

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

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

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

object BachgoldProblem extends App{
  val n = io.StdIn.readInt()
  println(n / 2)
  println(n match{
    case n if n <= 3 => n
    case n if n % 2 == 0 => "2" + " 2" * (n / 2 - 1)
    case _ => "2" + " 2" * (n / 2 - 2) + " 3"
  })
}

object A749 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    if(n%2 == 1) {
      println("3" ++ " 2" * ((n-2)/2))
    } else {
      println("2 " * (n/2))
    }
  }

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

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object BachgoldProblem extends App{
  val n = io.StdIn.readInt()
  println(n / 2)
  if(n % 2 == 0) println("2" +  " 2" * (n / 2 - 1))
  else println("2" + " 2" * (n / 2 - 2) + " 3")
}


Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) — the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) — the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) — the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.

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

object Main extends App {
  val sc = new Scanner(System.in)

  val t = sc.nextInt

  (1 to t).foreach(_ => {
    val n = sc.nextInt
    val m = sc.nextInt
    val numMap = mutable.Map[Int, Int]()

    (0 until n).foreach(i => {
      val mm = sc.nextInt
      numMap(mm) = i
    })

    var max = 0

    val ans =
      (0 until m)
        .map(i => {
          val mm = numMap(sc.nextInt)

          if (mm <= max) {
            1
          } else {
            max = mm
            2 * (mm - i) + 1
          }
        })
        .foldLeft(0L)(_ + _)

    println(ans)
  })
}

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

object Main extends App {
  val sc = new Scanner(System.in)

  val t = sc.nextInt

  (1 to t).foreach(_ => {
    val n = sc.nextInt
    val m = sc.nextInt
    val numMap = mutable.Map[Int, Int]()

    (0 until n).foreach(i => {
      val mm = sc.nextInt
      numMap(mm) = i
    })

    var max = 0

    val ans =
      (0 until m)
        .map(i => {
          val mm = numMap(sc.nextInt)

          if (mm <= max) {
            1
          } else {
            max = mm
            2 * (mm - i) + 1
          }
        })
        .reduce(_ + _)

    println(ans)
  })
}