Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance between the minimum and the maximum elements. The distance between two elements is considered to be equal to the absolute difference between their positions.

The first line of the input contains a single integer n (2 ≤ n ≤ 100) — the size of the permutation. The second line of the input contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n), where ai is equal to the element at the i-th position.

Print a single integer — the maximum possible distance between the minimum and the maximum elements Nicholas can achieve by performing exactly one swap.

NoteIn the first sample, one may obtain the optimal answer by swapping elements 1 and 2.In the second sample, the minimum and the maximum elements will be located in the opposite ends of the array if we swap 7 and 2.In the third sample, the distance between the minimum and the maximum elements is already maximum possible, so we just perform some unnecessary swap, for example, one can swap 5 and 2.

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  lines.next()
  val data = lines.next().split(' ').map(_.toInt)
  if (data.head == 1 || data.last == 1 || data.last == data.length || data.last == data.length) {
    println(data.length - 1)
  } else {
    val indexOne = data.indexOf(1) + 1
    val indexN = data.indexOf(data.length) + 1
    var first = Math.max(indexOne - 1, indexN - 1)
    var last = Math.max(data.length - indexOne, data.length - indexN)
    println(Math.max(first, last))
  }

}

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

object Permutation extends App {
  val n = readInt()
  val arr = readLine().split(" ").map(_.toInt)

  val pos1 = arr.indexOf(1)
  val posMax = arr.indexOf(n)
  val diff = abs(pos1-posMax)

  if(diff == n){
    println(n-1)
  }else{
    if(pos1>posMax){
      if((n-1)-pos1>= posMax){
        println((n-1)-posMax)
      }else{
        println(pos1)
      }
    }else{
      if((n-1)-posMax>= pos1){
        println((n-1)-pos1)
      }else{
        println(posMax)
      }
    }

  }
}

object A676 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val idx1 = in.indexOf(1)
    val idxN = in.indexOf(n)
    var max = math.abs(idxN - idx1)
    for(i <- 0 until n if i != idxN) {
      max = math.max(max, math.abs(idxN - i))
    }
    for(i <- 0 until n if i != idx1) {
      max = math.max(max, math.abs(idx1 - i))
    }
    println(max)
  }

  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 Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _676A extends CodeForcesApp {
  override def apply(io: IO) = {
    val a = io[Vector[Int]]
    val n = a.length
    val (p, q) = (a.indexOf(1) + 1, a.indexOf(n) + 1)
    //debug(n, p, q)
    val ans = (p - 1).abs max (n - p) max (q - 1).abs max (n - q)
    io += ans
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def 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
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  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 PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).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 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 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 SortedExtensions[A, C[A] <: collection.SortedSet[A]](val s: C[A]) extends AnyVal {
    def greaterThanOrEqualTo(a: A): Option[A] = s.from(a).headOption
    def lessThan(a: A): Option[A] = s.until(a).lastOption
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    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
  }
  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 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)
  }
  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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  implicit class FuzzyDouble(x: Double)(implicit eps: Double = 1e-9) {
    def >~(y: Double) = x > y+eps
    def >=~(y: Double) = x >= y-eps
    def ~<(y: Double) = x < y-eps
    def ~=<(y: Double) = x <= y+eps
    def ~=(y: Double) = ~=<(y) && >=~(y)
  }
  @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]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

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

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.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[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def array[A]: Write[Array[A]] = Write(_ mkString " ")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

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

object _676A extends CodeForcesApp {
  override def apply(io: IO) = {
    val a = io[Vector[Int]]
    val n = a.length
    val (p, q) = (a.indexOf(1), a.indexOf(n))
    val ans = p max (n - p) max q max (n - q)
    io += (ans - 1)
  }
}
/****************************[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
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  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 PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).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 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 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 SortedExtensions[A, C[A] <: collection.SortedSet[A]](val s: C[A]) extends AnyVal {
    def greaterThanOrEqualTo(a: A): Option[A] = s.from(a).headOption
    def lessThan(a: A): Option[A] = s.until(a).lastOption
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    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
  }
  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 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)
  }
  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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  implicit class FuzzyDouble(x: Double)(implicit eps: Double = 1e-9) {
    def >~(y: Double) = x > y+eps
    def >=~(y: Double) = x >= y-eps
    def ~<(y: Double) = x < y-eps
    def ~=<(y: Double) = x <= y+eps
    def ~=(y: Double) = ~=<(y) && >=~(y)
  }
  @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]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

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

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.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[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def array[A]: Write[Array[A]] = Write(_ mkString " ")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}


This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt.To make a toast, each friend needs nl milliliters of the drink, a slice of lime and np grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?

The first and only line contains positive integers n, k, l, c, d, p, nl, np, not exceeding 1000 and no less than 1. The numbers are separated by exactly one space.

Print a single integer — the number of toasts each friend can make.

NoteA comment to the first sample: Overall the friends have 4 * 5 = 20 milliliters of the drink, it is enough to make 20 / 3 = 6 toasts. The limes are enough for 10 * 8 = 80 toasts and the salt is enough for 100 / 1 = 100 toasts. However, there are 3 friends in the group, so the answer is min(6, 80, 100) / 3 = 2.

import java.util.Scanner
object Cola {

  def main(args: Array[String] ) {
    val scanner = new Scanner(System.in)
    val n, k, l, c, d, p, nl, np = scanner.nextInt();
    val limes = c*d/n
    val cola = k*l/(n*nl)
    val salt = p/(n*np)

    println(Math.min(Math.min(limes,cola),salt))

  }
}

/**
 * Created by IntelliJ IDEA.
 * User: cm
 * Date: 17.02.12
 * Time: 23:06
 * To change this template use File | Settings | File Templates.
 */

object P151A extends App {
  val Array(n, k, l, c, d, p, nl, np) = readLine().split(" ").map(_.toInt)
  print(List(k*l/nl,c*d,p/np).min / n)
}

import java.util.StringTokenizer

object _151A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val Array(n, k, l, c, d, p, nl, np) = (1 to 8).map(i => next.toInt).toArray
  val ans = (k * l / nl) min (c * d) min (p / np)
  println(ans / n)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k, l, c, d, p, nl, np) = in.next().split(" ").map(_.toInt)
  println(Math.min(c * d, Math.min((k * l) / nl, p / np)) / n)
}

    object Main
    {
        def min(a:Int, b:Int, c:Int):Int =
        {
            var aorb = 0;
            if (a < b)
            {
                aorb = a
            }
            else
            {
                aorb = b
            }

            if (c < aorb)
                return c;
            return aorb;
        }
        def main(args:Array[String])
        {
            val a = readLine().split(" ").map(i => i.toInt);
            val n = a(0);
            val k = a(1);
            val l = a(2);
            val c = a(3);
            val d = a(4);
            val p = a(5);
            val nl = a(6);
            val np = a(7);

            println(min(k * l / nl, c * d, p / np) / n);
        }
    }

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

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

  val n, k, l, c, d, p, nl, np  = sc.nextInt

  val drink = (k * l) / nl
  val lime = c * d
  val salt = p / np

  val answer = List(drink, lime, salt).min / n

  out.println(answer)
  out.close
}

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)

  val Array(n, k, l, c, d, p, nl, np) = readInts
  def ans = ((k * l) / nl min c * d min p / np) / n

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

object Main {
  def main(args: Array[String]) {
    val nklcdpnlnp = readLine().split(" ").map(_.toInt)
    val n = nklcdpnlnp(0)
    val k = nklcdpnlnp(1)
    val l = nklcdpnlnp(2)
    val c = nklcdpnlnp(3)
    val d = nklcdpnlnp(4)
    val p = nklcdpnlnp(5)
    val nl = nklcdpnlnp(6)
    val np = nklcdpnlnp(7)

    val tests = Seq(k * l / nl) ++ Seq(c * d) ++ Seq(p / np)
    println(tests.min / n)
  }
}

import java.util.Scanner

object SoftDrinking {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt
    val k = sc.nextInt
    val l = sc.nextInt
    val c = sc.nextInt
    val d = sc.nextInt
    val p = sc.nextInt
    val nl = sc.nextInt
    val np = sc.nextInt
    println(List(k * l / nl, c * d, p / np).min / n)
  }
}

import java.util.StringTokenizer

object _151A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val Array(n, k, l, c, d, p, nl, np) = (1 to 8).map(i => next.toInt).toArray
  val ans = (n * k / nl) min (c * d) min (p / np)
  println(ans / n)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k, l, c, d, p, nl, np) = in.next().split(" ").map(_.toInt)
  println(Math.min(c * d, Math.min(n / nl, p / np)) / n)
}


Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.

The only line contains a positive integer n (1 ≤ n ≤ 10100000). This number doesn't have leading zeroes.

Output the least super lucky number that is more than or equal to n.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next().toInt

  def next(a: Int): Option[Long] = {
    if (a.toBinaryString.length < 3)
      None
    else {
      val candidate = a.toBinaryString.tail
      if (candidate.length % 2 == 0 && candidate.count(_ == '0') == candidate.count(_ == '1'))
        Some(candidate.map(ch => if (ch == '0') '4' else '7').toLong)
      else
        None
    }
  }

  var a = 0
  while (next(a).getOrElse(0l) < line) {
    a += 1
  }
  println(next(a).get)
}


Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9).

The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n).

Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9).

NoteSample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points.Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4.Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number.

import scala.collection._

object A extends App {

  val MOD = 1000000009

  def readString = Console.readLine
  def readBigs = readString.split(" ").map(s => BigInt(s))

  val Array(n, m, k) = readBigs

  val plain = ((n - m) * (k - 1) + m.min(n % k)).min(m)
  val doubling = m - plain
  val groups = doubling / k
  val doubled = k * (BigInt(2).modPow(groups + 1, MOD) - 2 + MOD)

  val result = (plain + doubled) % MOD

  println(result)
}


Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is p (the number p is even).Print the total money grandma should have at the end of the day to check if some buyers cheated her.

The first line contains two integers n and p (1 ≤ n ≤ 40, 2 ≤ p ≤ 1000) — the number of the buyers and the cost of one apple. It is guaranteed that the number p is even. The next n lines contains the description of buyers. Each buyer is described with the string half if he simply bought half of the apples and with the string halfplus if grandma also gave him a half of an apple as a gift. It is guaranteed that grandma has at least one apple at the start of the day and she has no apples at the end of the day.

Print the only integer a — the total money grandma should have at the end of the day. Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

NoteIn the first sample at the start of the day the grandma had two apples. First she sold one apple and then she sold a half of the second apple and gave a half of the second apple as a present to the second buyer.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, p) = in.next().split(' ').map(_.toInt)
  println((1 to n).map(_ => in.next()).reverse.tail.foldLeft((1l, p.toLong / 2)) {
    case ((mayBuy, money), "halfplus") => (mayBuy * 2 + 1, money + p * mayBuy + p / 2)
    case ((mayBuy, money), _) => (mayBuy * 2, money + p * mayBuy)
  }._2)
}

/**
 * Created by aborisenko on 21.02.16.
 */

import io.StdIn._

object Main extends App {
  def a632 (){

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

    var result: Long = 0
    var nn: Long = 0

    val a: Array[Int] = Array.fill[Int](n)(0)
    for( i <- 0 to n-1)
      if( readLine() == "half" )
        a(i) = 1

    for( i <- 1 to n) {
      if (a(n-i) == 1) {
        result += nn * p
        nn *= 2
      } else {
        result += nn * p + p / 2
        nn = nn * 2 + 1
      }
    }

    println(result)
  }

  a632()
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, p) = in.next().split(' ').map(_.toInt)
  println((1 to n).map(_ => in.next()).reverse.tail.foldLeft((1, p / 2)) {
    case ((mayBuy, money), "halfplus") => (mayBuy * 2 + 1, money + p * mayBuy + p / 2)
    case ((mayBuy, money), _) => (mayBuy * 2, money + p * mayBuy)
  }._2)
}

/**
 * Created by aborisenko on 21.02.16.
 */

import io.StdIn._

object Main extends App {
  def a632 (){

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

    var result: Long = 0
    var nn: Long = 0

    val a: Array[Int] = Array.fill[Int](n)(0)
    for( i <- 0 to n-1)
      if( readLine() == "half" )
        a(i) = 1

    for( i <- 0 to n-1) {
      if (a(i) == 1) {
        result += nn * p
        nn *= 2
      } else {
        result += nn * p + p / 2
        nn = nn * 2 + 1
      }
    }

    println(result)
  }

  a632()
}


Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form one or multiple bonds with any other atom, but it cannot form a bond with itself. The number of bonds of an atom in the molecule must be equal to its valence number.  Mike knows valence numbers of the three atoms. Find a molecule that can be built from these atoms according to the stated rules, or determine that it is impossible.

The single line of the input contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 106) — the valence numbers of the given atoms.

If such a molecule can be built, print three space-separated integers — the number of bonds between the 1-st and the 2-nd, the 2-nd and the 3-rd, the 3-rd and the 1-st atoms, correspondingly. If there are multiple solutions, output any of them. If there is no solution, print "Impossible" (without the quotes).

NoteThe first sample corresponds to the first figure. There are no bonds between atoms 1 and 2 in this case.The second sample corresponds to the second figure. There is one or more bonds between each pair of atoms.The third sample corresponds to the third figure. There is no solution, because an atom cannot form bonds with itself.The configuration in the fourth figure is impossible as each atom must have at least one atomic bond.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(a, b, c) = in.next().split(' ').map(_.toInt)
  val r = (0 to a).find{ i =>
    val ab = i
    val ac = a - i
    b - ab >= 0 && (b - ab) == (c - ac)
  }
  println(r.map{
    i => s"$i ${b - i} ${a - i}"
  }.getOrElse("Impossible"))
}

object B344 {
  @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(a, b, c) = readInts(3)
    var i = 0
    var break = false
    while(!break && i <= a) {
      if(c-(a-i) >= 0 && c-a+2*i == b) {
        println(s"$i ${c-a+i} ${a-i}")
        break = true
      }
      i += 1
    }

    if(!break) {
      println("Impossible")
    }
  }
}

import scala.collection._

object B extends App {

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

  val as = readInts(3)
  val sort = as.zipWithIndex.sortBy(_._1)

  val d = math.abs(sort(1)._1 - sort(2)._1)

  def idx(a: Int, b: Int) = (a, b) match {
      case (0, 1) | (1, 0) => 0
      case (1, 2) | (2, 1) => 1
      case (0, 2) | (2, 0) => 2
    }

  if ((sort(0)._1 - d) % 2 == 1 || sort(0)._1 < d) {
    println("Impossible")
  } else {
    val dd = (sort(0)._1 - d) / 2
    val bs = Array(dd, dd + d, sort(1)._1 - dd)
    val cs = Array.ofDim[Int](3)

    cs(idx(sort(0)._2, sort(1)._2)) = bs(0)
    cs(idx(sort(1)._2, sort(2)._2)) = bs(2)
    cs(idx(sort(0)._2, sort(2)._2)) = bs(1)

    println(cs.mkString(" "))
  }

}

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.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): String = {
    val A, B, C = sc.nextInt

    val xyz2 = List(A + B - C, - A + B + C, A - B + C)

    if (xyz2.forall { x => x >= 0 && x % 2 == 0 } ) {
      xyz2.map(_ / 2).mkString(" ")
    }
    else {
      "Impossible"
    }
  }

  out.println(solve)
  out.close
}

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

    s(0) = (a(0) + a(1) - a(2)) / 2
    s(1) = (a(1) + a(2) - a(0)) / 2
    s(2) = (a(2) + a(0) - a(1)) / 2

    if (s.min < 0 || a.sum % 2 != 0) println("Impossible")
    else println(s.mkString(" "))
  }
}

object B344 {
  @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(a, b, c) = readInts(3)
    var i = 0
    var break = true
    while(break && i <= a) {
      if(c-(a-i) > 0 && c-a+2*i > 0 && c-a+2*i == b) {
        println(s"$i ${c-(a-i)} ${a-i}")
        break = false
      }
      i += 1
    }

    if(break) {
      println("Impossible")
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val a = readLine().split(" ").map(_.toInt)
    val s = a.map(_ => 0)
    s(0) = (a(0) + a(1) - a(2)) / 2
    s(1) = (a(1) + a(2) - a(0)) / 2
    s(2) = (a(2) + a(0) - a(1)) / 2

    if (s.min < 0) println("Impossible")
    else println(s.mkString(" "))
  }
}


Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.  The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: house i and house i + 1 (1 ≤ i < n) are exactly 10 meters away. In this village, some houses are occupied, and some are not. Indeed, unoccupied houses can be purchased.You will be given n integers a1, a2, ..., an that denote the availability and the prices of the houses. If house i is occupied, and therefore cannot be bought, then ai equals 0. Otherwise, house i can be bought, and ai represents the money required to buy it, in dollars.As Zane has only k dollars to spare, it becomes a challenge for him to choose the house to purchase, so that he could live as near as possible to his crush. Help Zane determine the minimum distance from his crush's house to some house he can afford, to help him succeed in his love.

The first line contains three integers n, m, and k (2 ≤ n ≤ 100, 1 ≤ m ≤ n, 1 ≤ k ≤ 100) — the number of houses in the village, the house where the girl lives, and the amount of money Zane has (in dollars), respectively. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 100) — denoting the availability and the prices of the houses. It is guaranteed that am = 0 and that it is possible to purchase some house with no more than k dollars.

Print one integer — the minimum distance, in meters, from the house where the girl Zane likes lives to the house Zane can buy.

NoteIn the first sample, with k = 20 dollars, Zane can buy only house 5. The distance from house m = 1 to house 5 is 10 + 10 + 10 + 10 = 40 meters.In the second sample, Zane can buy houses 6 and 7. It is better to buy house 6 than house 7, since house m = 3 and house 6 are only 30 meters away, while house m = 3 and house 7 are 40 meters away.

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

object a12 {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().take(2).map(_.split(' ').map(_.toInt)).toArray
    val Array(n,kk,l) = lines(0)
    val k = kk-1
    val (bb,cc) = lines(1).zipWithIndex.splitAt(k)
    val (b,c) = (bb.filter(_._1!=0).reverse.dropWhile(_._1 > l).headOption,
                 cc.tail.filter( _._1!=0).dropWhile(_._1 > l).headOption)
    println(
      (b,c) match {
        case (Some(a), Some(b)) => min(k-a._2, b._2-k)*10
        case (Some(d),None) => (k - d._2)*10
        case (None, Some(d)) => (d._2 - k)*10
        case (None,None) => -1
       }
    )
  }
}

//package com.obarros.hackerrank.codechallenges.daysofcode.codeforces.Round_408

object ProblemA {
  def main(args: Array[String]): Unit = {
    val input = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val n = input(0)
    val m = input(1)
    val k = input(2)
    val houses = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    System.out.println(solution(n, m, k, houses))
  }

  def solution(n: Int, m: Int, k: Int, houses: Array[Int]): Int = {

    var result = Int.MaxValue
    for (i <- houses.indices) {
      if (houses(i) != 0 && houses(i) <= k)
        result = math.min(result, 10*math.abs(m -1 - i))
    }
    result
  }
}

/**
  * Created by ruslan on 3/29/17.
  */
object ProblemA extends App {
    import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}
import java.util.StringTokenizer

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

    def nextToken(): String = {
      while (st == null || !st.hasMoreTokens()) {
        st = new StringTokenizer(in.readLine);
      }
      return st.nextToken();
    }

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val n = in.nextInt()
  val m = in.nextInt()

  val k = in.nextInt()

  var res = n + 1

  for (i <- 1 to n) {
    val emount = in.nextInt()
    if (emount != 0 && emount <= k && Math.abs(i - m) < res) {
      res = Math.abs(i - m)
    }
  }

  println(res * 10)

}

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

object a12 {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().take(2).map(_.split(' ').map(_.toInt)).toArray
    val Array(n,k,l) = lines(0)
    val (bb,cc) = lines(1).zipWithIndex.splitAt(k-1)
    val (b,c) = (bb.filter(_._1!=0).reverse.dropWhile(_._1 > l).headOption,
                 cc.tail.filter( _._1!=0).dropWhile(_._1 > l).headOption)
    println(
      (b,c) match {
        case (Some(a), Some(b)) => min(k-a._2, b._2-k)*10
        case (Some(d),None) => (k-1 - d._2)*10
        case (None, Some(d)) => (d._2 - k+1)*10
        case (None,None) => -1
       }
    )
  }
}

//package com.obarros.hackerrank.codechallenges.daysofcode.codeforces.Round_408

object ProblemA {
  def main(args: Array[String]): Unit = {
    val input = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val m = input(0)
    val n = input(1)
    val k = input(2)
    val houses = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var cond: Array[Int] = Array[Int]()
    var res: Array[Int] = Array[Int]()

    for (i <- houses.indices) {
      if (houses(i) <= k && i != n && i != 0)
        cond :+= 1
      else
        cond :+= 0
    }

    for (j <- houses.indices) {
      res :+= cond(j) * (j + 1) * 10
    }

    val reset = n * 10
    val result = {
      res.filter(x => x != 0).map(x => math.abs(x - reset)).min
    }

    System.out.println(result)
  }

}

//package com.obarros.hackerrank.codechallenges.daysofcode.codeforces.Round_408

object ProblemA {
  def main(args: Array[String]): Unit = {
    val input = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val m = input(0)
    val n = input(1)
    val k = input(2)
    val houses = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var cond: Array[Int] = Array[Int]()
    var res: Array[Int] = Array[Int]()

    for (i <- houses.indices) {
      if (houses(i) <= k && i != n && i != 0)
        cond :+= 1
      else
        cond :+= 0
    }

    for (j <- houses.indices) {
      res :+= cond(j) * (j + 1) * 10
    }

    val reset = n * 10
    val result = {
      res.map(x => x - reset).filter(x => x != 0).map(x => math.abs(x)).min
    }

    System.out.println(result)
  }

}

//package com.obarros.hackerrank.codechallenges.daysofcode.codeforces.Round_408

object ProblemA {
  def main(args: Array[String]): Unit = {
    val input = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val m = input(0)
    val n = input(1)
    val k = input(2)
    val houses = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var cond: Array[Int] = Array[Int]()
    var res: Array[Int] = Array[Int]()

    for (i <- houses.indices) {
      if (houses(i) <= k && i != n && houses(i) != 0)
        cond :+= 1
      else
        cond :+= 0
    }

    for (j <- houses.indices) {
      res :+= cond(j) * (j + 1) * 10
    }

//    System.out.println("cond: ")
//    cond.foreach(x => print(x + " "))
//    System.out.println()
//    System.out.println("res: ")
//    res.foreach(x => print(x + " "))
//    System.out.println()

    val reset = n * 10
    val result = {
      res.filter(x => x != 0 ).map(x => math.abs(x - reset)).filter(x => x != 0 ).min
    }

    System.out.println(result)
  }

}

//package Round_408

/**
  * Created by OMVB on 10/04/2017.
  */
object Problem_A {
  def main(args: Array[String]): Unit = {
    val input = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val m = input(0)
    val n = input(1)
    val k = input(2)
    val houses = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var cond: Array[Int] = Array[Int]()
    var res: Array[Int] = Array[Int]()

    for (i <- houses.indices) {
      if (houses(i) <= k && i != n && i != 0)
        cond :+= 1
      else
        cond :+= 0
    }

    for (j <- houses.indices) {
      res :+= cond(j) * (j + 1) * 10
    }

    val reset = n * 10
    val result = {
      res.map(x => x - reset).filter(x => x > 0 && x != 0 && x != m).min
    }

    System.out.println(result)
  }

}


One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to produce  (remainder after dividing x by m) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory. The board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by m). Given the number of details a on the first day and number m check if the production stops at some moment.

The first line contains two integers a and m (1 ≤ a, m ≤ 105).

Print "Yes" (without quotes) if the production will eventually stop, otherwise print "No".

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var Array(a, m) = in.next().split(" ").map(_.toInt)
  var visited = Set.empty[Int]
  while (!visited(a) && a != 0) {
    visited += a
    a = 2 * a % m
  }
  if (a == 0)
    println("Yes")
  else
    println("No")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var Array(a, m) = in.next().split(" ").map(_.toInt)
  var visited = Set.empty[Int]
  while (!visited(a) && a != 0) {
    visited += a
    a = 2 * a % m
  }
  if (a == 0)
    println("YES")
  else
    println("NO")
}


Polycarp plays "Game 23". Initially he has a number $$$n$$$ and his goal is to transform it to $$$m$$$. In one move, he can multiply $$$n$$$ by $$$2$$$ or multiply $$$n$$$ by $$$3$$$. He can perform any number of moves.Print the number of moves needed to transform $$$n$$$ to $$$m$$$. Print -1 if it is impossible to do so.It is easy to prove that any way to transform $$$n$$$ to $$$m$$$ contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).

The only line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le m \le 5\cdot10^8$$$).

Print the number of moves to transform $$$n$$$ to $$$m$$$, or -1 if there is no solution.

NoteIn the first example, the possible sequence of moves is: $$$120 \rightarrow 240 \rightarrow 720 \rightarrow 1440 \rightarrow 4320 \rightarrow 12960 \rightarrow 25920 \rightarrow 51840.$$$ The are $$$7$$$ steps in total.In the second example, no moves are needed. Thus, the answer is $$$0$$$.In the third example, it is impossible to transform $$$48$$$ to $$$72$$$.

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    REP(30) { two =>
      REP(18) { three =>
        val a = math.round(math.pow(2, two))
        val b = math.round(math.pow(3, three))
        debug(s"$a $b")
        if (M % a == 0 && M % b == 0 && M / a / b == N) {
          out.println(s"${two + three}")
          return
        }
      }
    }

    out.println(-1)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

import java.util.Scanner

object Main {

  def main(args: Array[String]): Unit = {
    val sc  = new Scanner(System.in)
    val n = sc.nextInt()
    val m = sc.nextInt()
    if(n == m)
      println(0)

    else if(n % 2 == 0 && m % 2 == 1)
      println(-1)

    else if(m % n == 0){
      var division = m / n
      var res = 0;
      while(division % 3 == 0){
        division = division / 3
        res += 1
      }
      while (division % 2 == 0){
        division = division / 2
        res += 1
      }
      if(division == 1)
        println(res)
      else
        println(-1)
    }
    else
      println(-1)
  }
}

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

  override def apply(io: IO): io.type = {
    val n, m = io.read[Int]
    val ans = if (m%n == 0) {
      var r = m/n
      var c = 0
      while(r%3 == 0) {
        r /= 3
        c += 1
      }
      while(r%2 == 0) {
        r /= 2
        c += 1
      }
      if (r == 1) Some(c) else None
    } else {
      None
    }

    io.write(ans.getOrElse(-1))
  }
}
/****************************[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 Competitive extends App {
  val Array(x,y) = readLine.split(" ").map(_.toInt)
  if(x==y) println(0)
  else if(y%x!=0) println(-1)
  else {
    var z = y / x
    var count = 0
    var stat = 1
    while(z>1) {
      if(z%2!=0 && z%3!=0) {
        stat = 0
        z = 1
      }
      else {
        if(z%2==0) z/=2
        else if(z%3==0) z/=3
        count+=1
      }
    }
    if(stat==0) println(-1)
    else println(count)
  }

}

import scala.annotation.tailrec

object Main extends App {

  val inputs = io.StdIn.readLine().split(" ").map(x => x.toInt)

  def solve(i: Int, i1: Int): Int = {
    @tailrec
    def solve(a: Int, acc: Int = 0): Int = {
      if (a == 1) acc
      else if (a == -1) -1
      else solve(if (a % 3 == 0) a / 3 else if (a % 2 == 0) a / 2 else -1, acc + 1)

    }

    if (i1 % i != 0) -1
    else solve(i1 / i)
  }

  println(solve(inputs(0), inputs(1)))

}

object Main extends App {

  val inputs = io.StdIn.readLine().split(" ").map(x => x.toInt)

  def solve(i: Int, i1: Int): Int = {
    def solve(a: Int, acc: Int = 0): Int = {
      if (a == 1) acc
      else if (a == -1) -1
      else solve(if (a % 3 == 0) a / 3 else if (a % 2 == 0) a / 2 else -1, acc + 1)

    }

    if (i1 % i != 0) -1
    else solve(i1 / i)
  }

  println(solve(inputs(0), inputs(1)))

}

object Main extends App {

  val inputs = io.StdIn.readLine().split(" ").map(x => x.toInt)

  def solve(i: Int, i1: Int) : Int = {
    def solve(a: Int, acc: Int = 0): Int = {
      if (a == 1) acc
      else solve(if (a % 3 == 0) a / 3 else a / 2, acc + 1)

    }
    if (i1 % i != 0) -1
    else solve(i1 / i)
  }

  println(solve(inputs(0),inputs(1)))

}

object Main extends App {

  val inputs = io.StdIn.readLine().split(" ").map(x => x.toInt)

  def solve(i: Int, i1: Int): Int = {
    def solve(a: Int, acc: Int = 0): Int = {
      if (a == 1) acc
      else solve(if (a % 3 == 0) a / 3 else a / 2, acc + 1)

    }

    if (i1 % i != 0) -1
    else if (i == i1) 0
    else if (i1 % 2 != 0 && i1 % 3 != 0) -1
    else solve(i1 / i)
  }

  println(solve(inputs(0), inputs(1)))

}


Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:  on Mondays, Thursdays and Sundays he eats fish food;  on Tuesdays and Saturdays he eats rabbit stew;  on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains:  $$$a$$$ daily rations of fish food;  $$$b$$$ daily rations of rabbit stew;  $$$c$$$ daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.

The first line of the input contains three positive integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 7\cdot10^8$$$) — the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly.

NoteIn the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday — rabbit stew and during Wednesday — chicken stake. So, after four days of the trip all food will be eaten.In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack.In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be $$$99$$$ portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.

import scala.annotation.tailrec
import scala.io.StdIn._

object GourmetCat {

  @tailrec
  def gormetCat(m: Map[Int, Int], mToWeekD: Map[Int, Int], index: Int = 0, result: Int = 0): Int = {
    val i = mToWeekD.getOrElse(index % 7, 0)
    if(m.getOrElse(i, 0) == 0) {
      result
    } else {
      gormetCat(m.updated(i, m.getOrElse(i, 0) - 1), mToWeekD, index+1, result+1)
    }
  }

  @tailrec
  def reduceCatFood(fishFood: Int, rabbitStew: Int, chickenStake: Int, result: Int = 0): (Int, Int, Int, Int) = {
    if(fishFood > 3 && rabbitStew > 3  && chickenStake > 3) {
      reduceCatFood(fishFood - 3, rabbitStew - 2, chickenStake - 2, result + 7)
    } else (fishFood, rabbitStew, chickenStake, result)
  }

  def main(args: Array[String]): Unit = {
    val Array(fishFood, rabbitStew, chickenStake) = readLine.split(" ").map(_.toInt)

    val (reducedFishFood, reducedRabbitStew, reducedChickenStake, prelimResult) =
      reduceCatFood(fishFood, rabbitStew, chickenStake)
    val m = Map[Int, Int]().updated(0, reducedFishFood).
      updated(1, reducedRabbitStew).updated(2, reducedChickenStake)
    val mToWeekD = Map[Int, Int]((0, 0), (1, 1), (2, 2),
      (3, 0), (4,2), (5,1),(6,0))

    println((0 to 6).map(gormetCat(m, mToWeekD, _, prelimResult)).max)
  }
}


Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate.  Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number x is the notation of form AeB, where A is a real number and B is an integer and x = A × 10B is true. In our case A is between 0 and 9 and B is non-negative.Barney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding.

The first and only line of input contains a single string of form a.deb where a, d and b are integers and e is usual character 'e' (0 ≤ a ≤ 9, 0 ≤ d < 10100, 0 ≤ b ≤ 100) — the scientific notation of the desired distance value. a and b contain no leading zeros and d contains no trailing zeros (but may be equal to 0). Also, b can not be non-zero if a is zero.

Print the only real number x (the desired distance value) in the only line in its decimal notation.  Thus if x is an integer, print it's integer value without decimal part and decimal point and without leading zeroes.  Otherwise print x in a form of p.q such that p is an integer that have no leading zeroes (but may be equal to zero), and q is an integer that have no trailing zeroes (and may not be equal to zero).

object Solution {
    def main(args : Array[String]) {
        val line = readLine()
        val r = "^(.*)\\.(.*)e(.*)$"r;
        val r(a, d, e) = line
        var n = a + d
        val i = e.toInt
        if (n.size < 1 + i) n = n + ("0" * (i + 1 - n.size))
        n = n.substring(0, i + 1) +  "." + n.substring(i + 1);
        println(post(n));
    }
    def post(s:String) :String = {
        if (s.startsWith("0") && !s.startsWith("0."))
            post(s.substring(1))
        else if (s.matches(".*\\.0*")) s.substring(0,s.indexOf('.'))
        else s
    }
}

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

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

        var b:Int = 0;
        var ex_e = false

        for (i <- 0 until line.length()) {
            if (ex_e == true) {
                b = b * 10 + line(i) - '0'
            }
            if (line(i) == 'e') ex_e = true
        }

        // println(b)
        var ex_point = false
        var buf = new StringBuilder()

        var loop = new Breaks
        loop.breakable {
            for (i <- 0 until line.length()) {
                if (line(i) == 'e') {
                    if (b > 0) {
                        while (b > 0) {
                            buf += '0'
                            b = b - 1
                        }
                        buf += '.'
                    }
                    loop.break
                }

                if (ex_point == true) {
                    if (b == 0) {
                        buf += '.'
                    }
                    buf += line(i)
                    b = b - 1
                } else {
                    if (line(i) == '.') {
                        ex_point = true
                    } else {
                        buf += line(i)
                    }
                }
            }
        }

        var pos: Int = 0
        // println(buf)
        loop.breakable {
            for (i <- 0 until buf.length()) {
                var j = buf.length() - i - 1;
                if (buf(j) == '.') {
                    pos = j
                    loop.break
                }
                if (buf(j) != '0') {
                    pos = j + 1
                    loop.break
                }
            }
        }
        // println("pos " + pos)
        var flag = false

        for (i <- 0 until pos) {
            if (flag == true) {
                if (buf(i) == '.' && i == buf.length()-1) {
                } else {
                    print(buf(i))
                }
            } else {
                if (buf(i) != '0') {
                    print(buf(i))
                    flag = true
                } else if (buf(i + 1) == '.' ) {
                    print(buf(i));
                    flag = true
                }
            }
        }
        println()
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val (ne, ee) = ns.split('.') match {
    case Array(before, after) =>
      val afterDrop = after.reverse.dropWhile(_ == '0').reverse
      (before + afterDrop, -afterDrop.length)
    case Array(before) => (before, 0)
  }
  val e = ee + es.toInt

  if (e == 0)
    println(ne)
  else if (e < 0)
    println(ne.take(ne.length + e) + '.' + ne.drop(ne.length + e))
  else
    println(ne + "0" * e)
}

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

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

        var b:Int = 0;
        var ex_e = false

        for (i <- 0 until line.length()) {
            if (ex_e == true) {
                b = b * 10 + line(i) - '0'
            }
            if (line(i) == 'e') ex_e = true
        }

        // println(b)
        var ex_point = false
        var buf = new StringBuilder()

        var loop = new Breaks
        loop.breakable {
            for (i <- 0 until line.length()) {
                if (line(i) == 'e') {
                    while (b > 0) {
                        buf += '0'
                        b = b - 1
                    }
                    buf += '.'
                    loop.break
                }

                if (ex_point == true) {
                    if (b == 0) {
                        buf += '.'
                    }
                    buf += line(i)
                    b = b - 1
                } else {
                    if (line(i) == '.') {
                        ex_point = true
                    } else {
                        buf += line(i)
                    }
                }
            }
        }

        var pos: Int = 0
        // println(buf)
        loop.breakable {
            for (i <- 0 until buf.length()) {
                var j = buf.length() - i - 1;
                if (buf(j) == '.') {
                    pos = j
                    loop.break
                }
                if (buf(j) != '0') {
                    pos = j + 1
                    loop.break
                }
            }
        }
        // println("pos " + pos)
        var flag = false

        for (i <- 0 until pos) {
            if (flag == true) {
                if (buf(i) == '.' && i == buf.length()-1) {
                } else {
                    print(buf(i))
                }
            } else {
                if (buf(i) != '0') {
                    print(buf(i))
                    flag = true
                } else if (buf(i + 1) == '.' ) {
                    print(buf(i));
                    flag = true
                }
            }
        }
        println()
    }
}

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

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

        var b:Int = 0;
        var ex_e = false

        for (i <- 0 until line.length()) {
            if (ex_e == true) {
                b = b * 10 + line(i) - '0'
            }
            if (line(i) == 'e') ex_e = true
        }

        // println(b)
        var ex_point = false
        var buf = new StringBuilder()

        var loop = new Breaks
        loop.breakable {
            for (i <- 0 until line.length()) {
                if (line(i) == 'e') {
                    while (b > 0) {
                        buf += '0'
                        b = b - 1
                    }
                    loop.break
                }

                if (ex_point == true) {
                    if (b == 0) {
                        buf += '.'
                    }
                    buf += line(i)
                    b = b - 1
                } else {
                    if (line(i) == '.') {
                        ex_point = true
                    } else {
                        buf += line(i)
                    }
                }
            }
        }

        var pos: Int = 0
        // println(buf)
        loop.breakable {
            for (i <- 0 until buf.length()) {
                var j = buf.length() - i - 1;
                if (buf(j) != '0') {
                    pos = j
                    loop.break;
                }
            }
        }
        // println("pos " + pos)
        var flag = false

        for (i <- 0 until pos) {
            if (flag == true) {
                if (buf(i) == '.' && i == buf.length()-1) {
                } else {
                    print(buf(i))
                }
            } else {
                if (buf(i) != '0') {
                    print(buf(i))
                    flag = true
                } else if (buf(i + 1) == '.' ) {
                    print(buf(i));
                    flag = true
                }
            }
        }
        println()
/*
        val loop = new Breaks;
        loop.breakable {
            for (i <- 0 until buf.length()) {
                if (buf(i) == 'e') loop.break
                print(buf(i))
            }
            println()
        }
*/

    }
}

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

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

        var b:Int = 0;
        var ex_e = false

        for (i <- 0 until line.length()) {
            if (ex_e == true) {
                b = b * 10 + line(i) - '0'
            }
            if (line(i) == 'e') ex_e = true
        }

        // println(b)
        var ex_point = false
        var buf = new StringBuilder()

        var loop = new Breaks
        loop.breakable {
            for (i <- 0 until line.length()) {
                if (line(i) == 'e') {
                    while (b > 0) {
                        buf += '0'
                        b = b - 1
                    }
                    loop.break
                }

                if (ex_point == true) {
                    if (b == 0) {
                        buf += '.'
                    }
                    buf += line(i)
                    b = b - 1
                } else {
                    if (line(i) == '.') {
                        ex_point = true
                    } else {
                        buf += line(i)
                    }
                }
            }
        }

        // println(buf)

        var flag = false

        for (i <- 0 until buf.length()) {
            if (flag == true) {
                if (buf(i) == '.' && i == buf.length()-1) {
                } else {
                    print(buf(i))
                }
            } else {
                if (buf(i) != '0') {
                    print(buf(i))
                    flag = true
                } else if (buf(i + 1) == '.' ) {
                    print(buf(i));
                    flag = true
                }
            }
        }
        println()
/*
        val loop = new Breaks;
        loop.breakable {
            for (i <- 0 until buf.length()) {
                if (buf(i) == 'e') loop.break
                print(buf(i))
            }
            println()
        }
*/

    }
}

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

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

        var b:Int = 0;
        var ex_e = false

        for (i <- 0 until line.length()) {
            if (ex_e == true) {
                b = b * 10 + line(i) - '0'
            }
            if (line(i) == 'e') ex_e = true
        }

        // println(b)
        var ex_point = false
        var buf = new StringBuilder()

        var loop = new Breaks
        loop.breakable {
            for (i <- 0 until line.length()) {
                if (line(i) == 'e') {
                    while (b > 0) {
                        buf += '0'
                        b = b - 1
                    }
                    loop.break
                }

                if (ex_point == true) {
                    if (b == 0) {
                        buf += '.'
                    }
                    buf += line(i)
                    b = b - 1
                } else {
                    if (line(i) == '.') {
                        ex_point = true
                    } else {
                        buf += line(i)
                    }
                }
            }
        }

        var pos: Int = 0
        // println(buf)
        loop.breakable {
            for (i <- 0 until buf.length()) {
                var j = buf.length() - i - 1;
                if (buf(j) == '.') {
                    pos = j
                    loop.break
                }
                if (buf(j) != '0') {
                    pos = j + 1
                    loop.break
                }
            }
        }
        // println("pos " + pos)
        var flag = false

        for (i <- 0 until pos) {
            if (flag == true) {
                if (buf(i) == '.' && i == buf.length()-1) {
                } else {
                    print(buf(i))
                }
            } else {
                if (buf(i) != '0') {
                    print(buf(i))
                    flag = true
                } else if (buf(i + 1) == '.' ) {
                    print(buf(i));
                    flag = true
                }
            }
        }
        println()
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val n = ns.toDouble
  val e = es.toInt
  val ans = n * Math.pow(10, e)
  if (ans == ans.toInt)
    println(ans.toInt)
  else
    println(ans)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val n = ns.toDouble
  val e = es.toInt
  println(n * Math.pow(10, e))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val n = ns.filter(_ != '.')
  val eee = ns.indexOf('.')
  val ee = if (eee == -1) 0 else eee
  val e = es.toInt + ee + n.reverse.takeWhile(_ == '0').length
  val ne = n.reverse.dropWhile(_ == '0').reverse

  if (e == ne.length)
    println(ne)
  else if (e < ne.length)
    println(ne.take(e) + '.' + n.drop(e))
  else
    println(ne + "0" * (e - ne.length))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val (ne, ee) = ns.split('.') match {
    case Array(before, after) =>
      val afterDrop = after.reverse.dropWhile(_ == 0).reverse
      (before + afterDrop, -afterDrop.length)
    case Array(before) => (before, 0)
  }
  val e = ee + es.toInt

  if (e == 0)
    println(ne)
  else if (e < ne.length)
    println(ne.take(ne.length + e) + '.' + ne.drop(ne.length + e))
  else
    println(ne + "0" * (e - ne.length))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val (ne, ee) = ns.split('.') match {
    case Array(before, after) =>
      val afterDrop = after.reverse.dropWhile(_ == 0).reverse
      (before + afterDrop, -afterDrop.length)
    case Array(before) => (before, 0)
  }
  val e = ee + es.toInt

  println(e)

  if (e == 0)
    println(ne)
  else if (e < 0)
    println(ne.take(ne.length + e) + '.' + ne.drop(ne.length + e))
  else
    println(ne + "0" * e)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val (ne, ee) = ns.split('.') match {
    case Array(before, after) =>
      val afterDrop = after.reverse.dropWhile(_ == 0).reverse
      (before + afterDrop, -afterDrop.length)
    case Array(before) => (before, 0)
  }
  val e = ee + es.toInt
  if (e == ne.length)
    println(ne)
  else if (e < ne.length)
    println(ne.take(ne.length + e) + '.' + ne.drop(ne.length + e))
  else
    println(ne + "0" * (e - ne.length))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val (ne, ee) = ns.split('.') match {
    case Array(before, after) =>
      val afterDrop = after.reverse.dropWhile(_ == 0).reverse
      (before + afterDrop, -afterDrop.length)
    case Array(before) => (before, 0)
  }
  val e = ee + es.toInt

  println(e)

  if (e == ne.length)
    println(ne)
  else if (e < ne.length)
    println(ne.take(ne.length + e) + '.' + ne.drop(ne.length + e))
  else
    println(ne + "0" * (e - ne.length))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val n = ns.filter(_ != '.')
  val eee = ns.indexOf('.')
  val ee = if (eee == -1) 0 else eee
  val e = es.toInt + ee
  println(n.take(e) + '.' + n.drop(e))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val n = ns.filter(_ != '.')
  val eee = ns.indexOf('.')
  val ee = if (eee == -1) 0 else eee
  val e = es.toInt - ee + n.reverse.takeWhile(_ == '0').length
  val ne = n.reverse.dropWhile(_ == '0').reverse

  if (e == ne.length)
    println(ne)
  else if (e < ne.length)
    println(ne.take(e) + '.' + n.drop(e))
  else
    println(ne + "0" * (e - ne.length))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val (ne, ee) = ns.split('.') match {
    case Array(before, after) =>
      val afterDrop = after.reverse.dropWhile(_ == 0).reverse
      (before + afterDrop, -afterDrop.length)
    case Array(before) => (before, 0)
  }
  val e = ee + es.toInt

  if (e == 0)
    println(ne)
  else if (e < 0)
    println(ne.take(ne.length + e) + '.' + ne.drop(ne.length + e))
  else
    println(ne + "0" * e)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val (ne, ee) = ns.split('.') match {
    case Array(before, after) =>
      val afterDrop = after.reverse.dropWhile(_ == 0).reverse
      (before + afterDrop, -afterDrop.length)
    case Array(before) => (before, 0)
  }
  val e = ee + es.toInt

  println(e)

  if (e == 0)
    println(ne)
  else if (e < ne.length)
    println(ne.take(ne.length + e) + '.' + ne.drop(ne.length + e))
  else
    println(ne + "0" * (e - ne.length))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val Array(ns, es) = line.split('e')
  val n = ns.filter(_ != '.')
  val eee = ns.indexOf('.')
  val ee = if (eee == -1) 0 else eee
  val e = es.toInt + ee + n.reverse.takeWhile(_ == '0').length
  val ne = n.reverse.dropWhile(_ == '0').reverse

  if (e == ne.length)
    println(ne)
  else if (e < ne.length)
    println(ne.take(e) + '.' + n.drop(e))
  else
    println(ne + "0" * (e - ne.length + 1))
}


Little Petya was given this problem for homework:You are given function  (here  represents the operation of taking the remainder). His task is to count the number of integers x in range [a;b] with property f(x) = x.It is a pity that Petya forgot the order in which the remainders should be taken and wrote down only 4 numbers. Each of 24 possible orders of taking the remainder has equal probability of being chosen. For example, if Petya has numbers 1, 2, 3, 4 then he can take remainders in that order or first take remainder modulo 4, then modulo 2, 3, 1. There also are 22 other permutations of these numbers that represent orders in which remainder can be taken. In this problem 4 numbers wrote down by Petya will be pairwise distinct.Now it is impossible for Petya to complete the task given by teacher but just for fun he decided to find the number of integers  with property that probability that f(x) = x is not less than 31.4159265352718281828459045%. In other words, Petya will pick up the number x if there exist at least 7 permutations of numbers p1, p2, p3, p4, for which f(x) = x.

First line of the input will contain 6 integers, separated by spaces: p1, p2, p3, p4, a, b (1 ≤ p1, p2, p3, p4 ≤ 1000, 0 ≤ a ≤ b ≤ 31415).  It is guaranteed that numbers p1, p2, p3, p4 will be pairwise distinct.

Output the number of integers in the given range that have the given property.

object Main {
  def main(args: Array[String]) {
    val Array(p1, p2, p3, p4, a, b) = readLine().split(" ").map(_.toInt)
    val p = Array(p1, p2, p3, p4).min
    println((p - a).min(b - a + 1).max(0))
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(p1, p2, p3, p4, a, b) = readLine().split(" ").map(_.toInt)
    val p = Array(p1, p2, p3, p4).min
    println((p - a).max(0))
  }
}