Alice is the leader of the State Refactoring Party, and she is about to become the prime minister. The elections have just taken place. There are $$$n$$$ parties, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th party has received $$$a_i$$$ seats in the parliament.Alice's party has number $$$1$$$. In order to become the prime minister, she needs to build a coalition, consisting of her party and possibly some other parties. There are two conditions she needs to fulfil:   The total number of seats of all parties in the coalition must be a strict majority of all the seats, i.e. it must have strictly more than half of the seats. For example, if the parliament has $$$200$$$ (or $$$201$$$) seats, then the majority is $$$101$$$ or more seats.  Alice's party must have at least $$$2$$$ times more seats than any other party in the coalition. For example, to invite a party with $$$50$$$ seats, Alice's party must have at least $$$100$$$ seats. For example, if $$$n=4$$$ and $$$a=[51, 25, 99, 25]$$$ (note that Alice'a party has $$$51$$$ seats), then the following set $$$[a_1=51, a_2=25, a_4=25]$$$ can create a coalition since both conditions will be satisfied. However, the following sets will not create a coalition:  $$$[a_2=25, a_3=99, a_4=25]$$$ since Alice's party is not there;  $$$[a_1=51, a_2=25]$$$ since coalition should have a strict majority;  $$$[a_1=51, a_2=25, a_3=99]$$$ since Alice's party should have at least $$$2$$$ times more seats than any other party in the coalition. Alice does not have to minimise the number of parties in a coalition. If she wants, she can invite as many parties as she wants (as long as the conditions are satisfied). If Alice's party has enough people to create a coalition on her own, she can invite no parties.Note that Alice can either invite a party as a whole or not at all. It is not possible to invite only some of the deputies (seats) from another party. In other words, if Alice invites a party, she invites all its deputies.Find and print any suitable coalition.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of parties. The second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 100$$$) — the number of seats the $$$i$$$-th party has.

If no coalition satisfying both conditions is possible, output a single line with an integer $$$0$$$. Otherwise, suppose there are $$$k$$$ ($$$1 \leq k \leq n$$$) parties in the coalition (Alice does not have to minimise the number of parties in a coalition), and their indices are $$$c_1, c_2, \dots, c_k$$$ ($$$1 \leq c_i \leq n$$$). Output two lines, first containing the integer $$$k$$$, and the second the space-separated indices $$$c_1, c_2, \dots, c_k$$$.  You may print the parties in any order. Alice's party (number $$$1$$$) must be on that list. If there are multiple solutions, you may print any of them.

NoteIn the first example, Alice picks the second party. Note that she can also pick the third party or both of them. However, she cannot become prime minister without any of them, because $$$100$$$ is not a strict majority out of $$$200$$$.In the second example, there is no way of building a majority, as both other parties are too large to become a coalition partner.In the third example, Alice already has the majority. The fourth example is described in the problem statement.

object A extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n).zipWithIndex
  val a0 = as(0)._1

  val cs = as.filter(_._1 * 2 <= a0)

  val sum = a0 + cs.map(_._1).sum

  if (sum * 2 > as.map(_._1).sum) {
    println(cs.size + 1)
    println((1 +: cs.map(_._2 + 1)).mkString(" "))
  } else {
    println(0)
  }

  Console.flush
}

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

  override def apply(io: IO): io.type = {
    val votes = io.read[Vector[Int]]
    val majority = 0 +: votes.indicesWhere(v => 2*v <= votes.head)
    val ans = if (2*majority.map(votes).sum > votes.sum) {
      majority
    } else {
      Nil
    }
    io.writeLine(ans.length).writeAll(ans.map(_ +  1))
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
  }
}
/****************************[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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

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

  override def apply(io: IO): io.type = {
    val votes = io.read[Vector[Int]]
    val majority = 0 +: votes.indicesWhere(v => 2*v <= votes.head)
    val ans = if (2*majority.map(votes).sum >= votes.sum) {
      majority
    } else {
      Nil
    }
    io.writeLine(ans.length).writeAll(ans.map(_ +  1))
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
  }
}
/****************************[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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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


The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of n men (n is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore. The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends. You are asked to calculate the maximum total number of soldiers that may be killed during the game.

The input data consist of a single integer n (2 ≤ n ≤ 108, n is even). Please note that before the game starts there are 2n soldiers on the fields.

Print a single number — a maximum total number of soldiers that could be killed in the course of the game in three turns.

NoteThe first sample test:1) Valera's soldiers 1 and 2 shoot at Arcady's soldier 1.2) Arcady's soldier 2 shoots at Valera's soldier 1.3) Valera's soldier 1 shoots at Arcady's soldier 2.There are 3 soldiers killed in total: Valera's soldier 1 and Arcady's soldiers 1 and 2.

import java.util.Scanner
object GAGA {
    def main(args: Array[String]) {
      val scanner = new Scanner(System.in)
      val n = scanner.nextInt()
      println(n/2*3);
    }
}

import java.util.StringTokenizer

object _84A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  println(n / 2 * 3)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  println(3 * in.next().toInt / 2)
}

import scala.math
object Main
{
	def main(args:Array[String])
	{
		println(readInt / 2 * 3)
	}
}

object A84 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    println(3*(n/2))
  }

  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 java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

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

  val N = sc.nextInt

  val answer = 2 * N - (N / 2)

  out.println(answer)
  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)

  def ans = readInt / 2 * 3

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

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    println(3 * n / 2)
  }
}


While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:  Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":    Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?

The first line of the input contains the only integer n (1 ≤ n ≤ 9) — the number of digits in the phone number that Mike put in. The second line contains the string consisting of n digits (characters from '0' to '9') representing the number that Mike put in.

If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line. Otherwise print "NO" (without quotes) in the first line.

NoteYou can find the picture clarifying the first sample case in the statement above.

import scala.io.StdIn._

object _361A extends App {
  readInt
  val s = readLine.toCharArray.map(_.asDigit).toSet
  val unique =
    List(
      Set(1, 4, 7, 0),
      Set(1, 2, 3),
      Set(3, 6, 9, 0),
      Set(7, 0, 9))
  val ans = unique.forall(x => x.intersect(s).nonEmpty)
  println(if (ans) "YES" else "NO")
}

import scala.io.StdIn._
import scala.util.control._

object cf689A {
    def main (args: Array[String]) {
        val n = readInt();
        val s = readLine();

        if (judge(s, up) || judge(s, down) || judge(s, left) || judge(s, right)) {
            println("NO");
        } else {
            println("YES");
        }
    }

    def judge (s:String, f: Char => Boolean) : Boolean = {
        var res:Boolean = true;
        for (i <- 0 until s.length()) {
            if (f(s(i)) == false) {
                res = false
            }
        }
        return res;
    }

    def up (c:Char) : Boolean = {
        if (c == '0' || c > '3') return true;
        else return false;
    }

    def down (c:Char) : Boolean = {
        if (c == '8' || (c < '7' && c > '0')) return true;
        else return false;
    }

    def left (c:Char) : Boolean = {
        if ((c - '0') % 3 == 1 || c == '0') return false;
        else return true;
    }

    def right (c:Char) : Boolean = {
        if ((c - '0') % 3 == 0 || c == '0') return false;
        else return true;
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()
  val up = Set('1', '2', '3')
  val down = Set('7', '0', '9')
  val right = Set('3', '6', '9', '0')
  val left = Set('1', '4', '7', '0')
  List(left, right, down, up).exists(set => line.forall(i => !set.contains(i))) match {
    case false => println("YES")
    case true => println("NO")
  }
}

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

object _689A extends CodeForcesApp {

  val moves = Map(
    1 -> "DR",
    2 -> "DLR",
    3 -> "DL",
    4 -> "UDR",
    5 -> "UDLR",
    6 -> "UDL",
    7 -> "UR",
    8 -> "UDLR",
    9 -> "UL",
    0 -> "U"
  ).mapValues(_.toSet)

  override def apply(io: IO) = {import io.{read, write}
    val (_, d) = read[(Int, String)]
    val ans = "UDLR" find {c => d.forall(i => moves(i - '0').contains(c))}
    write(ans.isEmpty.toYesNo)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(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
  }
  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 toYesNo = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def 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(n.min(x, y), n.max(x, y), 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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  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 writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = 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 ctoi(c: Char) = c.toInt - '0'.toInt

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

    val dp = new Array[Boolean](10)

    val key = Array((1, 3),
      (0,0), (1,0), (2,0),
      (0,1), (1,1), (2,1),
      (0,2), (1,2), (2,2)
    )

    var xl = 9
    var xr = -1
    var yl = 9
    var yr = -1

    for(i <- 0 until n){
      val now = ctoi(s(i))
      dp(now) = true
      val (nx, ny) = key(now)

      xl = Math.min(xl, nx)
      xr = Math.max(xr, nx)
      yl = Math.min(yl, ny)
      yr = Math.max(yr, ny)
    }

    val xz = xr - xl + 1
    val yz = yr - yl + 1

    val yes = "YES"
    val no = "NO"

    if(yz == 4)
      println(yes)
    else if(xz == 3 && yz == 3){
      if(dp(0) || (dp(8) && !dp(7) && !dp(9)))
        println(no)
      else
        println(yes)
    }
    else
      println(no)
  }
}

import scala.io.StdIn._

object A extends App {
  readInt()
  val M = readLine().toCharArray.map(_.asDigit)

  def delta(a: Int, b: Int): (Int, Int) = {
    val (y1, x1) = pos(a)
    val (y2, x2) = pos(b)
    (y2 - y1, x2 - x1)
  }

  def pos(a: Int) = {
    if (List(1, 2, 3).contains(a)) (0, a - 1)
    else if (List(4, 5, 6).contains(a)) (1, a % 4)
    else if (List(7, 8, 9).contains(a)) (2, a % 7)
    else (3, 1)
  }

  var prev = M.head
  val Deltas = M.tail.map { curr =>
    val d = delta(prev, curr)
    prev = curr
    d
  }

  def canMoveFromThisPoint(startY: Int, startX: Int): Boolean = {
    var y = startY
    var x = startX

    Deltas.foreach { case (dy, dx) =>
      y += dy
      x += dx

      if (y < 0 || x < 0 || y > 3 || x >= 3) return false
      else if (y == 3 && x != 1) return false
    }

    true
  }

  def existDifferentPath: Boolean = {
    val (startY, startX) = pos(M.head)
    for {
      y <- 0 to 3
      x <- 0 to 2
    } {
      val isIllegal = (y == 3 && x != 1) || (y == startY && x == startX)
      if (!isIllegal && canMoveFromThisPoint(y, x)) return true
    }

    false
  }

  val unique = !existDifferentPath
  println(if (unique) "YES" else "NO")
}

object main
{
	def main(args : Array[String] )
	{
		var n = Console.readLine.toInt;
		var str = Console.readLine;

		var pos = Array(Array(4,2),Array(1,1),Array(1,2),Array(1,3),Array(2,1),Array(2,2),Array(2,3),Array(3,1),Array(3,2),Array(3,3));

		var cnt = 0;
		var a = 0;
		for (a <- 0 to 9 )
		{
			var nowx = pos(a)(0);
			var nowy = pos(a)(1);
			var able = true;
			var b = 0;
			for (b <- 0 to n-2)
			{
				var dx = pos(str.charAt(b+1)-'0')(0)-pos(str.charAt(b)-'0')(0);
				var dy = pos(str.charAt(b+1)-'0')(1)-pos(str.charAt(b)-'0')(1);
				nowx += dx;
				nowy += dy;
				if (nowx < 1 || nowy < 1 || nowy>3) able=false;
				if (nowx>3 && (nowx!=4 || nowy!=2)) able=false;
			}
			if (able) cnt+=1;
		}
		if (cnt==1) println("YES");
		else println("NO");
}
}

import scala.io.StdIn._
import scala.util.control._

object cf689A {
    def main (args: Array[String]) {
        val n = readInt();
        val s = readLine();

        if (judge(s, up) || judge(s, down) || judge(s, left) || judge(s, right)) {
            println("NO");
        } else {
            println("YES");
        }
    }

    def judge (s:String, f: Char => Boolean) : Boolean = {
        var res:Boolean = true;
        for (i <- 0 until s.length()) {
            if (f(s(i)) == false) {
                res = false
            }
        }
        return res;
    }

    def up (c:Char) : Boolean = {
        if (c == '0' || c > '3') return true;
        else return false;
    }

    def down (c:Char) : Boolean = {
        if (c == '8' || c < '7') return true;
        else return false;
    }

    def left (c:Char) : Boolean = {
        if ((c - '0') % 3 == 1 || c == '0') return false;
        else return true;
    }

    def right (c:Char) : Boolean = {
        if ((c - '0') % 3 == 0 || c == '0') return false;
        else return true;
    }
}

import scala.io.StdIn._
import scala.util.control._

object cf689A {
    def main (args: Array[String]) {
        val n = readInt();
        val s = readLine();

        if (judge(s, up) || judge(s, down) || judge(s, left) || judge(s, right)) {
            println("NO");
        } else {
            println("YES");
        }
    }

    def judge (s:String, f: Char => Boolean) : Boolean = {
        var res:Boolean = true;
        for (i <- 0 until s.length()) {
            if (f(s(i)) == false) {
                res = false
            }
        }
        return res;
    }

    def up (c:Char) : Boolean = {
        if (c == '0' || c > '3') return true;
        else return false;
    }

    def down (c:Char) : Boolean = {
        if (c == '8' || c < '7') return true;
        else return false;
    }

    def left (c:Char) : Boolean = {
        if ((c - '0') % 3 == 1) return true;
        else return false;
    }

    def right (c:Char) : Boolean = {
        if ((c - '0') % 3 == 0 && c != '0') return true;
        else return false;
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()
  val up = Set('1', '2', '3')
  val down = Set('7', '0', '9')
  val right = Set('3', '6', '9', '0')
  val left = Set('1', '4', '7', '0')
  List(left, up, down, up).exists(set => line.forall(i => !set.contains(i))) match {
    case false => println("YES")
    case true => println("NO")
  }
}

import java.util.Scanner

object Main{
  def ctoi(c: Char) = c.toInt - '0'.toInt

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

    val key = Array((1, 3),
      (0,0), (1,0), (2,0),
      (0,1), (1,1), (2,1),
      (0,2), (1,2), (2,2)
    )

    var xl = 9
    var xr = -1
    var yl = 9
    var yr = -1

    for(i <- 0 until n){
      val (nx, ny) = key(ctoi(s(i)))
      xl = Math.min(xl, nx)
      xr = Math.max(xr, nx)
      yl = Math.min(yl, ny)
      yr = Math.max(yr, ny)
    }

    val xz = xr - xl + 1
    val yz = yr - yl + 1

    val yes = "YES"
    val no = "NO"

    if(yz == 4)
      println(yes)
    else if(xz == 3 && yz == 3)
      println(yes)
    else
      println(no)
  }
}

import scala.io.StdIn._

object A extends App {
  readInt()
  val M = readLine().toCharArray.map(_.asDigit)

  def delta(a: Int, b: Int): (Int, Int) = {
    val (y1, x1) = pos(a)
    val (y2, x2) = pos(b)
    (y2 - y1, x2 - x1)
  }

  def pos(a: Int) = {
    if (List(1, 2, 3).contains(a)) (0, a - 1)
    else if (List(4, 5, 6).contains(a)) (1, a % 4)
    else if (List(7, 8, 9).contains(a)) (2, a % 7)
    else (3, 1)
  }

  var prev = M.head
  val Deltas = M.tail.map { curr =>
    val d = delta(prev, curr)
    prev = curr
    d
  }

  def canMoveFromThisPoint(startY: Int, startX: Int): Boolean = {
    var y = startY
    var x = startX

    Deltas.foreach { case (dy, dx) =>
      y += dy
      x += dx

      if (y < 0 || x < 0 || y > 3 || x >= 3) return false
      else if (y == 3 && x != 1) return false
    }

    true
  }

  def existDifferentPath: Boolean = {
    val (startY, startX) = pos(M.head)
    for {
      y <- 0 to 3
      x <- 0 to 2
      if y != startY && x != startX
    } {
      if (canMoveFromThisPoint(y, x)) return true
    }

    false
  }

  val unique = !existDifferentPath
  println(if (unique) "YES" else "NO")
}

import scala.io.StdIn._

object A extends App {
  readInt()
  val M = readLine().toCharArray.map(_.asDigit)

  def delta(a: Int, b: Int): (Int, Int) = {
    val (y1, x1) = pos(a)
    val (y2, x2) = pos(b)
    (y2 - y1, x2 - x1)
  }

  def pos(a: Int) = {
    if (List(1, 2, 3).contains(a)) (0, a - 1)
    else if (List(4, 5, 6).contains(a)) (1, a % 4)
    else if (List(7, 8, 9).contains(a)) (2, a % 7)
    else (3, 1)
  }

  var prev = M.head
  val Deltas = M.tail.map { curr =>
    val d = delta(prev, curr)
    prev = curr
    d
  }

  def canMoveFromThisPoint(startY: Int, startX: Int): Boolean = {
    var y = startY
    var x = startX

    Deltas.foreach { case (dy, dx) =>
      y += dy
      x += dx

      if (y < 0 || x < 0 || y > 3 || x >= 3) return false
      else if (y == 3 && x != 1) return false
    }

    true
  }

  def existDifferentPath: Boolean = {
    val (startY, startX) = pos(M.head)
    for {
      y <- 0 to 3
      x <- 0 to 2
      if y != startY && x != startX
    } {
      val isIllegal = y == 3 && x != 1
      if (!isIllegal && canMoveFromThisPoint(y, x)) return true
    }

    false
  }

  val unique = !existDifferentPath
  println(if (unique) "YES" else "NO")
}

object main
{
	def main(args : Array[String] )
	{
		var n = Console.readLine.toInt;
		var str = Console.readLine;

		var a = 0;

		var minx = 3;
		var miny = 3;
		var maxx = 1;
		var maxy = 1;

		for ( a <- 0 to n-1 )
		{
			if (str.charAt(a)<='3')
			{
				minx=1;
			}
			if (str.charAt(a)<='6' && minx==3)
			{
				minx=2;
			}
			if (str.charAt(a)>='7')
			{
				maxx=3;
			}
			if (str.charAt(a)>='4' && maxx==1)
			{
				maxx=2;
			}
			if (str.charAt(a)=='1' || str.charAt(a)=='4' || str.charAt(a)=='7')
			{
				miny=1;
			}
			if ((str.charAt(a)=='2' || str.charAt(a)=='5' || str.charAt(a)=='8'))
			{
				if (miny==3)
				{
					miny=2;
				}
				if (maxy==1)
				{
					maxy=2;
				}
			}
			if (str.charAt(a)=='3' || str.charAt(a)=='6' || str.charAt(a)=='9')
			{
				maxy=3;
			}
		}
		if (minx==1 && maxx==3 && miny==1 && maxy==3)
		{
			println("YES");
		}
		else
		{
			println("NO");
		}
	}
}

object main
{
	def main(args : Array[String] )
	{
		var n = Console.readLine.toInt;
		var str = Console.readLine;

		var a = 0;

		var minx = 3;
		var miny = 3;
		var maxx = 1;
		var maxy = 1;

		for ( a <- 0 to n-1 )
		{
			if (str.charAt(a)<='3')
			{
				minx=1;
			}
			if (str.charAt(a)<='6' && minx==3)
			{
				minx=2;
			}
			if (str.charAt(a)>='7')
			{
				maxx=3;
			}
			if (str.charAt(a)>='4' && maxx==1)
			{
				maxx=2;
			}
			if (str.charAt(a)=='1' || str.charAt(a)=='4' || str.charAt(a)=='7')
			{
				miny=1;
			}
			if ((str.charAt(a)=='2' || str.charAt(a)=='5' || str.charAt(a)=='8'))
			{
				if (miny==3)
				{
					miny=2;
				}
				if (maxy==1)
				{
					maxy=2;
				}
			}
			if (str.charAt(a)=='3' || str.charAt(a)=='6' || str.charAt(a)=='9')
			{
				maxx=3;
			}
		}
		if (minx==1 && maxx==3 && miny==1 && maxy==3)
		{
			println("YES");
		}
		else
		{
			println("NO");
		}
	}
}


The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.

//package codeforces.contest1213

object EqualizingByDivision {

  def main(args: Array[String]): Unit = {
    val Array(_, k) = io.StdIn.readLine().split(" ").map(_.toInt)
    val elements = io.StdIn.readLine().split(" ").map(_.toInt)

    val maxElement = elements.max

    val frequency = Array.ofDim[Int](maxElement + 1, 20) // frequency with steps

    for (e <- elements) {
      var temp = e
      var i = 0
      while (temp > 0) {
        frequency(temp)(i) += 1

        i += 1
        temp = temp / 2
      }
    }

    println {
      (1 to maxElement).foldLeft(Int.MaxValue) {
        case (acc, e) =>
          val (steps, count) = frequency(e).indices
            .foldLeft((0, 0)) {
              case ((steps, count), i) =>
                val c = frequency(e)(i)
                if (c != 0 && count < k)
                  if (count + c <= k) (steps + i * c, count + c)
                  else (steps + i * (k - count), k)
                else
                  (steps, count)
            }

          if (count == k) acc min steps else acc
      }
    }
  }
}

//package codeforces.contest1213

object EqualizingByDivision {

  def main(args: Array[String]): Unit = {
    val Array(_, k) = io.StdIn.readLine().split(" ").map(_.toInt)
    val elements = io.StdIn.readLine().split(" ").map(_.toInt)

    val maxElement = elements.max

    val frequency = Array.ofDim[Int](maxElement + 1, 20) // frequency with steps

    for (e <- elements) {
      var temp = e
      var i = 0
      while (temp > 0) {
        frequency(temp)(i) += 1

        i += 1
        temp = temp / 2
      }
    }

    println {
      (1 to maxElement).foldLeft(Int.MaxValue) {
        case (acc, e) =>
          val (steps, count) = frequency(e).indices
            .foldLeft((0, 0)) {
              case ((steps, count), i) =>
                val c = frequency(e)(i)
                if (c != 0 && count < k)
                  if (count + c <= k) (steps + i * c, count + c)
                  else (steps + i * (count + c - k), k)
                else
                  (steps, count)
            }

          if (count == k) acc min steps else acc
      }
    }
  }
}


Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b. Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1 + 2 + 3 = 6.The friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.

The first line contains a single integer a (1 ≤ a ≤ 1000) — the initial position of the first friend.  The second line contains a single integer b (1 ≤ b ≤ 1000) — the initial position of the second friend. It is guaranteed that a ≠ b.

Print the minimum possible total tiredness if the friends meet in the same point.

NoteIn the first example the first friend should move by one to the right (then the meeting happens at point 4), or the second friend should move by one to the left (then the meeting happens at point 3). In both cases, the total tiredness becomes 1.In the second example the first friend should move by one to the left, and the second friend should move by one to the right. Then they meet in the point 100, and the total tiredness becomes 1 + 1 = 2.In the third example one of the optimal ways is the following. The first friend should move three times to the right, and the second friend — two times to the left. Thus the friends meet in the point 8, and the total tiredness becomes 1 + 2 + 3 + 1 + 2 = 9.

import scala.io._
import scala.math._

object a7 {
  def main(args: Array[String]): Unit = {
    def apsum(n:Int) = n*(n+1)/2
    val pos = Source.stdin.getLines().toArray.map(_.toInt)
    val (a,b)=(pos(0), pos(1))
    val diff = abs(a-b)
    println(apsum(diff/2)+apsum(diff-diff/2))
  }
}

object A extends App {
  def l(n: Int): Int = n * (n + 1) / 2

  val a = scala.io.StdIn.readInt()
  val b = scala.io.StdIn.readInt()
  val n = (a - b).abs
  val m = n / 2

  val t = if (n == 1) 1
  else if (n % 2 == 0) 2 * l(m)
  else 2 * l(m) + (m + 1)

  println(t)
}


One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..."The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could have paid for the ride.The bus fare equals one berland ruble in High Bertown. However, not everything is that easy — no more than one child can ride for free with each grown-up passenger. That means that a grown-up passenger who rides with his k (k > 0) children, pays overall k rubles: a ticket for himself and (k - 1) tickets for his children. Also, a grown-up can ride without children, in this case he only pays one ruble.We know that in High Bertown children can't ride in a bus unaccompanied by grown-ups.Help Vasya count the minimum and the maximum sum in Berland rubles, that all passengers of this bus could have paid in total.

The input file consists of a single line containing two space-separated numbers n and m (0 ≤ n, m ≤ 105) — the number of the grown-ups and the number of the children in the bus, correspondingly.

If n grown-ups and m children could have ridden in the bus, then print on a single line two space-separated integers — the minimum and the maximum possible total bus fare, correspondingly.  Otherwise, print "Impossible" (without the quotes).

NoteIn the first sample a grown-up rides with two children and pays two rubles.In the second sample there are only children in the bus, so the situation is impossible. In the third sample there are two cases:  Each of the two grown-ups rides with one children and pays one ruble for the tickets. In this case the passengers pay two rubles in total.  One of the grown-ups ride with two children's and pays two rubles, the another one rides alone and pays one ruble for himself. So, they pay three rubles in total.

object Solution {
  def main(args: Array[String]) {
    val tokens = readLine().split(" ").map(_.toInt)
    val grownups = tokens(0)
    val kids = tokens(1)
    if (grownups == 0 && kids > 0) {
      println("Impossible")
    } else {
      printf("%d %d\n",
             grownups + (0 max (kids-grownups)),
             grownups + (0 max (kids-1)))
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  println((n, m) match {
    case(x, 0) => s"$x $x"
    case(0, x) => "Impossible"
    case(y, x) if y >= x => s"$y ${y + x - 1}"
    case(y, x) => s"$x ${y + x - 1}"
  })

}

//http://rextester.com scala 2.11.7
import scala.io.Source
object Rextester extends App{
    val a=Source.stdin.getLines();val Array(b,c)=a.next().split(' ').map(_.toInt)
    if(b<1&c>0)print("Impossible")
    else{
        var d=b+c-1
        if(c==0)d=b
        print(math.max(b,c)+" "+d)
    }
}

import scala.io.Source;object a{def main(args:Array[String]){val z=Source.stdin.getLines();val Array(a,b)=z.next().split(' ').map(_.toInt);if(a<1&b>0)print("Impossible")else print(math.max(a,b)+" "+{if(b>0)a+b-1 else a})}}

//rextester.com:2.11.7--codeforces.com:2.11.8
import scala.io.Source
object Rextester extends App{
    val z=Source.stdin.getLines();val Array(a,b)=z.next().split(' ').map(_.toInt)
    if(a<1&b>0)print("Impossible")
    else print(math.max(a,b)+" "+{if(b>0)a+b-1 else a})
}

//rextester.com:2.11.7--codeforces.com:2.11.8
import scala.io.Source
object a extends App{
    val z=Source.stdin.getLines();val Array(a,b)=z.next().split(' ').map(_.toInt)
    if(a<1&b>0)print("Impossible")
    else print(math.max(a,b)+" "+{if(b>0)a+b-1 else a})
}

//2.12.5 | JDoodle.Com & 2.12 | CodeForces.Com
import scala.io.Source

object Solution {
    def main(args: Array[String]) {
        val input = Source.stdin.getLines()

        val Array(grown_ups, children) = input.next().split(' ').map(_.toInt)

        if (grown_ups < 1 & children > 0)
            print("Impossible")
        else
            print(math.max(grown_ups, children) + " " + {if (children > 0) grown_ups + children - 1 else grown_ups})
    }
}

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 P190A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N, M = sc.nextInt

  val res = (N, M) match {
      case (0, 0) => "0 0"
      case (0, _) => "Impossible"
      case (x, 0) => List(x, x).mkString(" ")
      case (x, y) => List(x max y, x + y - 1).mkString(" ")
  }

  out.println(res)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val min = n + (m - n).max(0)
    val max = n + (m - 1).max(0)
    if (n == 0 && m == 0) println("0 0")
    else if (n == 0) println("Impossible")
    else println(min + " " + max)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  println((n, m) match {
    case(0, x) => "Impossible"
    case(x, 0) => s"$x $x"
    case(y, x) if y >= x => s"$y ${y + x - 1}"
    case(y, x) => s"$x ${y + x - 1}"
  })

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  println((n, m) match {
    case(0, x) => "Impossible"
    case(y, x) if y >= x => s"$y ${y + x - 1}"
    case(y, x) => s"$x ${y + x - 1}"
  })

}

//http://rextester.com scala 2.11.7
import scala.io.Source
object Rextester extends App{
    val in=Source.stdin.getLines();val Array(a,b)=in.next().split(' ').map(_.toInt)
    if(a>0&b>=0){
        var c=a+b-1
        if(b==0)c=a
        print(math.max(a,b)+" "+c)
    }
    else print("Impossible")
}

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 P190A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N, M = sc.nextInt

  val res = (N, M) match {
      case (0, _) => "Impossible"
      case (x, 0) => List(x, x).mkString(" ")
      case (x, y) => List(x max y, x + y - 1).mkString(" ")
  }

  out.println(res)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val min = n + (m - n).max(0)
    val max = n + (m - 1).max(0)
    if (n == 0) println("Impossible")
    else println(min + " " + max)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val min = n + (m - n).max(0)
    val max = n + m - 1
    if (n == 0) println("Impossible")
    else println(min + " " + max)
  }
}


A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.As before, the chessboard is a square-checkered board with the squares arranged in a 8 × 8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.

The input file contains 8 lines, each of the lines contains 8 characters. The given matrix describes the client's requirements, W character stands for a white square, and B character — for a square painted black. It is guaranteed that client's requirments can be fulfilled with a sequence of allowed strokes (vertical/column or horizontal/row).

Output the only number — the minimum amount of rows and columns that Kalevitch has to paint on the white chessboard to meet the client's requirements.

WWWBWWBW
BBBBBBBB
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW

WWWWWWWW
BBBBBBBB
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW

object P7A {
    def main(args : Array[String]) {
        val a = Array.fill(8){readLine}
        val af = a filter {_ != "BBBBBBBB"}
        val c = 0 until 8 count {n => af exists {_(n) == 'B'}}
        println(8 - af.size + c)
    }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val data = (1 to 8).map(_ => in.next())
  val lines = data.count(_.forall(_ == 'B'))
  val rows = data.find(_.exists(_ == 'W')).map(_.count(_ == 'B')).getOrElse(0)
  println(lines + rows)
}

import java.util.Scanner

object A7Chess extends App {

  val scanner = new Scanner(System.in)

  val in = Array.ofDim[Cell](8, 8)

  var result = 0

  for (x <- 0 until 8) yield {
    val str = scanner.next()
    in(x) = str.map({
      case 'W' => Cell(color = false)
      case 'B' => Cell(color = true)
    }).toArray
  }

  (0 until 8) foreach(i => solve(in(_)(i)))
  (0 until 8) foreach(i => solve(in(i)(_)))

  println(result)

  def solve(function: (Int) => Cell): Unit = {
    if (paintedWithBlack(function)) {
      visit(function)
      result += 1
    }
  }

  def visit(function: (Int) => Cell): Unit = {
    (0 until 8).foreach(function(_).visited = true)
  }

  def paintedWithBlack(function: (Int) => Cell): Boolean = {
    (0 until 8).forall(function(_).color) && (0 until 8).exists(!function(_).visited)
  }

  case class Cell(color: Boolean, var visited: Boolean = false)

}

object A7 {

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

  def main(args: Array[String]): Unit = {
    val in = Array.fill(8)(read.toCharArray)
    val res = {
      (0 until 8).map{j => (0 until 8).map(i=>in(i)(j))}.count(_.forall(_ == 'B')) +
      in.count(_.forall(_ == 'B'))
    }
    if(res == 16)
      println("8")
    else
      println(res)
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object P7A {
    def main(args : Array[String]) {
        val a = Array.fill(8){readLine} filter {_ != "BBBBBBBB"}
        val c = 0 until 8 count {n => a exists {_(n) == 'B'}}
        println(8 - a.size + c)
    }
}

object P7A {
    def main(args : Array[String]) {
        val a = Array.fill(8){readLine}
        val af = a filter {_ != "BBBBBBBB"}
        val c = 0 until 8 count {n => af exists {_(n) == 'W'}}
        println(8 - af.size + c)
    }
}

object P7A {
    def main(args : Array[String]) {
        val a = Array.fill(8){readLine}
        val af = a filter {_ != "BBBBBBBB"}
        val c = 0 until 8 count {
            n : Int => af forall {_(n) == 'B'}
        }
        println(8 - af.size + c)
    }
}


Count the number of distinct sequences a1, a2, ..., an (1 ≤ ai) consisting of positive integers such that gcd(a1, a2, ..., an) = x and . As this number could be large, print the answer modulo 109 + 7.gcd here means the greatest common divisor.

The only line contains two positive integers x and y (1 ≤ x, y ≤ 109).

Print the number of such sequences modulo 109 + 7.

NoteThere are three suitable sequences in the first test: (3, 3, 3), (3, 6), (6, 3).There are no suitable sequences in the second test.

object Main extends App {

  import scala.io.StdIn
  val MOD: Integer = 1000000007

  val Array(x, y) = StdIn.readLine().split(" ").map(_.toInt)
  var mem = collection.mutable.Map[Integer, Integer]()

  if (y % x > 0) {
    println(0)
  }
  else {
    println(f(y/x))
  }

  def f(n: Integer): Integer = {

    if (n == 1) return 1

    if (mem contains(n))
      return mem(n)

    var res = pow2(n-1)

    for (d <- 2 to Math.round(Math.sqrt(1*n)).toInt)
      if (n % d == 0) {
        res = ((res - f(n / d))%MOD+MOD)%MOD
        if (d != n / d) res = ((res - f(d))%MOD+MOD)%MOD
      }
    res -= 1
    mem += n -> (res%MOD+MOD)%MOD
    mem(n)
  }

  def pow2(x: Integer): Integer = {
    x%2 match {
      case 0 if x > 0 => {
        val res = pow2(x/2)%MOD
        ((1l*res*res)%MOD).toInt
      }
      case 0 if x == 0 => 1
      case _ => {
        (2 * pow2(x-1) % MOD) % MOD
      }
    }
  }

}

import java.util.Scanner

object UnusualSequencesJudgeSolution {
  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }
  def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {
    override def apply(key: I) = getOrElseUpdate(key, f(key))
  }

  val MOD: Long = 1000000007

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

    def count(L: Int): Long = {
      if (L <= 2) 1
      else {
        def pow(b: Long, p: Long): Long = {
          if (p == 0) 1L
          else if (p % 2 == 0) {
            val result = pow(b, p / 2);
            (result * result) % MOD
          }
          else (b * pow(b, p - 1)) % MOD
        }
        def divisors(x: Int): List[Int] = {
          def divisorsRec(d: Int): List[Int] = {
            if (1L * d * d > x) List.empty
            else if (x % d == 0) {
              if (d * d == x) d :: divisorsRec(d + 1)
              else d :: x / d :: divisorsRec(d + 1)
            }
            else divisorsRec(d + 1)
          }
          divisorsRec(1)
        }

        lazy val D: Int => Long = memoize (l => (pow(2, l - 1) - divisors(l).filter(_ != l).map(d => D(d)).foldLeft(0L)((x, sum) => (x + sum) % MOD) + MOD) % MOD)

        D(L)
      }
    }
    def solve(): Long = {
      if (y % x != 0) 0
      else {
        count(y / x)
      }
    }
    println(solve())
  }
}

import java.util.Scanner

object UnusualSequencesJudgeSolution {
  val MOD: Long = 1000000007

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

    def count(L: Int): Long = {
      if (L <= 2) 1
      else {
        def pow(b: Long, p: Long): Long = {
          if (p == 0) 1L
          else if (p % 2 == 0) {
            val result = pow(b, p / 2);
            (result * result) % MOD
          }
          else (b * pow(b, p - 1)) % MOD
        }
        def divisors(x: Int): List[Int] = {
          def divisorsRec(d: Int): List[Int] = {
            if (1L * d * d > x) List.empty
            else if (x % d == 0) {
              if (d * d == x) d :: divisorsRec(d + 1)
              else d :: x / d :: divisorsRec(d + 1)
            }
            else divisorsRec(d + 1)
          }
          divisorsRec(1)
        }

        val DP = collection.mutable.Map[Int, Long]()
        def D(l: Int): Long = {
          if (DP.contains(l)) DP(l)
          else {
            val result = (pow(2, l - 1) - divisors(l).filter(_ != l).map(d => D(d)).foldLeft(0L)((x, sum) => (x + sum) % MOD) + MOD) % MOD
            DP.update(l, result)
            result
          }
        }

        D(L)
      }
    }
    def solve(): Long = {
      if (y % x != 0) 0
      else {
        count(y / x)
      }
    }
    println(solve())
  }
}

object Main extends App {

  import scala.io.StdIn
  val MOD: Integer = 1000000007

  val Array(x, y) = StdIn.readLine().split(" ").map(_.toInt)
  var mem = collection.mutable.Map[Integer, Integer]()

  if (y % x > 0) {
    println(0)
  }
  else {
    println(f(y/x))
  }

  def f(n: Integer): Integer = {

    if (mem contains(n))
      return mem(n)

    var res = pow2(n-1)

    for (d <- 2 to Math.round(Math.sqrt(1*n)).toInt)
      if (n % d == 0) {
        res = ((res - f(n / d))%MOD+MOD)%MOD
        if (d != n / d) res = ((res - f(d))%MOD+MOD)%MOD
      }
    res -= 1
    mem += n -> (res%MOD+MOD)%MOD
    mem(n)
  }

  def pow2(x: Integer): Integer = {
    x%2 match {
      case 0 if x > 0 => {
        val res = pow2(x/2)%MOD
        ((1l*res*res)%MOD).toInt
      }
      case 0 if x == 0 => 1
      case _ => {
        (2 * pow2(x-1) % MOD) % MOD
      }
    }
  }

}

import java.util.Scanner

object UnusualSequences {
  val MOD: Long = 1000000007

  class Matrix (val M: Array[Array[Long]]) {
    val R = M.size
    val C = M(0).size
    def *(other: Matrix): Matrix = {
      val result = Array.tabulate(R, other.C)((r, c) => 0.until(C).map(x => M(r)(x) * other.M(x)(c)).sum)
      new Matrix(result)
    }
    def power(pow: Long): Matrix = {
      if (pow == 0) Matrix.getIdentity(R, C)
      else if (pow % 2 != 0) this * power(pow - 1)
      else {
        val result = power(pow / 2)
        result * result
      }
    }
  }
  object Matrix {
    def apply(M: Array[Array[Long]]) = new Matrix(M)
    def getIdentity(r: Int, c: Int) = {
      new Matrix(Array.tabulate(r, c)((i, j) => if (i == j) 1 else 0))
    }
  }

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

    def count(L: Int): Long = {
      if (L <= 2) 1
      else {
        val base = Matrix(Array(Array(1), Array(0), Array(1)))
        val matrix = Matrix(Array(Array(0, 1, 1), Array(1, 1, 0), Array(0, 0, 2)))

        val result = matrix.power(L - 1) * base
        result.M(0)(0)
      }
    }
    def solve(): Long = {
      if (y % x != 0) 0
      else {
        count(y / x)
      }
    }
    println(solve())
  }
}

import java.util.Scanner

object UnusualSequencesJudgeSolution {
  val MOD: Long = 1000000007

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

    def count(L: Int): Long = {
      if (L <= 2) 1
      else {
        def pow(b: Long, p: Long): Long = {
          if (p == 0) 1
          else if (p % 2 == 0) {
            val result = pow(b, p / 2);
            (result * result) % MOD
          }
          else (b * pow(b, p - 1)) % MOD
        }
        def divisors(x: Int): List[Int] = {
          def divisorsRec(d: Int): List[Int] = {
            if (1L * d * d > x) List.empty
            else if (x % d == 0) {
              if (d * d == x) d :: divisorsRec(d + 1)
              else d :: x / d :: divisorsRec(d + 1)
            }
            else divisorsRec(d + 1)
          }
          divisorsRec(1)
        }

        val DP = collection.mutable.Map[Int, Long]()
        def D(l: Int): Long = {
          if (DP.contains(l)) DP(l)
          else {
            val result = pow(2, l - 1) - divisors(l).filter(_ != l).map(d => D(d)).foldLeft(0L)((x, sum) => (x + sum) % MOD)
            DP.update(l, result)
            result
          }
        }

        D(L)
      }
    }
    def solve(): Long = {
      if (y % x != 0) 0
      else {
        count(y / x)
      }
    }
    println(solve())
  }
}


There are three doors in front of you, numbered from $$$1$$$ to $$$3$$$ from left to right. Each door has a lock on it, which can only be opened with a key with the same number on it as the number on the door.There are three keys — one for each door. Two of them are hidden behind the doors, so that there is no more than one key behind each door. So two doors have one key behind them, one door doesn't have a key behind it. To obtain a key hidden behind a door, you should first unlock that door. The remaining key is in your hands.Can you open all the doors?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 18$$$) — the number of testcases. The first line of each testcase contains a single integer $$$x$$$ ($$$1 \le x \le 3$$$) — the number on the key in your hands. The second line contains three integers $$$a, b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 3$$$) — the number on the key behind each of the doors. If there is no key behind the door, the number is equal to $$$0$$$. Values $$$1, 2$$$ and $$$3$$$ appear exactly once among $$$x, a, b$$$ and $$$c$$$.

For each testcase, print "YES" if you can open all the doors. Otherwise, print "NO".

import scala.io.StdIn._
import scala.util.control.Breaks._

object Main {
  def main(args: Array[String]): Unit = {
      val t: Int = readInt()
      for (_ <- 1 to t) {
          var curr_door: Int = readInt()
          val A: Array[Int] = readLine().split(" ").map(_.toInt)
          var a: Boolean = true
          breakable {for (_ <- 1 to 3) {
              if (curr_door == 0) {
                  a = false
                  break
              }
              curr_door = A(curr_door-1)
          }}
          if (a) println("YES") else println("NO")
      }
    }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val A = new Array[Int](3)
      tokenizer = new StringTokenizer(input.readLine())
      A(0) = tokenizer.nextToken().toInt
      A(1) = tokenizer.nextToken().toInt
      A(2) = tokenizer.nextToken().toInt
      var t = false
      val a = A(n-1)
      if (a != 0) {
        val b = A(a-1)
        if (b!=0) {
          t = true
        }
      }
      if (t) {
        println("YES")
      }
      else {
        println("NO")
      }
    }
  }
}


You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand.The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands.Ambidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand.Please find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.

The only line contains three integers l, r and a (0 ≤ l, r, a ≤ 100) — the number of left-handers, the number of right-handers and the number of ambidexters at the training.

Print a single even integer — the maximum number of players in the team. It is possible that the team can only have zero number of players.

NoteIn the first example you can form a team of 6 players. You should take the only left-hander and two ambidexters to play with left hand, and three right-handers to play with right hand. The only person left can't be taken into the team.In the second example you can form a team of 14 people. You have to take all five left-handers, all five right-handers, two ambidexters to play with left hand and two ambidexters to play with right hand.

object aTask1 {
  import scala.io.StdIn.{readLine, readInt}
  def main(args: Array[String]):Unit = {
    val l::r::a::Nil = readLine.split(" ").map(_.toInt).toList
    val p1 = math.min(l,r)
    val p2 = math.min(math.abs(l - r), a)
    val p3 = if (a - p2 >0) (a-p2)/2 else 0
    println((p1+p2+p3) * 2)
  }
}

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val l, r, a = sc.nextInt
    val u = a.min((r - l).abs)

    println(2 * (l.min(r) + u + (a - u)/2))
  }
}

object A extends App {
  val Array(l, r, a) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val d = (l max r) - (l min r)
  val t = a min d
  val s = (l min r) + t + (0 max (a - t)) / 2

  println(2 * s)
}

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

object Solution {
  // VM options: -Xmx1024m -Xss1024m
  private val inputFilename = "input.txt"
  private val outputFilename = "output.txt"

  def main(args: Array[String]): Unit = {
    new Solution(args.contains("DEBUG_MODE")).run(args)
  }
}

case class Solution(isDebug: Boolean) {
  def solve(): Unit = {
    var l = nextInt
    var r = nextInt
    var a = nextInt
    val addL = Math.max(0, Math.min(r - l, a))
    l += addL
    a -= addL
    val addR = Math.max(0, Math.min(l - r, a))
    r += addR
    a -= addR
    l += a / 2
    r += a / 2
    println(s"${Math.min(l, r) * 2}")
  }

  def run(args: Array[String]): Unit = {
    if (isDebug) {
      in = new BufferedReader(new InputStreamReader(new FileInputStream(Solution.inputFilename)))
      //      in = new BufferedReader(new InputStreamReader(System.in))
    } else {
      in = new BufferedReader(new InputStreamReader(System.in))
    }
    out = new PrintWriter(System.out)
    //    out = new PrintWriter(outputFilename)

    //    val t = nextInt
    val t = 1
    (0 until t).foreach { i =>
      //      out.print(s"Case #${i + 1}: ")
      solve()
    }
    in.close()
    out.flush()
    out.close()
  }

  private var in: BufferedReader = _
  private var line: StringTokenizer = _
  private var out: PrintWriter = _

  private[this] def println(s: String = ""): Unit = out.println(s)

  private[this] def nextIntArray(n: Int) = (0 until n).map(_ => nextInt).toArray

  private[this] def nextLongArray(n: Int) = (0 until n).map(_ => nextLong).toArray

  private[this] def nextInt = nextToken.toInt

  private[this] def nextLong = nextToken.toLong

  private[this] def nextDouble = nextToken.toDouble

  private[this] def nextToken = {
    while (line == null || !line.hasMoreTokens) {
      line = new StringTokenizer(in.readLine)
    }
    line.nextToken
  }
}


The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose — to show the developer the imperfection of their protection.The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of 12345 should lead to 13542. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number 12345 is 455 422 043 125 550 171 232. The answer is the 5 last digits of this result. For the number 12345 the answer should be 71232.Vasya is going to write a keygen program implementing this algorithm. Can you do the same?

The only line of the input contains a positive integer five digit number for which the activation code should be found.

Output exactly 5 digits without spaces between them — the found activation code of the program.

import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

  def C(n: Int, k: Int) = {
    var res = BigInt(1)
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

  def fact(n: Int) = {
    var res = BigInt(1)
    for (i <- 1 to n) {
      res = res * i
    }
    res
  }

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

  def lcm(a: Long, b: Long) = a / gcd(a, b) * b

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

    val s = in.nextLine()

    val t = "" + s(0) + s(2) + s(4) + s(3) + s(1)

    val x = BigInt(t)
    val y = (x * x * x * x * x).toString()

    println(y.substring(y.length() - 5))
  }
}

import scala.io.StdIn

object CrackingTheCode {

  def main(args: Array[String]) {
    val MOD = 100000
    val n = StdIn.readLong()
    val res = Array(n / 10000, (n / 100) % 10, n % 10, (n / 10) % 10, (n / 1000) % 10)
    val k = res(0) * 10000 + res(1) * 1000 + res(2) * 100 + res(3) * 10 + res(4)
    def pow(n : Int) : Long = {
      if (n == 0) 1
      else (k * pow(n - 1)) % MOD
    }
    println("%05d".format(pow(5)))
  }

}

import scala.io.StdIn

object CrackingTheCode {

  def main(args: Array[String]) {
    val MOD = 100000
    val n = StdIn.readLong()
    val res = Array(n / 10000, (n / 100) % 10, n % 10, (n / 10) % 10, (n / 1000) % 10)
    val k = res(0) * 10000 + res(1) * 1000 + res(2) * 100 + res(3) * 10 + res(4)
    def pow(n : Int) : Long = {
      if (n == 0) 1
      else (k * pow(n - 1)) % MOD
    }
    println(pow(5))
  }

}


Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?

The only line of the input data contains a non-empty string consisting of letters "С" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "С", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.

Print the only number — the minimum number of times Polycarpus has to visit the closet.

CPCPCPC CCCCCCPPPPPP CCCCCCPPCPPPPPPPPPP CCCCCCCCCC

NoteIn the first sample Polycarpus needs to take one item to the closet 7 times.In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).

import scala.collection.mutable.ArrayBuffer

object Flask {
  def main(args: Array[String]): Unit = {
    var s = readLine
    var total = 0
    var symbol = s(0); var count = 1

    (1 until s.size).foreach(i => {
        if (s(i) == symbol && count < 5) count += 1
        else { count = 1; symbol = s(i); total += 1 }
    })
    println(total + 1)
  }
}

object main {
    def main(args: Array[String]) = {
        val str = readLine()

        var last:Char = str apply 0
        var n = 0
        var res = 0

        str foreach ((x:Char) => {
            if (last == x) {
                if (n == 5) {
                    n = 1
                    res += 1
                } else {
                    n += 1
                }
            } else {
                if (n != 0) {
                    res += 1
                }
                n = 1
                last = x

            }
        })

        println(res + 1)
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val res = str.tail.foldLeft((0, 1, str.head)) {
    case ((count, soFar, prev), el) if soFar == 5 => (count + 1, 1, el)
    case ((count, soFar, prev), el) if el == prev => (count, soFar + 1, el)
    case ((count, soFar, prev), el) => (count + 1, 1, el)
  }
  println(res._1 + (if (res._2 != 0) 1 else 0))
}

object A137 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    var res = 0
    var curr = 1
    for(i <- 1 to str.length) {
      if(i == str.length || str(i) != str(i-1)) {
        res += (curr+4)/5
        curr = 1
      } else {
        curr += 1
      }
    }
    out.println(res)
    out.close()
  }

  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")))
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object P137A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val CP = sc.nextLine.toList

  def solve(): Int = {

    @tailrec
    def loop(n: Int, carry: List[Char], wall: List[Char]): Int = (carry, wall) match {
        case (_, Nil) => n
        case (Nil, y :: ys) => loop(n, y :: Nil, ys)
        case (xs, ys) if xs.size == 5     => loop(n + 1, Nil, ys)
        case (x :: xs, y :: ys) if x == y => loop(n, y :: x :: xs, ys)
        case (x :: xs, y :: ys) if x != y => loop(n + 1, y :: Nil, ys)
      }

    loop(0, Nil, CP) + 1
  }

  out.println(solve)
  out.close
}

object A137 {
	def main(args: Array[String]) {
		val s: String = readLine
		var res: Int = 0
		var curc: Char = '?'
		var curval: Int = 5
		for (c <- s)
			if (c == curc && curval < 5)
				curval += 1
			else {
				res += 1
				curval = 1
				curc = c
			}
		println(res)
	}
}

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)
  def readLine = reader.readLine

  def calc(str: String): Double = {
    if(str.length == 0) 0
    else {
      val ch = str.head
      Math.ceil(0.2 * str.takeWhile(_ == ch).length) + calc(str.dropWhile(_ == ch))
    }
  }
  def ans = calc(readLine)

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

object Main {
  def main(args: Array[String]) = {
    val s = readLine()

    var cur = ' '
    var inHands = 0
    var count = 0
    s.foreach{ c =>
      if (c != cur) {
        inHands = 0
        count += 1
        cur = c
      } else if (inHands == 5) {
        count += 1
        inHands = 0
      }
      inHands += 1
    }
    println(count)
  }
}

object main {
	def main(args: Array[String]) = {
		val str = readLine()

		var last:Char = str apply 0
		var n = 0
		var res = 1

		str foreach ((x:Char) => {
			if (last == x) {
				if (n == 5) {
					n = 0
					res += 1
				} else {
					n += 1
				}
			} else {
				if (n != 0) {
					res += 1
				}
				n += 1
				last = x

			}
		})

		println(res)
	}
}

object main {
    def main(args: Array[String]) = {
        val str = readLine()

        var last:Char = str apply 0
        var n = 0
        var res = 0

        str foreach ((x:Char) => {
            if (last == x) {
                if (n == 5) {
                    n = 1
                    res += 1
                } else {
                    n += 1
                }
            } else {
                if (n != 0) {
                    res += 1
                }
                n += 1
                last = x

            }
        })

        println(res + 1)
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val res = str.tail.foldLeft((0, 0, str.head)) {
    case ((count, soFar, prev), el) if soFar == 5 => (count + 1, 1, el)
    case ((count, soFar, prev), el) if el == prev => (count, 1, el)
    case ((count, soFar, prev), el) => (count + 1, 1, el)
  }
  println(res._1 + (if (res._2 != 0) 1 else 0))
}


Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.

The first line contains one integer n (1 ≤ n ≤ 360)  — the number of pieces into which the delivered pizza was cut. The second line contains n integers ai (1 ≤ ai ≤ 360)  — the angles of the sectors into which the pizza was cut. The sum of all ai is 360.

Print one integer  — the minimal difference between angles of sectors that will go to Vasya and Petya.

NoteIn first sample Vasya can take 1 and 2 pieces, Petya can take 3 and 4 pieces. Then the answer is |(90 + 90) - (90 + 90)| = 0.In third sample there is only one piece of pizza that can be taken by only one from Vasya and Petya. So the answer is |360 - 0| = 360.In fourth sample Vasya can take 1 and 4 pieces, then Petya will take 2 and 3 pieces. So the answer is |(170 + 10) - (30 + 150)| = 0.Picture explaning fourth sample:Both red and green sectors consist of two adjacent pieces of pizza. So Vasya can take green sector, then Petya will take red sector.

import java.util.Scanner
import scala.language.implicitConversions

object PizzaSeparation {

  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }

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

    val N = sc.nextInt()
    val A = for (i <- 0.until(N)) yield sc.nextInt()

    def bestPrefix(xs: List[Int], s: Int): Int = xs match {
      case Nil => 360
      case x :: rest => val ns = s + x; Math.min(Math.abs(360 - 2 * ns), bestPrefix(rest, ns))
    }

    def solve(xs: List[Int]): Int = xs match {
      case Nil => 360
      case x :: rest => Math.min(bestPrefix(xs, 0), solve(rest))
    }

    println(solve(A.toList))
  }
}

import java.io.FileReader
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable

object Solution {
  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val widths = readIntLine()

    val sum = Array.ofDim[Int](widths.length, widths.length + 1)

    for (i <- widths.indices) {
      for (j <- i + 1 to widths.length) {
        sum(i)(j) = sum(i)(j - 1) + widths(j - 1)
      }
    }

    val minDiff = widths.indices.map{
      i =>
        (i + 1 to widths.length).map{
          j =>
            Math.abs(180 - sum(i)(j)) * 2
        }.min
    }.min

    println(minDiff)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

  def readIntLine(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    readLine().split(" ").map(BigInt.apply)
  }
}

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 as = readInts(n)

  var min = 360

  for {
    i <- 0 until n
    j <- i to n
  } {
    val s1 = as.view(i, j).sum
    val s2 = 360 - s1
    val d = Math.abs(s1 - s2)
    if (d < min) min = d
  }

  println(min)
}

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

  val Array(n) = readInts(1)
  val as = readInts(n)

  var min = 360
  var s1 = 0
  var l, r = 0

  def check(s1: Int) = {
    val s2 = 360 - s1
    val d = Math.abs(s1 - s2)
    if (d < min) min = d
  }

  while (r < n) {
    while (s1 < 180 && r < n) {
      s1 += as(r)
      r += 1
      check(s1)
    }
    while (s1 >= 180) {
      s1 -= as(l)
      l += 1
      check(s1)
    }
  }

  println(min)
}

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

  val Array(n) = readInts(1)
  val as = readInts(n)

  var min = 360
  var s1 = 0
  var l, r = 0

  def check(s1: Int) = {
    val s2 = 360 - s1
    val d = Math.abs(s1 - s2)
    if (d < min) min = d
  }

  while (r < n) {
    while (s1 < 180 && r < n) {
      s1 += as(r)
      r += 1
    }
    check(s1)
    while (s1 >= 180) {
      s1 -= as(l)
      l += 1
    }
    check(s1)
  }

  println(min)
}