There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.

The first line of the input contains integer n (2 ≤ n ≤ 100) — the number of cards in the deck. It is guaranteed that n is even. The second line contains the sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ 100), where ai is equal to the number written on the i-th card.

Print n / 2 pairs of integers, the i-th pair denote the cards that should be given to the i-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input. It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them.

NoteIn the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8. In the second sample, all values ai are equal. Thus, any distribution is acceptable.

import scala.io.StdIn._

object Main extends App {
  val n = readInt()
  val a = readLine().split(" ").map(_.toInt).zipWithIndex.sorted
  val (f, s) = a.splitAt(n / 2)
  val ans = f.zip(s.reverse)
  for (((_, a), (_, b)) <- ans) println((a + 1) + " " + (b + 1))
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val data = lines.next().split(' ').map(_.toInt).zipWithIndex.sorted
  println(data.take(n / 2).zip(data.drop(n / 2).reverse).map(a => s"${a._1._2 + 1} ${a._2._2 + 1}").mkString("\n"))
}

object A701 {
  @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 = readInts(n).zipWithIndex.sortBy(_._1)
    for(i <- 1 to n/2) {
      println(s"${input(i-1)._2 + 1} ${input(n-i)._2 + 1}")
    }
  }
}

object main {
  def main (args: Array[String]) {
    val n = scala.io.StdIn.readInt()
    val input = (scala.io.StdIn.readLine().split(" ") map (x => x.toInt)).toVector
    val inputWithIndex = input zip (1 to n)
    val sortedInputWithIndex = inputWithIndex.sortBy(pair => pair._1)
    (0 until n/2) map (
       i => println(sortedInputWithIndex(i)._2.toString + " " + sortedInputWithIndex(n - i - 1)._2).toString)
  }
}

object A extends App {

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

  val Array(n) = readInts(1)
  val xs = readInts(n).zipWithIndex.sortBy(_._1).map(_._2 + 1)

  for (i <- 0 until n / 2) println(s"${xs(i)} ${xs(n - i - 1)}")
}

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

object _701A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val cards = read[Vector[Int]]
    val n = cards.length
    val used = mutable.Set.empty[Int]
    val sum = 2*cards.sum/n

    val cz = cards.zipWithIndex

    val ans = Vector.fill(n/2) {
      val Some((c1, i1)) = cz find {case (c, i) => !used(i)}
      used += i1
      val Some((c2, i2)) = cz find {case (c, i) => !used(i) && c + c1 == sum}
      used += i2
      //debug(i1, i2, c1, c2, sum)
      s"${i1 + 1} ${i2 + 1}"
    }

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

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

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

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

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

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

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

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

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

import java.util.Scanner

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

    val dp = new Array[(Int, Int)](n)
    for(i <- 0 until n){
      val tmp = sc.nextInt()
      dp(i) = (tmp, i+1)
    }

   val ans = dp.sorted

    for(i <- 0 until n / 2){
      println(ans(i)._2 + " " + ans(n-1-i)._2)
    }
  }
}

object main extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
//  override
  def solve(input: InputStream, output: PrintStream): Unit = {
   val sc = new Scanner(input)
    val n = sc.nextInt()
    val cardsSorted = (1 to n).map(_ => sc.nextInt()).zipWithIndex.sortBy{case (v,_) => v}.toArray
    (1 to n/2).foreach{
      i => {
        val (_,firstIndex) = cardsSorted(i-1)
        val (_,secondIndex) = cardsSorted(n-i)
        output.println((firstIndex+1)+" "+(secondIndex+1))
      }
    }
  }
  solve(System.in,System.out)
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val data = lines.next().split(' ').map(_.toInt).zipWithIndex.sorted
  println(data.take(n / 2).zip(data.drop(n / 2)).map(a => s"${a._1._2 + 1} ${a._2._2 + 1}").mkString("\n"))
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val data = lines.next().split(' ').map(_.toInt).sorted
  println(data.take(n / 2).zip(data.drop(n / 2)).map(a => s"${a._1} ${a._2}").mkString("\n"))
}


Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.

The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.

Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.

NoteIn the first case, the entire source code works, as well as the "RL" substring in the second and third characters.Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.

/**
  * Created by octavian on 13/02/2016.
  */
object Calvin {

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

    //System.setIn(new FileInputStream("./src/calvin.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/calvin.out")))

    val n = readInt()
    val a: Array[Char] = readLine().toCharArray
    var res = 0
    for(i <- 0 until n - 1) {
      var x = 0
      var y = 0
      for(j <- i until n) {
        a(j) match {
          case 'R' => x = x + 1
          case 'L' => x = x - 1
          case 'D' => y = y + 1
          case 'U' => y = y - 1
        }
        if(x == 0 && y == 0) {
          res += 1
        }
      }
    }

    println(res)

  }

}

import scala.io.Source

object Main {
  def isOk(s: Seq[(Int, Int)]): Boolean = {
    var x = 0
    var y = 0
    s.foreach{t =>
      x += t._1
      y += t._2
    }
    x == 0 && y == 0
  }

  def run(in: Source): String = {
    val tuples = in.getLines().toSeq(1).map{
      case 'U' => (0, 1)
      case 'R' => (1, 0)
      case 'D' => (0, -1)
      case 'L' => (-1, 0)
    }
    val result = (1 to tuples.size).map{ size =>
      tuples.sliding(size).map(isOk).map {
        case false => 0
        case true => 1
      }.sum
    }.sum

    result.toString
  }

  //

  def readAll: String = {
    Source.fromInputStream(System.in).mkString
  }

  def main(args: Array[String]): Unit = {
    val in: Source = Source.fromString(readAll)
    print(run(in))
  }

  def test(string: String): String = {
    val in: Source = Source.fromString(string)
    run(in)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  val lU = Array.ofDim[Int](str.length)
  val lD = Array.ofDim[Int](str.length)
  val lR = Array.ofDim[Int](str.length)
  val lL = Array.ofDim[Int](str.length)
  str.indices.foreach { i =>
    if (i != 0) {
      lU(i) = lU(i - 1)
      lD(i) = lD(i - 1)
      lR(i) = lR(i - 1)
      lL(i) = lL(i - 1)
    }
    if (str(i) == 'L') lL(i) += 1
    else if (str(i) == 'U') lU(i) += 1
    else if (str(i) == 'D') lD(i) += 1
    else lR(i) += 1
  }
  println(str.indices.foldLeft(0) { case (acc, start) =>
    (start + 1 until str.length by 2).foldLeft(acc) {
      case (a, end) =>
        val lCount = if (start == 0) lL(end) else lL(end) - lL(start - 1)
        val rCount = if (start == 0) lR(end) else lR(end) - lR(start - 1)
        val dCount = if (start == 0) lD(end) else lD(end) - lD(start - 1)
        val uCount = if (start == 0) lU(end) else lU(end) - lU(start - 1)

        if (lCount == rCount && dCount == uCount) a + 1 else a
    }
  })

}

import scala.collection._

object A extends App {

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

  var res = 0
  val Array(n) = readInts(1)
  val s = readLine

  for (i <- 0 until n) {
    for (j <- i + 1 to n) {
      val ss = s.substring(i, j)
      if (ss.count(_ == 'L') == ss.count(_ == 'R') && ss.count(_ == 'U') == ss.count(_ == 'D')) res += 1
    }
  }

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

  println(res)

  Console.flush
}

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  def main(args: Array[String]) {
    val n = readLine().toInt
    val s = readLine()

    var res = 0

    for (i <- 0 to n-1) {
      var h = 0
      var v = 0
      for (j <- i to n-1) {
        if (s(j) == 'R') v += 1
        if (s(j) == 'L') v -= 1
        if (s(j) == 'U') h += 1
        if (s(j) == 'D') h -= 1

        if (v == 0 && h == 0) res += 1
      }
    }

    println(res)

//    Console.withOut(new java.io.BufferedOutputStream(Console.out))
//    println(res.mkString("\n"))
//    Console.flush
  }
}

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

object _626A extends CodeForcesApp {
  override type Result = Int

  override def solve(read: InputReader) = {
    val n = read[Int]
    val instr = read[String].toList
    var ans = 0
    for {
      i <- 0 until n
      j <- i+1 to n
      s = instr.slice(i, j)
      if isOkay(s)
    } ans += 1
    ans
  }

  @tailrec
  def isOkay(instr: List[Char], x: Int = 0, y: Int = 0): Boolean = instr match {
    case 'U' :: rest => isOkay(rest, x, y + 1)
    case 'D' :: rest => isOkay(rest, x, y - 1)
    case 'L' :: rest => isOkay(rest, x - 1, y)
    case 'R' :: rest => isOkay(rest, x + 1, y)
    case _ => x == 0 && y == 0
  }

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {i <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

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


You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.

The first line of the input contains a single integer N (3 ≤ N ≤ 10). The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.

Output the maximum length of the shortest path between any pair of vertices in the graph.

NoteYou're running short of keywords, so you can't use some of them:definedoforforeachwhilerepeatuntilifthenelseelifelsifelseifcaseswitch

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val arr = Array.ofDim[Int](n, n)
    (0 to n - 1).map(i => {
      arr(i) = StdIn.readLine().split(" ").map(_.toInt)
      1
    })
    (0 to n - 1).map(k => {
      (0 to n - 1).map(i => {
        (0 to n - 1).map(j => {
          arr(i)(j) = Math.min(arr(i)(j), arr(i)(k) + arr(k)(j))
          1
        })
      })
    })

    println(arr.map(_.max).max)
  }
}

import scala.io.StdIn._

object E {
    def main(args: Array[String]) {

        val n = readInt()
        val a = Vector.fill(n)(readLine().split(" ").map(_.toInt))

        (0 to n-1).map( k => {
            (0 to n-1).map( i => {
                (0 to n-1).map( j => {
                    a(i)(j) = Math.min(a(i)(k) + a(k)(j), a(i)(j))
                    0
                })
            })
        })

        var m = 0
        (0 to n-1).map( i => {
            (0 to n-1).map( j => {
                m = Math.max(m, a(i)(j))
            })
        })

        println(m)
    }
}

import scala.io.StdIn._

object E {
    def main(args: Array[String]) {

        val n = readInt()
        val a = Vector.fill(n)(readLine().split(" ").map(_.toInt))

        (0 until n).map( k => {
            (0 until n).map( i => {
                (0 until n).map( j => {
                    (a(i)(j) > a(i)(k) + a(k)(j)) match {
                        case true => a(i)(j) = a(i)(k) + a(k)(j)
                        case false =>
                    }
                    0
                })
            })
        })

        var m = 0
        (0 until n).map( i => {
            (0 until n).map( j => {
                m = Math.max(m, a(i)(j))
            })
        })

        println(m)
    }
}

import scala.io.StdIn._

object Main extends App {

    val n = readInt()
    val a = Vector.fill(n)(readLine().split(" ").map(_.toInt))

    (0 until n).map( k => {
        (0 until n).map( i => {
            (0 until n).map( j => {
                (a(i)(j) > a(i)(k) + a(k)(j)) match {
                    case true => a(i)(j) = a(i)(k) + a(k)(j)
                    case false =>
                }
                0
            })
        })
    })

    var m = 0
    (0 until n).map( i => {
        (0 until n).map( j => {
            m = Math.max(m, a(i)(j))
        })
    })

    println(m)
}


Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.

The first line contains four space-separated integers s1, s2, s3, s4 (1 ≤ s1, s2, s3, s4 ≤ 109) — the colors of horseshoes Valera has. Consider all possible colors indexed with integers.

Print a single integer — the minimum number of horseshoes Valera needs to buy.

object Two28A extends App {
	val Array(s1, s2, s3, s4) = readLine.split(' ').map(_.toInt)
	val set = Set(s1, s2, s3, s4)
	println(4 - set.size)
}

import scala.io.StdIn

object Main extends App {
  val colors = StdIn.readLine().split(" ").toList
  println(colors.size - colors.distinct.size)
}

object A {
    def main(args: Array[String]) {
        println(4 - readLine.split(" ").distinct.size)
    }
}

object Solution228A extends App {

  def solution() {
    println(4 - 1.to(4).map(_ => _int).groupBy(i => i).size)
  }

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

import scala.collection.mutable._
import scala.math._
import scala.util._
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 t = (for(i <- 1 to 4) yield sc.nextInt).toSet
  println(4 - t.size)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next().split(" ")
  println(data.length - data.distinct.length)
}

//package cf228

object A {

  def main(args: Array[String]) {
    val cs = readLine.split(' ').map(_.toInt)
    println((cs.map((_,1)).groupBy(_._1).toSeq.map(_._2.size) /:\ 0){_+_-1})
  }

}

object A228 {
  @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 input  = readInts(4).toSet
    println(4 - input.size)
  }
}

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

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

  val shoes = Array.fill(4)(sc.nextInt)

  val answer: Int = 4 - shoes.groupBy(identity[Int]).size

  out.println(answer)
  out.close
}

object Horseshoe {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val set = Set(scanner.nextInt(),scanner.nextInt(),scanner.nextInt(),scanner.nextInt())
		println(4-set.size)
	}
}

import java.io._
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 ans = 4 - readInts.groupBy(x => x).size

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

object test5 extends App {
    val s=readLine.split(" ").map(_.toInt)
    println(4-s.groupBy(v=>v).size)
}

object Main {
  def main(args: Array[String]) {
    val s = readLine().split(" ").map(_.toInt).toSet
    println(4 - s.size)
  }
}

// Codeforces 228A

object _228A extends App {
  val scanner = new java.util.Scanner(System.in)
  val horseshoes = Array.fill(4)(scanner.nextInt)
  println(4-horseshoes.distinct.size)
}

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

object HorseShoe {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def main(args: Array[String]) {
     println(4  - readInts.toSet.size)
   }

}

object Solution extends App {
  val hh = readLine.split(" ").map(_.toInt)

  println(4 - hh.distinct.size)
}

object A00228 extends App {
  def frequency[T](seq: Seq[T]) = seq.groupBy(identity).mapValues(_.size).withDefaultValue(0)
  def parseInt(str: String, count: Int): Seq[Long] = {
    val scanner = new java.util.Scanner(str)
    val res = (1 to count) map (_ => scanner.nextLong())
    scanner.close()
    res
  }
  def scanInts(count: Int): Seq[Long] = parseInt(Console.readLine, count)
  def readMatrix(row: Int, col: Int) = (1 to row) map (x => scanInts(col))

  val hooves = readMatrix(1, 4).head.toList
  println(4 - frequency(hooves).size)
}

object A00228 extends App {
  def frequencyList[T](lst: List[T]) = {
    def iter(remLst: List[T], acc: List[(T, Int)]): List[(T, Int)] = (remLst, acc) match {
      case (Nil, l) => l.reverse
      case (x :: xs, Nil) => iter(xs, (x, 1) :: Nil)
      case (x :: xs, (last, count) :: ys) if x == last => iter(xs, (last, count + 1) :: ys)
      case (x :: xs, ys) => iter(xs, (x, 1) :: ys)
    }
    iter(lst, Nil)
  }

  def parseInt(str: String, count: Int): Seq[Long] = {
    val scanner = new java.util.Scanner(str)
    val res = (1 to count) map (_ => scanner.nextLong())
    scanner.close()
    res
  }
  def scanInts(count: Int): Seq[Long] = parseInt(Console.readLine, count)
  def readMatrix(row: Int, col: Int) = (1 to row) map (x => scanInts(col))

  println(4 - frequencyList(readMatrix(1, 4).head.toList).size)
}


Mike is trying rock climbing but he is awful at it. There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height.Today Mike decided to cover the track with holds hanging on heights a1, ..., an. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1, 2, 3, 4, 5) and remove the third element from it, we obtain the sequence (1, 2, 4, 5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.Help Mike determine the minimum difficulty of the track after removing one hold.

The first line contains a single integer n (3 ≤ n ≤ 100) — the number of holds. The next line contains n space-separated integers ai (1 ≤ ai ≤ 1000), where ai is the height where the hold number i hangs. The sequence ai is increasing (i.e. each element except for the first one is strictly larger than the previous one).

Print a single number — the minimum difficulty of the track after removing a single hold.

NoteIn the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.In the second test after removing every hold the difficulty equals 2.In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer — 4.

import java.util.StringTokenizer

object _496A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val d = (1 until n).map(i => a(i) - a(i - 1))
  var ans = d.max
  val dd = (1 until d.length).map(i => d(i) + d(i - 1))
  ans = ans max dd.min
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var min = data.sliding(2).map{t => t.last - t.head}.max
  println(Math.max(data.sliding(3).map{t => t.last - t.head}.min, min))
}

object A496 {

  import IO._
  def drop(a: Int, arr: Array[Int]) = arr.take(a) ++ arr.drop(a+1)
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    var res = Int.MaxValue
    for(i <- 1 to n-2) {
      val arr = drop(i, in.clone())
      var inter = 0
      for(j <- 1 until n-1) {
        //i+1 is removed
        inter = math.max(inter, arr(j)-arr(j-1))
      }
      res = math.min(res, inter)
    }

    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

    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 P496A {
	def zipSub(a: List[Int], b: List[Int]) : List[Int] = {
		return (a, b).zipped.map(_ - _)
	}

	def main(args: Array[String]) {
		val n = scala.io.StdIn.readInt()
		val a = scala.io.StdIn.readLine.split(" ").map(_.toInt).toList
		println(math.max(zipSub(a.drop(1), a).max, zipSub(a.drop(2), a).min))
	}
}

object Main extends App {

  val n = readInt
  val a = readLine.split(" ").map(_.toInt)
  val pairs = (a zip a.tail) map { case (a1,a2) => a2 - a1 }
  val cur = pairs.max
  val dropped = (pairs zip pairs.tail) map { case (a1, a2) => List(a1+a2, cur).max }
  println(dropped.min)

}

object Main extends App {

  val n = readInt

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

  def trackDiff(a: List[Int], maxDiff: Int): Int =
    if (a.tail.isEmpty) maxDiff else trackDiff(a.tail, maxDiff.max(a.tail.head - a.head))

  def trackDiffWithout(i: Int) = trackDiff(a.take(i) ::: a.drop(i + 1), -1)

  println((1 to n - 2).map(trackDiffWithout(_)).min)
}


Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1.You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value v, you combine them together to create a slime with value v + 1.You would like to see what the final state of the row is after you've added all n slimes. Please print the values of the slimes in the row from left to right.

The first line of the input will contain a single integer, n (1 ≤ n ≤ 100 000).

Output a single line with k integers, where k is the number of slimes in the row after you've finished the procedure described in the problem statement. The i-th of these numbers should be the value of the i-th slime from the left.

NoteIn the first sample, we only have a single slime with value 1. The final state of the board is just a single slime with value 1.In the second sample, we perform the following steps:Initially we place a single slime in a row by itself. Thus, row is initially 1.Then, we will add another slime. The row is now 1 1. Since two rightmost slimes have the same values, we should replace these slimes with one with value 2. Thus, the final state of the board is 2.In the third sample, after adding the first two slimes, our row is 2. After adding one more slime, the row becomes 2 1.In the last sample, the steps look as follows:   1  2  2 1  3  3 1  3 2  3 2 1  4

import scala.collection.mutable.ArrayBuffer

/**
  * Created by octavian on 30/01/2016.
  */
object Slime {

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

    //System.setIn(new FileInputStream("./src/slime.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/slime.out")))

    val n = readInt()
    var slimes = ArrayBuffer.empty[Int]
    for(i <- 1 to n) {
      slimes :+= 1
      while(slimes.size > 1 && slimes(slimes.length - 1) == slimes(slimes.length - 2)) {
        //println("condition holds")
        slimes(slimes.length - 2) += 1
        slimes = slimes.dropRight(1)
      }
      //println("slimes is " + slimes)
    }
    println(slimes.mkString(" "))
  }
}

import scala.collection.mutable.ListBuffer

object A341{
  def main(args: Array[String]){
    def log2(x: Double) = scala.math.log(x)/scala.math.log(2)
    var x=scala.io.StdIn.readDouble
    val res = scala.collection.mutable.ArrayBuffer.empty[Int]
    while (x > 1){
      val p = log2(x)
      x -= math.pow(2, p.toInt)
      res+=(p.toInt+1)
    }
    if (x == 1){
      res+=1
    }
    println(res.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val string = in.next().toInt.toBinaryString.reverse
  println(string.zipWithIndex.map{
    case ('1', n) => n + 1
    case _ => 0
  }.filter(_ != 0).reverse.mkString(" "))
}

object A618 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    var res = Array.empty[Int]
    for(i <- 0 to 30) {
      if ((n & (1 << i)) != 0)
        res ++= Array(i+1)
    }
    println(res.sorted.reverse.mkString(" "))
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

import scala.collection._
import scala.collection.mutable.ArrayStack

object A extends App {

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

  val Array(n) = readInts(1)
  val s = ArrayStack.empty[Int]

  for (_ <- 1 to n) {
    var x = 1
    while (s.nonEmpty && s.head == x) {
      x += 1
      s.pop()
    }
    s.push(x)
  }

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

  println(s.toArray.reverse.mkString(" "))

  Console.flush
}

import scala.collection.mutable

/**
 * <a href="http://codeforces.com/problemset/problem/618/A"/>
 *
 * @author pvasilyev
 * @since 25 Apr 2016
 */
object Problem156 extends App {

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

  def solve(n: Int, binaryRepresentation: mutable.MutableList[Int], factor: Int): Unit = {
    if (n > 0) {
      if (n % factor == 0) {
        binaryRepresentation += 0
      } else {
        binaryRepresentation += 1
      }

      solve(n / factor, binaryRepresentation, factor)
    }
  }

  val binaryRepresentation: mutable.MutableList[Int] = mutable.MutableList.empty
  solve(n, binaryRepresentation, 2)
  val answer: mutable.MutableList[Int] = mutable.MutableList.empty
  for (i <- binaryRepresentation.indices) {
    if (binaryRepresentation.get(i).get == 1) {
      answer += (i+1)
    }
  }
  println(answer.reverse.mkString(" "))

}

import scala.collection.mutable

/**
 * <a href="http://codeforces.com/problemset/problem/618/A"/>
 *
 * @author pvasilyev
 * @since 25 Apr 2016
 */
object Problem156 extends App {

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

  def solve(n: Int, bits: mutable.MutableList[Int]): Unit = {
    if (n > 0) {
      bits += (n % 2)
      solve(n / 2, bits)
    }
  }

  val bits: mutable.MutableList[Int] = mutable.MutableList.empty
  solve(n, bits)
  val answer = bits.zipWithIndex.collect({case (1, i) => i + 1})
  println(answer.reverse.mkString(" "))

}

import scala.io.Source

object Main {
  val count = Source.stdin.getLines().mkString.toInt
  val stack = scala.collection.mutable.Stack[Int]()

  def foldStack(): Unit = {
    while (stack.length > 1 && stack.elems.head == stack.elems.tail.head) {
      val a = stack.pop()
      val b = stack.pop()
      stack.push(a + 1)
    }
  }

  def main(args: Array[String]) {
    for (i <- 0 until count) {
      foldStack()
      stack.push(1)
    }
    foldStack()
    println(stack.reverse.mkString(" "))
  }
}

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

object _618A extends CodeForcesApp {
  override type Result = Seq[Int]

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val bits = java.lang.Integer.toBinaryString(n).reverse.zipWithIndex
    bits collect { case ('1', i) => i + 1}
  }

  override def format(result: Seq[Int]) = result.reverse mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

import java.util.Scanner

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

    // var ans = new List[Int]()

    if(n == 1){
      println(1)
    }
    else{
      val a = (Math.log(n)/Math.log(2)).toInt
      print(a + 1)
      n -= Math.pow(2, a).toInt

      def check(n: Int): Unit = {
        n match{
          case 0 =>
            println()
          case 1 =>
            println(" 1")
          case x =>
            val b = (Math.log(n)/Math.log(2)).toInt
            print(' ')
            print(b + 1)
            val c = x - Math.pow(2, b).toInt
            check(c)
        }
      }

      check(n)
    }
  }
}

object Runner {

  def main(args: Array[String]) = {
    val n = readInt()

    val binaryStr = Integer.toBinaryString(n)
    var res = List[Int]()
    for (i <- 0 until binaryStr.length()) {
      if (binaryStr.charAt(i).equals('1')) {
        res = res :+ (binaryStr.length() - i)
      }
    }
    var str = ""
    for (i <- 0 until res.size) {
      str += res(i)
      if (i != res.size - 1) {
        str += " "
      }
    }
    println(str)
  }
}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer
import javax.print.attribute.standard.Sides

object CF2016_A {

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

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int

    val arr = new ArrayList[Int]
    for (i<- 1 to n) {
      arr.add(1)
      while (arr.size() > 1 && arr.get(arr.size()-1) == arr.get(arr.size()-2)) {
        val vv = arr.remove(arr.size()-1) + 1
        arr.remove(arr.size()-1)
        arr.add(vv)
      }
    }
    for (i <- 0 until arr.size()) print(arr.get(i)+" ")

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """

"""

}

}

import scala.collection.mutable.ArrayBuffer

/**
  * Created by octavian on 30/01/2016.
  */
object Slime {

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

    //System.setIn(new FileInputStream("./src/slime.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/slime.out")))

    val n = readInt()
    var slimes = ArrayBuffer.empty[Int]
    for(i <- 1 to n) {
      slimes :+= 1;
      //println("slimes is " + slimes)
      while(slimes.size > 1 && slimes(slimes.length - 1) == slimes(slimes.length - 2)) {
        //println("condition holds")
        slimes(slimes.length - 2) += 1
        slimes = slimes.dropRight(1)
      }
    }
    println(slimes.mkString)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val string = in.next().toInt.toBinaryString
  println(string.zip(string.indices.map(i => 1 << i)).map{
    case ('1', n) => n
    case _ => 0
  }.filter(_ != 0).mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val string = in.next().toInt.toBinaryString.reverse
  println(string.zip(string.indices.map(i => 1 << i)).map{
    case ('1', n) => n
    case _ => 0
  }.filter(_ != 0).reverse.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val string = in.next().toInt.toBinaryString.reverse
  println(string.zip(string.indices.map(i => 1 << i)).map{
    case ('1', n) => n
    case _ => 0
  }.filter(_ != 0).mkString(" "))
}

import java.util.Scanner

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

    // var ans = new List[Int]()

    if(n == 1){
      println(1)
    }
    else{
      val a = (Math.log(n)/Math.log(2)).toInt
      print(a + 1)
      n -= Math.pow(2, a).toInt

      def check(n: Int): Unit = {
        n match{
          case 0 =>
            println()
          case 1 =>
            println(" 1")
          case x =>
            val b = (Math.log(n)/Math.log(2)).toInt
            print(b + 1)
            val c = x - Math.pow(2, b).toInt
            check(c)
        }
      }

      check(n)
    }
  }
}


Vasya plays Robot Bicorn Attack.The game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string s. Vasya decided to brag about his achievement to the friends. However, he has forgotten how many points he got for each round. The only thing he remembers is the string s.Help Vasya to find out what is the maximum amount of points he could get. Take into account that Vasya played Robot Bicorn Attack for the first time, so he could not get more than 1000000 (106) points for one round.

The only line of input contains non-empty string s obtained by Vasya. The string consists of digits only. The string length does not exceed 30 characters.

Print the only number — the maximum amount of points Vasya could get. If Vasya is wrong and the string could not be obtained according to the rules then output number -1.

NoteIn the first example the string must be split into numbers 1, 2 and 34.In the second example the string must be split into numbers 90, 0 and 0. In the third example the string is incorrect, because after splitting the string into 3 numbers number 00 or 09 will be obtained, but numbers cannot have leading zeroes.

import scala.math.max

object CF105A {

  def parseScore(string: String): Option[Int] = {
    if (string.length == 0) None
    else if (string.length >= 2 && string.charAt(0) == '0') None
    else if (string.length >= 8) None
    else if (string.toInt > 1000000) None
    else Some(string.toInt)
  }

  def main(args: Array[String]): Unit = {
    val input = readLine()
    var maxSum = -1
    for (i <- 0 until input.length) {
      for (j <- i until input.length) {
        val string1 = input.substring(0, i)
        val string2 = input.substring(i, j)
        val string3 = input.substring(j)
        (parseScore(string1), parseScore(string2), parseScore(string3)) match {
          case (Some(value1), Some(value2), Some(value3)) => {
            maxSum = max(value1 + value2 + value3, maxSum)
          }
          case _ => Unit
        }
      }
    }
    println(maxSum)
  }
}

/**
 * Created by IntelliJ IDEA.
 * User: ymatsux
 * Date: 12/05/06
 * Time: 2:02
 * To change this template use File | Settings | File Templates.
 */

object CF115A {
  def main(args: Array[String]): Unit = {
    val input = readLine()
    var ans = -1
    for (i <- 0 until input.length) {
      for (j <- i + 1 until input.length) {
        val s1 = input.substring(0, i)
        val s2 = input.substring(i, j)
        val s3 = input.substring(j)
        if (isValid(s1) && isValid(s2) && isValid(s3)) {
          ans = math.max(s1.toInt + s2.toInt + s3.toInt, ans)
        }
      }
    }
    println(ans)
  }

  def isValid(string: String): Boolean = {
    if (string.length == 0) false
    else if (string.length >= 2 && string.charAt(0) == '0') false
    else {
      val value = BigInt(string)
      value <= 1000000
    }
  }
}


One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".Names are case sensitive.

The only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 — the name of the problem.

Print "YES", if problem is from this contest, and "NO" otherwise.

import scala.io.StdIn._

object Codeforces extends App {
  val contest = readLine()
  val friends = List("Danil", "Olya", "Slava", "Ann", "Nikita")
  var count: Int = 0
  friends.foreach(count += _.r.findAllIn(contest).length)
  println(if (count == 1) "YES" else "NO")
}

object A extends App {
  def countSubstring(str1: String, str2: String): Int = {
    def count(pos: Int, c: Int): Int = {
      val idx = str1 indexOf(str2, pos)
      if (idx == -1) c else count(idx + str2.length, c+1)
    }
    count(0, 0)
  }

  val friends = List("Danil", "Olya", "Slava", "Ann", "Nikita")
  val str1 = scala.io.StdIn.readLine()

  if (friends.foldLeft(0)((acc, str2) => acc + countSubstring(str1, str2)) == 1) println("YES")
  else println("NO")
}

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

  override def apply(io: IO): io.type = {
    val friends = List("Danil", "Olya", "Slava", "Ann", "Nikita")
    val input = io.read[String]
    val result = friends.sumWith {f =>
      if (input.contains(f)) {
        if (input.indexOf(f) == input.lastIndexOf(f)) {
          1
        } else {
          2
        }
      } else {
        0
      }
    }

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

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

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

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

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

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

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

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

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

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


Pasha has many hamsters and he makes them work out. Today, n hamsters (n is even) came to work out. The hamsters lined up and each hamster either sat down or stood up.For another exercise, Pasha needs exactly  hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster ether sit down or stand up. How many minutes will he need to get what he wants if he acts optimally well?

The first line contains integer n (2 ≤ n ≤ 200; n is even). The next line contains n characters without spaces. These characters describe the hamsters' position: the i-th character equals 'X', if the i-th hamster in the row is standing, and 'x', if he is sitting.

In the first line, print a single integer — the minimum required number of minutes. In the second line, print a string that describes the hamsters' position after Pasha makes the required changes. If there are multiple optimal positions, print any of them.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  val small = str.count(_ == 'x')
  var change = Math.abs(n / 2 - small)
  println(change)
  if (small > n / 2) {
    println(str.map{
      case ('x') if change > 0 =>
        change -= 1
        'X'
      case t => t
    })
  } else {
    println(str.map{
      case ('X') if change > 0 =>
        change -= 1
        'x'
      case t => t
    })
  }
}

object A {
  def main(args: Array[String]): Unit = {
    val n = Console.readInt
    val s = new StringBuilder(Console readLine)
    var c = 0
    for (x <- s) c += (if (x == 'X') 1 else 0)
    if (c < n/2) {
      var q = n/2-c
      for (x <- 0 until n) {
        if (s(x) == 'x' && q > 0) {
          s(x) = 'X'
          q -= 1;
        }
      }
    } else {
      var q = c-n/2
      for (x <- 0 until n) {
        if (s(x) == 'X' && q > 0) {
          s(x) = 'x'
          q -= 1;
        }
      }
    }
    println(Math.abs(c-n/2))
    println(s)
  }
}


InputThe input contains a single integer a (1 ≤ a ≤ 40).OutputOutput a single string.ExamplesInput2OutputAdamsInput8OutputVan BurenInput29OutputHarding

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val arr = Array(
    "Washington",
    "Adams",
    "Jefferson",
    "Madison",
    "Monroe",
    "Adams",
    "Jackson",
    "Van Buren",
    "Harrison",
    "Tyler",
    "Polk",
    "Taylor",
    "Fillmore",
    "Pierce",
    "Buchanan",
    "Lincoln",
    "Johnson",
    "Grant",
    "Hayes",
    "Garfield",
    "Arthur",
    "Cleveland",
    "Harrison",
    "Cleveland",
    "McKinley",
    "Roosevelt",
    "Taft",
    "Wilson",
    "Harding",
    "Coolidge",
    "Hoover",
    "Roosevelt",
    "Truman",
    "Eisenhower",
    "Kennedy",
    "Johnson",
    "Nixon",
    "Ford",
    "Carter",
    "Reagan",
    "Bush",
    "Clinton",
    "Bush",
    "Obama")
  println(arr(n - 1))
}

object Main {
  def main(args: Array[String]) {
    val s = readInt() match {
      case 1 => "Washington"
      case 2 => "Adams"
      case 3 => "Jefferson"
      case 4 => "Madison"
      case 5 => "Monroe"
      case 6 => "Adams"
      case 7 => "Jackson"
      case 8 => "Van Buren"
      case 9 => "Harrison"
      case 10 => "Tyler"
      case 11 => "Polk"
      case 12 => "Taylor"
      case 13 => "Fillmore"
      case 14 => "Pierce"
      case 15 => "Buchanan"
      case 16 => "Lincoln"
      case 17 => "Johnson"
      case 18 => "Grant"
      case 19 => "Hayes"
      case 20 => "Garfield"
      case 21 => "Arthur"
      case 22 => "Cleveland"
      case 23 => "Harrison"
      case 24 => "Cleveland"
      case 25 => "McKinley"
      case 26 => "Roosevelt"
      case 27 => "Taft"
      case 28 => "Wilson"
      case 29 => "Harding"
      case 30 => "Coolidge"
      case 31 => "Hoover"
      case 32 => "Roosevelt"
      case 33 => "Truman"
      case 34 => "Eisenhower"
      case 35 => "Kennedy"
      case 36 => "Johnson"
      case 37 => "Nixon"
      case 38 => "Ford"
      case 39 => "Carter"
      case 40 => "Reagan"
    }
    println(s)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  println(in.next())
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println(Map(2 -> "Adams", 8 -> "Van Buren", 29 -> "Harding").getOrElse(n, "don't know"))
}

object Main {
  def main(args: Array[String]) {
    val s = readInt() match {
      case 1 => "Washington"
      case 2 => "Adams"
      case 3 => "Jefferson"
      case 4 => "Madison"
      case 5 => "Monroe"
      case 6 => "Quincy Adams"
      case 7 => "Jackson"
      case 8 => "Van Buren"
      case 9 => "Henry Harrison"
      case 10 => "Tyler"
      case 11 => "K. Polk"
      case 12 => "Taylor"
      case 13 => "Fillmore"
      case 14 => "Pierce"
      case 15 => "Buchanan"
      case 16 => "Lincoln"
      case 17 => "Johnson"
      case 18 => "S. Grant"
      case 19 => "B. Hayes"
      case 20 => "A. Garfield"
      case 21 => "A. Arthur"
      case 22 => "Cleveland"
      case 23 => "Harrison"
      case 24 => "Cleveland"
      case 25 => "McKinley"
      case 26 => "Roosevelt"
      case 27 => "Howard Taft"
      case 28 => "Wilson"
      case 29 => "G. Harding"
      case 30 => "Coolidge"
      case 31 => "Hoover"
      case 32 => "D. Roosevelt"
      case 33 => "S. Truman"
      case 34 => "D. Eisenhower"
      case 35 => "F. Kennedy"
      case 36 => "B. Johnson"
      case 37 => "Nixon"
      case 38 => "Ford"
      case 39 => "Carter"
      case 40 => "Reagan"
    }
    println(s)
  }
}

object Main {
  def main(args: Array[String]) {
    val s = readInt() match {
      case 1 => "Washington"
      case 2 => "Adams"
      case 3 => "Jefferson"
      case 4 => "Madison"
      case 5 => "Monroe"
      case 6 => "Quincy Adams"
      case 7 => "Jackson"
      case 8 => "Van Buren"
      case 9 => "Henry Harrison"
      case 10 => "Tyler"
      case 11 => "Polk"
      case 12 => "Taylor"
      case 13 => "Fillmore"
      case 14 => "Pierce"
      case 15 => "Buchanan"
      case 16 => "Lincoln"
      case 17 => "Johnson"
      case 18 => "Grant"
      case 19 => "Hayes"
      case 20 => "Garfield"
      case 21 => "Arthur"
      case 22 => "Cleveland"
      case 23 => "Harrison"
      case 24 => "Cleveland"
      case 25 => "McKinley"
      case 26 => "Roosevelt"
      case 27 => "Howard Taft"
      case 28 => "Wilson"
      case 29 => "Harding"
      case 30 => "Coolidge"
      case 31 => "Hoover"
      case 32 => "Roosevelt"
      case 33 => "Truman"
      case 34 => "Eisenhower"
      case 35 => "Kennedy"
      case 36 => "Johnson"
      case 37 => "Nixon"
      case 38 => "Ford"
      case 39 => "Carter"
      case 40 => "Reagan"
    }
    println(s)
  }
}


Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 milliseconds.If connection ping (delay) is t milliseconds, the competition passes for a participant as follows:   Exactly after t milliseconds after the start of the competition the participant receives the text to be entered.  Right after that he starts to type it.  Exactly t milliseconds after he ends typing all the text, the site receives information about it. The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.Given the length of the text and the information about participants, determine the result of the game.

The first line contains five integers s, v1, v2, t1, t2 (1 ≤ s, v1, v2, t1, t2 ≤ 1000) — the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant.

If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship".

NoteIn the first example, information on the success of the first participant comes in 7 milliseconds, of the second participant — in 14 milliseconds. So, the first wins.In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participant — in 5 milliseconds. So, the second wins.In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participant — in 22 milliseconds. So, it is be a draw.

object A extends App {

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

  val Array(s, v1, v2, t1, t2) = readInts(5)

  val x1 = s * v1 + 2 * t1
  val x2 = s * v2 + 2 * t2

  val r = if (x1 < x2) "First"
  else if (x2 < x1) "Second"
  else "Friendship"

  println(r)
}

import scala.io.StdIn

object Main extends App {

  val Array(s, v1, v2, t1, t2) = StdIn.readLine().split(" ").map(_.toInt)

  val first = 2*t1 + v1*s
  val second = 2*t2 + v2*s
  if(first < second) println("First")
  else if(first > second) println("Second")
  else if(first == second) println("Friendship")

}

object AKeyRaces extends App {
  def result: (Int, Int, Int, Int, Int) => Int = (s: Int, v1: Int, v2: Int, t1: Int, t2: Int) => {
    val r1 = 2 * t1 + s * v1
    val r2 = 2 * t2 + s * v2
    if (r1 == r2) 0
    else if (r1 < r2) 1
    else -1
  }

  val Array(s, v1, v2, t1, t2) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val r = result(s, v1, v2, t1, t2)
  if (r == 0) print("Friendship")
  else if (r == 1) print("First")
  else print("Second")
}


Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych.The poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams. So the professor began: "Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has al fingers on her left hand and ar fingers on the right one. The boy correspondingly has bl and br fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. And in addition, no three fingers of the boy should touch each other. Determine if they can hold hands so that the both were comfortable."The boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa.

The first line contains two positive integers not exceeding 100. They are the number of fingers on the Venusian girl's left and right hand correspondingly. The second line contains two integers not exceeding 100. They are the number of fingers on the Marsian boy's left and right hands correspondingly.

Print YES or NO, that is, the answer to Petr Palych's question.

NoteThe boy and the girl don't really care who goes to the left.

import scala.io.StdIn

/**
 * @author chengyi
 */
object StudentDream {

  def tryHold(g:Int, b:Int):Boolean = {

    if (b>=(g-1) && b<=(2*(g-1)+4) ) true else false
  }

  def canHold(g:String, b:String):String = {
    val gi = g.split(" ")
    val gl = gi(0).toInt
    val gr = gi(1).toInt

    val bi = b.split(" ")
    val bl = bi(0).toInt
    val br = bi(1).toInt

    if (tryHold(gl, br) || tryHold(gr, bl)){
      "YES"
    }else{
      "NO"
    }
  }

  def main(args:Array[String]){
    val g = StdIn.readLine();
    val b = StdIn.readLine()
    println(canHold(g,b))
  }

}

import scala.io.StdIn

/**
 * @author chengyi
 */
object StudentDream {

  def tryHold(g:Int, b:Int):Boolean = {
    val del = b-g
    if (del>= -1 && del<=3) true else false
  }

  def canHold(g:String, b:String):String = {
    val gi = g.split(" ")
    val gl = gi(0).toInt
    val gr = gi(1).toInt

    val bi = b.split(" ")
    val bl = bi(0).toInt
    val br = bi(1).toInt

    if (tryHold(gl, br) || tryHold(gr, bl)){
      "YES"
    }else{
      "NO"
    }
  }

  def main(args:Array[String]){
    val g = StdIn.readLine();
    val b = StdIn.readLine()
    println(canHold(g,b))
  }

}

import scala.io.StdIn

/**
 * @author chengyi
 */
object StudentDream {

  def tryHold(g:Int, b:Int):Boolean = {
    val del = g -b
    if (del>= -1 && del<=3) true else false
  }

  def canHold(g:String, b:String):String = {
    val gi = g.split(" ")
    val gl = gi(0).toInt
    val gr = gi(1).toInt

    val bi = b.split(" ")
    val bl = bi(0).toInt
    val br = bi(1).toInt

    if (tryHold(gl, br) || tryHold(gr, bl)){
      "YES"
    }else{
      "NO"
    }
  }

  def main(args:Array[String]){
    val g = StdIn.readLine();
    val b = StdIn.readLine()
    println(canHold(g,b))
  }

}