You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.

The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task. It is guaranteed that n is divisible by k.

In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.

NoteExplanation of the first example.If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12. Explanation of the second example.In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println((0 until k).foldLeft((Int.MaxValue, 0)) {
    case ((acc, index), i) =>
      val value = (i until n by k).foldLeft(0) {
        case(acc, el) => acc + data(el)
      }
      if (value < acc)
        (value, i)
      else
        (acc, index)
  }._2 + 1)
}

object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n)
  val bs = Array.fill(k)(0)

  for (i <- as.indices) bs(i % k) += as(i)

  val best = bs.min
  val ans = bs.indexOf(best) + 1

  println(ans)
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val r = a.grouped(k).toArray.transpose
    val sums = r.map(_.sum)
    println(sums.zipWithIndex.minBy(_._1)._2 + 1)
  }
}

import java.util.Scanner

object DimaAndTodolist extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    val k = scan.nextInt

    val s = {
        for(i <- 0 until n) yield (i % k, scan.nextInt)
        }.toArray.groupBy(_._1)

    val ans = s.map(kv =>
        (kv._1, kv._2.map(_._2).reduce(_ + _))).minBy(x => (x._2, x._1))._1 + 1

    println(ans)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println((0 until k).foldLeft((Int.MaxValue, -1)) {
    case ((acc, index), i) =>
      val value = data.drop(i).grouped(k).map(_.head).sum
      if (value <= acc)
        (value, i)
      else
        (acc, index)
  }._2 + 1)
}

import java.util.Scanner

object DimaAndTodolist extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    val k = scan.nextInt

    val s = {
        for(i <- 0 until n) yield (i % k, scan.nextInt)
        }.groupBy(_._1)

    val ans = s.map(kv =>
        (kv._1, kv._2.map(_._2).reduce(_ + _))).min._1 + 1

    println(ans)
}

import java.util.Scanner

object DimaAndTodolist extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    val k = scan.nextInt

    val s = {
        for(i <- 0 until n) yield (i % k, scan.nextInt)
        }.groupBy(_._1)

    val ans = s.map(kv =>
        (kv._1, kv._2.map(_._2).reduce(_ + _))).minBy(_._2)._1 + 1

    println(ans)
}


AquaMoon has $$$n$$$ friends. They stand in a row from left to right, and the $$$i$$$-th friend from the left wears a T-shirt with a number $$$a_i$$$ written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.AquaMoon hopes that after some operations, the numbers written on the T-shirt of $$$n$$$ friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 50$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of Aquamoon's friends. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — the numbers, written on the T-shirts. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteThe possible list of operations in the first test case:  Swap $$$a_1$$$ and $$$a_2$$$. The resulting sequence is $$$3, 4, 2, 5$$$. The directions are: left, left, right, right.  Swap $$$a_2$$$ and $$$a_3$$$. The resulting sequence is $$$3, 2, 4, 5$$$. The directions are: left, left, right, right.  Swap $$$a_1$$$ and $$$a_2$$$. The resulting sequence is $$$2, 3, 4, 5$$$. The directions are: right, right, right, right.

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

  def f: Array[Int] => Map[Int, (Int, Int)] =
    _.zipWithIndex.foldLeft(Map.empty[Int, (Int, Int)]) { case (map, (ai, i)) =>
      val (even, odd) = map.getOrElse(ai, (0, 0))
      map.updated(ai, if (i % 2 == 0) (even + 1, odd) else (even, odd + 1))
      // map.updatedWith(ai) {
      //   case Some((even, odd)) => if (i % 2 == 0) Some(even + 1, odd) else Some(even, odd + 1)
      //   case None              => if (i % 2 == 0) Some(1, 0) else Some(0, 1)
      // }
    }

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val ans: Boolean = {
      val (amap, bmap) = (f(an), f(an.sorted))
      amap.foldLeft(true) { case (result, (ai, count)) => result && bmap(ai) == count }
    }

    ans match {
      case true => println("yes")
      case _    => println("no")
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val ans: Boolean = {
      val bn = an.zipWithIndex.sorted
      val cn = bn.zipWithIndex.map { case ((ai, i), j) => (ai, math.abs(i - j) % 2) }

      def check(ls: List[Int]): Boolean = ls.forall(_ == 0) || {
        val ms = ls.foldLeft(List.empty[Int]) {
          case (0 :: ms, 0) => 1 :: 1 :: ms
          case (ms, l)      => l :: ms
        }

        ms.mkString("").split("0").forall(_.length % 2 == 0)
      }

      @annotation.tailrec
      def go(i: Int, ls: List[Int]): Boolean =
        if (i == n) check(ls)
        else if (i != 0 && cn(i)._1 == cn(i - 1)._1) go(i + 1, cn(i)._2 :: ls)
        else check(ls) && go(i + 1, cn(i)._2 :: Nil)

      go(0, Nil)
    }

    ans match {
      case true => println("yes")
      case _    => println("no")
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val ans = {
      val bn = an.zipWithIndex.sorted
      val cn = bn.zipWithIndex.map { case ((ai, i), j) => (ai, (i - j) % 2 == 0) }

      (0 until n).forall { i =>
        cn(i) match {
          case (ai, false) =>
            if (i != 0 && cn(i - 1) == (ai, false)) {
              cn(i) = (ai, true)
              cn(i - 1) = (ai, true)
              true
            } else if (i != n - 1 && cn(i + 1) == (ai, false)) {
              cn(i) = (ai, true)
              cn(i + 1) = (ai, true)
              true
            } else false
          case _           => true
        }
      }
    }

    ans match {
      case true => println("yes")
      case _    => println("no")
    }
  }
}


You are given an array consisting of n non-negative integers a1, a2, ..., an.You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).  The third line contains a permutation of integers from 1 to n — the order used to destroy elements.

Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.

NoteConsider the first sample:   Third element is destroyed. Array is now 1 3  *  5. Segment with maximum sum 5 consists of one integer 5.  Fourth element is destroyed. Array is now 1 3  *   * . Segment with maximum sum 4 consists of two integers 1 3.  First element is destroyed. Array is now  *  3  *   * . Segment with maximum sum 3 consists of one integer 3.  Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Long](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  var max = 0l
  val answer = queries.reverse.map { i =>
    val sumToRemove = List(
      if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),
      if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumToRemove.sum
    sum(startIndex) = nSum
    max = Math.max(nSum, max)
    max
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Long](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  var max = 0l
  val answer = queries.reverse.map { i =>
    val sumParts =
      (if (i == 0 || start(i - 1) == -1) 0 else sum(start(i - 1))) +
        (if (i == n - 1 || end(i + 1) == -1) 0 else sum(i + 1))

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumParts
    sum(startIndex) = nSum
    max = Math.max(nSum, max)
    max
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}

import java.util

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

  class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val as = readLongs(n)
  val ps = readInts(n).map(_ - 1)
  val right = Array.fill(n + 1){ -1 }

  val bit = new BIT(as)

  val left = new util.TreeSet[Int]
  left.add(0)
  right(0) = n - 1

  val max = new util.TreeMap[Long, Int]

  def incMax(x: Long) = {
    if (max.containsKey(x)) max.put(x, max.get(x) + 1)
    else max.put(x, 1)
  }

  def decMax(x: Long) = {
    max.put(x, max.get(x) - 1)
    if (max.get(x) == 0) max.remove(x)
  }

  incMax(as.sum)

  var res = Array.ofDim[Long](n)

  for (i <- 0 until n) {

    val p = ps(i)
    val l = left.floor(p)
    val r = right(l)

    val sum = bit.rangeQuery(l, r)
    decMax(sum)

    val lSum = bit.rangeQuery(l, p - 1)
    incMax(lSum)

    val rSum = bit.rangeQuery(p + 1, r)
    incMax(rSum)

    right(l) = p - 1
    left.add(p + 1)
    right(p + 1) = r
    res(i) = max.lastKey
  }

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

  println(res.mkString("\n"))

  Console.flush
}

import java.util

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

  object BIT {

    def query(t: Array[Long], r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(t: Array[Long], l: Int, r: Int) = query(t, r) - query(t, l - 1)

    def update(t: Array[Long], i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Long]): Array[Long] = {
      val t = Array.fill(src.length) { 0L }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val Array(n) = readInts(1)
  val as = readLongs(n)
  val ps = readInts(n).map(_ - 1)
  val right = Array.fill(n + 1){ -1 }

  val bit = BIT(as)

  val left = new util.TreeSet[Int]
  left.add(0)
  right(0) = n - 1

  val max = new util.TreeMap[Long, Int]

  def incMax(x: Long) = {
    if (max.containsKey(x)) max.put(x, max.get(x) + 1)
    else max.put(x, 1)
  }

  def decMax(x: Long) = {
    max.put(x, max.get(x) - 1)
    if (max.get(x) == 0) max.remove(x)
  }

  incMax(as.sum)

  var res = Array.ofDim[Long](n)

  for (i <- 0 until n) {
    val p = ps(i)
    val l = left.floor(p)
    val r = right(l)
    //println(l, r)
    val sum = BIT.rangeQuery(bit, l, r)
    decMax(sum)
    val lSum = BIT.rangeQuery(bit, l, p - 1)
    incMax(lSum)
    val rSum = BIT.rangeQuery(bit, p + 1, r)
    incMax(rSum)
    //println(sum, lSum, rSum)
    right(l) = p - 1
    left.add(p + 1)
    right(p + 1) = r
    res(i) = max.lastKey
  }

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

  println(res.mkString("\n"))

  Console.flush
}

object _722C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val elements = read[Vector, Long](n)
    val destroyOrder = read[Vector, Int](n).map(_ - 1)
    val prefixSum = elements.scanLeft(0L)(_ + _)

    def sum(from: Int, until: Int): Long = prefixSum(until) - prefixSum(from)

    val invalids = new java.util.TreeSet[Int]
    val counts = new java.util.TreeMap[Long, Int]

    def add(l: Int, r: Int) = {
      val s = sum(l, r)
      val x = Option(counts.get(s)).getOrElse(0)
      counts.put(s, x + 1)
      //debug("add", l, r, s, counts)
    }

    def remove(i: Int): Long = {
      val l = Option(invalids.floor(i)).map(_ + 1) getOrElse 0
      val r = Option(invalids.ceiling(i)) getOrElse n
      val s = sum(l, r)
      val c = counts.get(s)
      if (c == 1) counts.remove(s) else counts.put(s, c - 1)
      invalids.add(i)
      //debug("remove", i, elements(i), l, r, s, c, counts, invalids)
      add(l, i)
      add(i+1, r)
      counts.lastKey()
    }

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

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

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

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

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

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

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

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

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

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Int](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  var max = 0
  val answer = queries.reverse.map { i =>
    val sumToRemove = List(
      if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),
      if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumToRemove.sum
    sum(startIndex) = nSum
    max = Math.max(nSum, max)
    max
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Int](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  var max = 0l
  val answer = queries.reverse.map { i =>
    val sumToRemove = List(
      if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),
      if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumToRemove.sum
    sum(startIndex) = nSum
    max = Math.max(nSum, max)
    max
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val queries = in.next().split(' ').map(_.toInt - 1)
  val sum = Array.ofDim[Int](n)
  val start = Array.fill[Int](n) {
    -1
  }
  val end = Array.fill[Int](n) {
    -1
  }
  val queue = mutable.PriorityQueue.empty[Int]
  var remove = Map.empty[Int, Int]
  val answer = queries.reverse.map { i =>
    val sumToRemove = List(
      if (i == 0 || start(i - 1) == -1) None else Some(sum(start(i - 1))),
      if (i == n - 1 || end(i + 1) == -1) None else Some(sum(i + 1))).flatten

    val startIndex = if (i == 0 || start(i - 1) == -1) i else start(i - 1)
    val endIndex = if (i == n - 1 || end(i + 1) == -1) i else end(i + 1)
    start(endIndex) = startIndex
    end(startIndex) = endIndex
    val nSum = line(i) + sumToRemove.sum
    sum(startIndex) = nSum

    sumToRemove.foreach { sum =>
      remove += (sum -> (remove.getOrElse(sum, 0) + 1))
    }
    queue.enqueue(-nSum)

    while (remove.getOrElse(queue.head, 0) != 0) {
      remove += (queue.head -> (remove(queue.head) - 1))
    }
    -queue.dequeue()
  }
  println(answer.reverse.tail.mkString("\n"))
  println(0)
}


Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel.  It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.

If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.

NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.

import scala.io.StdIn

object Codeforces1011C {

  def getCoefficients(n: Int, a: Array[Int], b: Array[Int]): Seq[Int] = {
    val coefficients = new Array[Int](2 * n)
    for (i <- 0 until n) {
      coefficients(2 * i) = a(i)
      coefficients(2 * i + 1) = b((i + 1) % n)
    }
    coefficients
  }

  def getFuel(n: Int, m: Int, a: Array[Int], b: Array[Int]): BigDecimal = {
    val coefficients = getCoefficients(n, a, b)
    if (coefficients contains 1) return -1
    var totalFuels = BigDecimal.valueOf(0)
    for (coefficient <- coefficients.reverse) {
      totalFuels += (m + totalFuels) / (coefficient - 1)
    }
    totalFuels
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val m = StdIn.readInt()
    val a = StdIn.readLine.trim.split(" ").map(_.toInt)
    val b = StdIn.readLine.trim.split(" ").map(_.toInt)
    val fuel = getFuel(n, m, a, b)
    println(fuel)
  }
}

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)

  val EPS = 1e-11
  def lt(x: Double, y: Double) = x < y - EPS
  def le(x: Double, y: Double) = x < y + EPS
  def gt(x: Double, y: Double) = x > y - EPS
  def ge(x: Double, y: Double) = x > y + EPS
  def eq(x: Double, y: Double) = abs(x - y) < EPS

  def solve(): Unit = {
    val N, M = ni()
    val A, B = na(N)
    val C = Array.ofDim[Int](2 * N)
    REP(N) { i =>
      C(2 * i) = A(i)
      C(2 * i + 1) = B((i + 1) % N)
    }

//    debug(C)

    val INF = 1e9 + 1
//    val INF = 100d // debug
    var l = 0d
    var r = INF

    def simulate(x: Double): Boolean = {
//      debug(s"simulate($x)")
      var fuel = x
      REP(C.length) { i =>
        fuel -= (M + fuel) / C(i)
//        debug(fuel.toString)
        if (lt(fuel, 0)) return false
      }
      true
    }

    REP(100) { _ =>
      val mid = (r + l) / 2
      if (simulate(mid)) r = mid
      else l = mid
    }

    if (r == INF) {
      out.println(-1)
    } else {
      out.println(f"$r%.10f")
    }
  }

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

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

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

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

  def debug(num: Long): Unit = {
    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 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
  }
}

object CF499C extends App {

  import java.io.PrintWriter
  import java.util.Scanner

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

  def solve: Unit = {
    val n = in.nextInt // number of planets
    val m = in.nextInt.toDouble // weight of the payload
    val as = new Array[Double](n).map(_ => in.nextInt.toDouble) // number of tons which can be lifted off by one ton of fuel
    val bs = new Array[Double](n).map(_ => in.nextInt.toDouble) // number of tons which can be landed by one ton of fuel

    //     fuel * factor = fuel + payload
    // <=> fuel = payload / (factor - 1), factor != 1

    if (Math.min(as.min, bs.min) <= 1) {
      out.println(-1) // Can't lift our fuel
      return
    }

    def calculateFuel(fuel: Double, planet: Int): Double = {
      val a = as(planet)
      val b = bs(planet)

      val fuelForLanding = (m + fuel) / (b - 1)
      val fuelForTakeOff = (m + fuel + fuelForLanding) / (a - 1)

      if (planet == 1)
        return fuelForTakeOff + fuelForLanding + fuel
      else
        return calculateFuel(fuelForTakeOff + fuelForLanding + fuel, planet - 1)
    }

    val fuelEarthLanding = m / (bs(0) - 1)
    val fuelBeforeEarthLanding = calculateFuel(fuelEarthLanding, n-1)
    val totalFuel = fuelBeforeEarthLanding + (m + fuelBeforeEarthLanding) / (as(0) - 1)

    out.println(totalFuel)
  }

  solve
  out.flush
  out.close
}


According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.

The first line of the input contains numbers n and m (1 ≤ n, m ≤ 100), n — the amount of rows, m — the amount of columns on the flag of Berland. Then there follows the description of the flag: each of the following n lines contain m characters. Each character is a digit between 0 and 9, and stands for the colour of the corresponding square.

Output YES, if the flag meets the new ISO standard, and NO otherwise.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(m, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.distinct.length > 1) || (m != 1 && data.sliding(2).exists(t => t.head.head == t.last.head)))
    println("NO")
  else
    println("YES")
}

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

  val N, _ = sc.nextInt
  sc.nextLine
  val Flag = List.fill(N)(sc.nextLine.toList)
  val striped = Flag.forall(_.distinct.size == 1)
  val validColoring = Flag.transpose.head.sliding(2).forall {
      case List(x, y) => x != y
      case List(x)    => true
    }
  val res = if (striped && validColoring) "YES"
            else "NO"
  out.println(res)
  out.close
}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 25 Jun 2016
 */
object A16 extends App {

  def solve() = {
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val a: Array[Char] = Array.ofDim[Char](n)
    var b = true
    for (i <- 0 until n) {
      if (b) {
        val s: mutable.Set[Char] = mutable.Set.empty
        scala.io.StdIn.readLine().foreach(s += _)
        if (s.size != 1) {
          b = false
        } else {
          a(i) = s.head
        }
      }
    }
    a.sliding(2).foreach(arr => {
      if (b) {
        if (arr.length > 1 && arr(0) == arr(1)) {
          b = false
        }
      }
    })
    println(if (b) "YES" else "NO")
  }

  solve()

}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val n = nextInt
    val m = nextInt
    var prevColor = -1
    var flag = true
    for (i <- 0 until n) {
      val line = next.toCharArray
      val lineColor = line(0)
      for (j <- 1 until m ) {
        if (line(j) != lineColor) {
          flag = false
        }
      }
      if (lineColor == prevColor) {
        flag = false
      }
      prevColor = lineColor
    }
    if (flag) {
      out.println("YES")
    } else {
      out.println("NO")
    }
  }

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

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val a = (1 to n).map(_ => readLine())
    val tr = a.map{ s =>
      val c = s(0)
      if (s.count(_ == c) == m) Some(c)
      else None
    }
    if (tr.count(_ == None) > 0) println("NO")
    else if (tr.size != 1 && tr.sliding(2).count(t => t(0) == t(1)) > 0) println("NO")
    else println("YES")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(m, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))
    println("NO")
  else
    println("YES")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(m, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.distinct.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))
    println("NO")
  else
    println("YES")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(m, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.distinct.length > 1) || data.sliding(2).forall(t => t.head.head != t.last.head))
    println("NO")
  else
    println("YES")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next())
  if (data.exists(_.length > 1) || data.sliding(2).exists(t => t.head.head == t.last.head))
    println("NO")
  else
    println("YES")
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val a = (1 to n).map(_ => readLine())
    val tr = a.map{ s =>
      val c = s(0)
      if (s.count(_ == c) == n) Some(c)
      else None
    }
    if (tr.count(_ == None) > 0) println("NO")
    else if (tr.sliding(2).count(t => t(0) == t(1)) > 0) println("NO")
    else println("YES")
  }
}


Petya has recently started working as a programmer in the IT city company that develops computer games.Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.

The only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx2 + vy2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c).

Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10 - 9.

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

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)

    var Array(px, py, vx, vy, a, b, c, d) = in.nextLine().split(' ').map(_.toDouble)

    var g = Math.sqrt(vx * vx + vy * vy)
    vx = vx / g
    vy = vy / g
    val (rx, ry) = (-vy, vx)

    var res = ArrayBuffer.empty[(Double, Double)]

    res += Tuple2(px + vx * b, py + vy * b)
    res += Tuple2(px + rx * a / 2, py + ry * a / 2)
    res += Tuple2(px + rx * c / 2, py + ry * c / 2)
    res += Tuple2(px - vx * d + rx * c / 2, py - vy * d + ry * c / 2)
    res += Tuple2(px - vx * d - rx * c / 2, py - vy * d - ry * c / 2)
    res += Tuple2(px - rx * c / 2, py - ry * c / 2)
    res += Tuple2(px - rx * a / 2, py - ry * a / 2)

    for (p <- res) {
      println("%.10f %.10f".format(p._1, p._2))
    }
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$.

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

Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element.

NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$.

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val _ = stdin.next().toInt
  val data = stdin.next().split(' ').map(_.toInt)
  var from = 0
  var maxSoFar = calc(data, from, None)
//  println("First = " + maxSoFar)
//  println(calc(data, 0, Some(2)))
  var endIndex = maxSoFar

  while (endIndex < data.length) {
    val deleteFirst = calc(data, from, Some(endIndex - 1)) - 1
    val deleteSecond = calc(data, from, Some(endIndex)) - 1
//    println("deleteFirst " + deleteFirst)
//    println("deleteSecond " + deleteSecond)
    maxSoFar = Math.max(maxSoFar, Math.max(deleteFirst, deleteSecond))
    from = endIndex
    endIndex = from + calc(data, from, None)
    maxSoFar = Math.max(maxSoFar, endIndex - from)
//    println("endIndex = " + endIndex)
  }

  println(maxSoFar)

  def calc(data: Array[Int], from: Int, removeIndex: Option[Int]): Int = {
    1 + Range(from + 1, data.length)
      .takeWhile(i => removeIndex.contains(i) || (if (removeIndex.contains(i - 1) && i -2 > 0) data(i) > data(i - 2) else data(i) > data(i - 1))).size
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val n = stdin.next().toInt
  val data = stdin.next().split(' ').map(_.toInt)
  var from = 0
  var maxSoFar = calc(data, from, None)
//  println("First = " + maxSoFar)
//  println(calc(data, 0, Some(2)))
  var endIndex = maxSoFar

  while (endIndex < n) {
    val deleteFirst = calc(data, from, Some(endIndex - 1)) - 1
    val deleteSecond = calc(data, from, Some(endIndex)) - 1
//    println("deleteFirst " + deleteFirst)
//    println("deleteSecond " + deleteSecond)
    maxSoFar = Math.max(maxSoFar, Math.max(deleteFirst, deleteSecond))
    from = endIndex + 1
    endIndex = from + calc(data, from, None)
    maxSoFar = Math.max(maxSoFar, endIndex - from)
//    println("endIndex = " + endIndex)
  }

  println(maxSoFar)

  def calc(data: Array[Int], from: Int, removeIndex: Option[Int]): Int = {
    1 + Range(from + 1, data.length).takeWhile(i => removeIndex.contains(i) || data(i) > data(i - 1)).size
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val _ = stdin.next().toInt
  val data = stdin.next().split(' ').map(_.toInt)
  var from = 0
  var maxSoFar = calc(data, from, None)
//  println("First = " + maxSoFar)
//  println(calc(data, 0, Some(2)))
  var endIndex = maxSoFar

  while (endIndex < data.length) {
    val deleteFirst = calc(data, from, Some(endIndex - 1)) - 1
    val deleteSecond = calc(data, from, Some(endIndex)) - 1
//    println("deleteFirst " + deleteFirst)
//    println("deleteSecond " + deleteSecond)
    maxSoFar = Math.max(maxSoFar, Math.max(deleteFirst, deleteSecond))
    from = endIndex + 1
    endIndex = from + calc(data, from, None)
    maxSoFar = Math.max(maxSoFar, endIndex - from)
//    println("endIndex = " + endIndex)
  }

//  println(maxSoFar)

  def calc(data: Array[Int], from: Int, removeIndex: Option[Int]): Int = {
    1 + Range(from + 1, data.length)
      .takeWhile(i => removeIndex.contains(i) || (if (removeIndex.contains(i - 1)) data(i) > data(i - 2) else data(i) > data(i - 1))).size
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val _ = stdin.next().toInt
  val data = stdin.next().split(' ').map(_.toInt)
  var from = 0
  var maxSoFar = calc(data, from, None)
//  println("First = " + maxSoFar)
//  println(calc(data, 0, Some(2)))
  var endIndex = maxSoFar

  while (endIndex < data.length) {
    val deleteFirst = calc(data, from, Some(endIndex - 1)) - 1
    val deleteSecond = calc(data, from, Some(endIndex)) - 1
//    println("deleteFirst " + deleteFirst)
//    println("deleteSecond " + deleteSecond)
    maxSoFar = Math.max(maxSoFar, Math.max(deleteFirst, deleteSecond))
    from = endIndex + 1
    endIndex = from + calc(data, from, None)
    maxSoFar = Math.max(maxSoFar, endIndex - from)
//    println("endIndex = " + endIndex)
  }

  println(maxSoFar)

  def calc(data: Array[Int], from: Int, removeIndex: Option[Int]): Int = {
    1 + Range(from + 1, data.length)
      .takeWhile(i => removeIndex.contains(i) || (if (removeIndex.contains(i - 1) && i -2 > 0) data(i) > data(i - 2) else data(i) > data(i - 1))).size
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2


An important meeting is to be held and there are exactly $$$n$$$ people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.Each person has limited sociability. The sociability of the $$$i$$$-th person is a non-negative integer $$$a_i$$$. This means that after exactly $$$a_i$$$ talks this person leaves the meeting (and does not talk to anyone else anymore). If $$$a_i = 0$$$, the $$$i$$$-th person leaves the meeting immediately after it starts.A meeting is considered most productive if the maximum possible number of talks took place during it.You are given an array of sociability $$$a$$$, determine which people should talk to each other so that the total number of talks is as large as possible.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) —the number of people in the meeting. The second line consists of $$$n$$$ space-separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2 \cdot 10^5$$$) — the sociability parameters of all people.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of all $$$a_i$$$ (over all test cases and all $$$i$$$) does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ answers to all test cases. On the first line of each answer print the number $$$k$$$ — the maximum number of talks possible in a meeting. On each of the next $$$k$$$ lines print two integers $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$ and $$$i \neq j$$$) — the numbers of people who will have another talk. If there are several possible answers, you may print any of them.

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val heap = new PriorityQueue[(Int, Int)]
        //var ans = Vector[(Int, Int)]()
        val ans = new ArrayBuffer[(Int, Int)]
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            if (tmp > 0)
                heap.enqueue((tmp, i+1))
        }
        var p1 = (0, 0)
        var p2 = (0, 0)
        while (heap.size > 1) {
            p1 = heap.dequeue()
            p2 = heap.dequeue()
            //ans = ans :+ (p1._2, p2._2)
            ans.append((p1._2, p2._2))
            if (p1._1 > 1)
                heap.enqueue((p1._1-1, p1._2))
            if (p2._1 > 1)
                heap.enqueue((p2._1-1, p2._2))
        }
        writer.println(ans.size)
        ans.foreach(x => writer.println(x._1 + " " + x._2))
    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val heap = new mutable.PriorityQueue[(Int, Int)]
        var ans = Vector[(Int, Int)]()
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            if (tmp > 0)
                heap.enqueue((tmp, i+1))
        }
        var p1 = (0, 0)
        var p2 = (0, 0)
        while (heap.size > 1) {
            p1 = heap.dequeue()
            p2 = heap.dequeue()
            ans = ans :+ (p1._2, p2._2)
            if (p1._1 > 1)
                heap.enqueue((p1._1-1, p1._2))
            if (p2._1 > 1)
                heap.enqueue((p2._1-1, p2._2))
        }
        writer.println(ans.size)
        ans.foreach(x => writer.println(x._1 + " " + x._2))
    }
    writer.flush()
}

object D extends App {
  import scala.collection.mutable.PriorityQueue

  type Talk = (Int, Int)

  def productiveMeeting(persons: IndexedSeq[Int]): List[Talk] = {
    val pq = PriorityQueue(persons.zipWithIndex: _*)

    @annotation.tailrec
    def go(talks: List[Talk]): List[Talk] =
      if (pq.length > 1) {
        val (s1, p1) = pq.dequeue()
        val (s2, p2) = pq.dequeue()

        if (s1 <= 0 || s2 <= 0) talks
        else {
          pq.enqueue((s1 - 1, p1), (s2 - 1, p2))
          go((p1, p2) :: talks)
        }
      } else talks

    go(List.empty[Talk])
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val pn = nextInts(n)

    val ts = productiveMeeting(pn)

    out.println(ts.length)
    ts.foreach { case (i, j) => out.println(s"${i + 1} ${j + 1}") }
  }

  out.flush()

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[myType](n)
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            arr(i) = myType(tmp, tmp, i+1)
        }
        quickSort(arr)
        var temp = 0
        var cnt = 0
        var po = 0
        var i = n-1
        while (i > po) {
            if (i > po && arr(i).cp == 0)
                i -= 1
            while (po < i && arr(po).cp == 0)
                po += 1
            tmp = i-1
            while (tmp >= po && arr(tmp).cp > 0 && arr(i).cp >0) {
                arr(tmp).cp -= 1
                arr(i).cp -= 1
                cnt += 1
                tmp -= 1
            }
            if (tmp > po && arr(tmp).cp == 0) {
                arr(tmp).cp = arr(po).cp
                po += 1
            }
        }
        writer.println(cnt)
        po = 0
        i = n-1
        while (i > po) {
            if (i > po && arr(i).social == 0)
                i -= 1
            while (po < i && arr(po).social == 0)
                po += 1
            tmp = i-1
            while (tmp >= po && arr(tmp).social > 0 && arr(i).social >0) {
                writer.println(arr(i).ind + " " + arr(tmp).ind)
                arr(tmp).social -= 1
                arr(i).social -= 1
                cnt += 1
                tmp -= 1
            }
            if (tmp > po && arr(tmp).social == 0) {
                temp = arr(tmp).ind
                arr(tmp).ind = arr(po).ind
                arr(po).ind = temp
                arr(tmp).social = arr(po).social
                po += 1
            }
        }
    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[myType](n)
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            arr(i) = myType(tmp, tmp, i+1)
        }
        quickSort(arr)
        var cnt = 0
        var po = n-2
        for (i <- (0 until n).reverse) {
            if (i == po)
                po -= 1
            while (po >= 0 && arr(i).cp > 0 && arr(po).cp > 0) {
                tmp = min(arr(i).cp, arr(po).cp)
                arr(i).cp -= tmp
                arr(po).cp -= tmp
                cnt += tmp
                if (arr(po).cp == 0) {
                    po -= 1
                }
            }
        }
        writer.println(cnt)
        po = n-2
        for (i <- (0 until n).reverse) {
            if (i == po)
                po -= 1
            while (po >= 0 && arr(i).social > 0 && arr(po).social > 0) {
                tmp = min(arr(i).social, arr(po).social)
                for (k <- 1 to tmp)
                    writer.println(arr(po).ind + " " + arr(i).ind)
                arr(i).social -= tmp
                arr(po).social -= tmp
                cnt += tmp
                if (arr(po).social == 0) {
                    po -= 1
                }
            }
        }

    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[myType](n)
        var tmp = 0
        for (i <- 0 until n) {
            tmp = readInt()
            arr(i) = myType(tmp, tmp, i+1)
        }
        quickSort(arr)
        var cnt = 0
        var po = n-2
        for (i <- (0 until n).reverse) {
            while (po >= 0 && arr(i).cp > 0 && arr(po).cp > 0) {
                tmp = min(arr(i).cp, arr(po).cp)
                arr(i).cp -= tmp
                arr(po).cp -= tmp
                cnt += tmp
                if (arr(po).cp == 0) {
                    po -= 1
                }
            }
        }
        writer.println(cnt)
        po = n-2
        for (i <- (0 until n).reverse) {
            while (po >= 0 && arr(i).social > 0 && arr(po).social > 0) {
                tmp = min(arr(i).social, arr(po).social)
                for (k <- 1 to tmp)
                    writer.println((po+1) + " " + (i+1))
                arr(i).social -= tmp
                arr(po).social -= tmp
                cnt += tmp
                if (arr(po).social == 0) {
                    po -= 1
                }
            }
        }

    }
    writer.flush()
}


Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.It is an undirected weighted graph on $$$n$$$ vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either $$$0$$$ or $$$1$$$; exactly $$$m$$$ edges have weight $$$1$$$, and all others have weight $$$0$$$.Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(\frac{n(n-1)}{2},10^5)$$$), the number of vertices and the number of edges of weight $$$1$$$ in the graph.  The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$), the endpoints of the $$$i$$$-th edge of weight $$$1$$$. It is guaranteed that no edge appears twice in the input.

Output a single integer, the weight of the minimum spanning tree of the graph.

NoteThe graph from the first sample is shown below. Dashed edges have weight $$$0$$$, other edges have weight $$$1$$$. One of the minimum spanning trees is highlighted in orange and has total weight $$$2$$$.  In the second sample, all edges have weight $$$0$$$ so any spanning tree has total weight $$$0$$$.

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.security.SecureRandom
import scala.annotation.tailrec

object CF_599_D {   var br = createBufferedReader(); var debugV = false

    import scala.collection.mutable.{Map => MyMap}
    import scala.collection.mutable.{Set => MySet}

    //COMMENT ME !
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val start = System.currentTimeMillis()
    val line = readLine
  	val n = line.int //vertices
  	val m = line.int //edge w1

  	var w1Edges = Array.fill(n)(Vector[Int]())
  	for(i <- 0 until m) {
  	  val vLine = readLine
  	  val a = vLine.int - 1
      val b = vLine.int - 1

      w1Edges(a) = w1Edges(a) :+ b
      w1Edges(b) = w1Edges(b) :+ a
  	}

    val durRead = System.currentTimeMillis() - start
    debug("durRead="+durRead)

    var domains = 0
//    w1Edges = w1Edges.sortBy(_.size)
    val processed = MySet[Int]()
    while (processed.size < n) {
      domains += 1
      val startV = (0 until n).find(i => !processed(i)).get
      debug("Domain start: " + (startV+1))
      goBreadth(Seq(startV))
    }

    def goBreadth(verts: Seq[Int]): Unit = {
//      debug("level: " + verts.map(_+1).mkString(","))
//      verts.foreach(v => processed += v)
      processed ++= verts
//      var all1ConnectionsVec = Vector[Int]()
      val blockMap = MyMap[Int, Int]().withDefaultValue(0)
//      verts.foreach(v => all1ConnectionsVec = (all1ConnectionsVec ++ w1Edges(v)) )
      verts.foreach{a =>
//        w1Edges(a).foreach(b => blockMap(b) = blockMap(b) + 1)
        w1Edges(a).foreach(b => blockMap(b) += 1)
      }
//      val all1Connections = all1ConnectionsVec.toSet
//      val all1Connections = verts.flatMap{v =>
//        w1Edges(v)}
//      val unproc = (0 until n).filter(v => !processed(v))
//      val connectedToThisLevel =  unproc.filterNot(all1Connections)
//      val connectedToThisLevel = (0 until n).filter(v => !processed(v) && !all1Connections(v))

      var nextLevel = Vector[Int]()
      for (v <- 0 until n) {
        if (!processed(v) && blockMap(v) < verts.size) nextLevel = nextLevel :+ v
      }

      if (nextLevel.size > 0) {
        goBreadth(nextLevel)
      }
    }

  	val res = (domains-1) + ""
    outLn(res)
    val durFull = System.currentTimeMillis() - start
    debug(s"durFull=$durFull")

//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
""" //2

val sa2 = """
3 0
""" //0

val t1 = """
7 5
7 5
1 5
3 2
2 6
3 6""" //0

val sa3 = genBig

def genBig(): String = {
  val verts = 100000
  val edges = 100000
  var res = s"""
$verts $edges
"""
  val sr = new SecureRandom()
  val allEdges = (0 until edges).map{i =>
    val a = sr.nextInt(verts-1) + 1
    val b = sr.nextInt(verts-1) + 1
    s"$a $b"
  }.mkString("\n")
  res += allEdges
  println(res.take(100))
  res
}
 }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.security.SecureRandom
import scala.annotation.tailrec

object CF_599_D {   var br = createBufferedReader(); var debugV = false

    //import scala.collection.mutable.{Map => MyMap}
    import scala.collection.mutable.{Set => MySet}

    //COMMENT ME !
    runTest(Test.sa3)
    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val start = System.currentTimeMillis()
    val line = readLine
  	val n = line.int //vertices
  	val m = line.int //edge w1

  	var w1Edges = Array.fill(n)(MySet[Int]())
  	for(i <- 0 until m) {
  	  val vLine = readLine
  	  val a = vLine.int - 1
      val b = vLine.int - 1

      w1Edges(a) += b
      w1Edges(b) += a
  	}

    val durRead = System.currentTimeMillis() - start
    debug("durRead="+durRead)

    var domains = 0
    w1Edges = w1Edges.sortBy(x => if(x!=null)x.size else 0)
    val processed = MySet[Int]()
    while (processed.size < n) {
      domains += 1
      val startV = (0 until n).find(i => !processed(i)).get
      goBreadth(Set(startV))
    }

    def goBreadth(verts: Set[Int]): Unit = {
//      verts.foreach(v => processed += v)
      processed ++= verts
//      var all1ConnectionsVec = Vector[Int]()
      val all1Connections = MySet[Int]()
//      verts.foreach(v => all1ConnectionsVec = (all1ConnectionsVec ++ w1Edges(v)) )
      verts.foreach(v => all1Connections ++= w1Edges(v) )
//      val all1Connections = all1ConnectionsVec.toSet
//      val all1Connections = verts.flatMap{v =>
//        w1Edges(v)}
//      val unproc = (0 until n).filter(v => !processed(v))
//      val connectedToThisLevel =  unproc.filterNot(all1Connections)
//      val connectedToThisLevel = (0 until n).filter(v => !processed(v) && !all1Connections(v))

      var nextLevel = Vector[Int]()
      for (v <- 0 until n) {
        if (!processed(v) && !all1Connections(v)) nextLevel = nextLevel :+ v
      }

      if (nextLevel.size > 0) {
        goBreadth(nextLevel.toSet)
      }
    }

  	val res = (domains-1) + ""
    outLn(res)
    val durFull = System.currentTimeMillis() - start
    debug(s"durFull=$durFull")

//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
""" //2

val sa2 = """
3 0
""" //0

val sa3 = genBig

def genBig(): String = {
  val verts = 100000
  val edges = 100000
  var res = s"""
$verts $edges
"""
  val sr = new SecureRandom()
  val allEdges = (0 until edges).map{i =>
    val a = sr.nextInt(verts-1) + 1
    val b = sr.nextInt(verts-1) + 1
    s"$a $b"
  }.mkString("\n")
  res += allEdges
  println(res.take(100))
  res
}
 }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.security.SecureRandom
import scala.annotation.tailrec

object CF_599_D {   var br = createBufferedReader(); var debugV = false

    //import scala.collection.mutable.{Map => MyMap}
    import scala.collection.mutable.{Set => MySet}

    //COMMENT ME !
//    runTest(Test.sa3)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val start = System.currentTimeMillis()
    val line = readLine
  	val n = line.int //vertices
  	val m = line.int //edge w1

  	var w1Edges = Array.fill(n)(Vector[Int]())
  	for(i <- 0 until m) {
  	  val vLine = readLine
  	  val a = vLine.int - 1
      val b = vLine.int - 1

      w1Edges(a) = w1Edges(a) :+ b
      w1Edges(b) = w1Edges(b) :+ a
  	}

    val durRead = System.currentTimeMillis() - start
    debug("durRead="+durRead)

    var domains = 0
//    w1Edges = w1Edges.sortBy(_.size)
    val processed = MySet[Int]()
    while (processed.size < n) {
      domains += 1
      val startV = (0 until n).find(i => !processed(i)).get
      goBreadth(Set(startV))
    }

    def goBreadth(verts: Set[Int]): Unit = {
//      verts.foreach(v => processed += v)
      processed ++= verts
//      var all1ConnectionsVec = Vector[Int]()
      val all1Connections = MySet[Int]()
//      verts.foreach(v => all1ConnectionsVec = (all1ConnectionsVec ++ w1Edges(v)) )
      verts.foreach(v => all1Connections ++= w1Edges(v) )
//      val all1Connections = all1ConnectionsVec.toSet
//      val all1Connections = verts.flatMap{v =>
//        w1Edges(v)}
//      val unproc = (0 until n).filter(v => !processed(v))
//      val connectedToThisLevel =  unproc.filterNot(all1Connections)
//      val connectedToThisLevel = (0 until n).filter(v => !processed(v) && !all1Connections(v))

      var nextLevel = Vector[Int]()
      for (v <- 0 until n) {
        if (!processed(v) && !all1Connections(v)) nextLevel = nextLevel :+ v
      }

      if (nextLevel.size > 0) {
        goBreadth(nextLevel.toSet)
      }
    }

  	val res = (domains-1) + ""
    outLn(res)
    val durFull = System.currentTimeMillis() - start
    debug(s"durFull=$durFull")

//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
""" //2

val sa2 = """
3 0
""" //0

val sa3 = genBig

def genBig(): String = {
  val verts = 100000
  val edges = 100000
  var res = s"""
$verts $edges
"""
  val sr = new SecureRandom()
  val allEdges = (0 until edges).map{i =>
    val a = sr.nextInt(verts-1) + 1
    val b = sr.nextInt(verts-1) + 1
    s"$a $b"
  }.mkString("\n")
  res += allEdges
  println(res.take(100))
  res
}
 }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.security.SecureRandom
import scala.annotation.tailrec

object CF_599_D {   var br = createBufferedReader(); var debugV = false

    //import scala.collection.mutable.{Map => MyMap}
    import scala.collection.mutable.{Set => MySet}

    //COMMENT ME !
    runTest(Test.sa3)
    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val start = System.currentTimeMillis()
    val line = readLine
  	val n = line.int //vertices
  	val m = line.int //edge w1

  	var w1Edges = Array.fill(n)(MySet[Int]())
  	for(i <- 0 until m) {
  	  val vLine = readLine
  	  val a = vLine.int - 1
      val b = vLine.int - 1

      w1Edges(a) += b
      w1Edges(b) += a
  	}

    val durRead = System.currentTimeMillis() - start
    debug("durRead="+durRead)

    var domains = 0
    w1Edges = w1Edges.sortBy(x => if(x!=null)x.size else 0)
    val processed = MySet[Int]()
    while (processed.size < n) {
      domains += 1
      val startV = (0 until n).find(i => !processed(i)).get
      goBreadth(Set(startV))
    }

    def goBreadth(verts: Set[Int]): Unit = {
      verts.foreach(v => processed += v)
      val unproc = (0 until n).filterNot(processed)
      val all1Connections = verts.flatMap(v=> w1Edges(v))
      val connectedToThisLevel =  unproc.filterNot(all1Connections)
      if (connectedToThisLevel.size > 0) {
        goBreadth(connectedToThisLevel.toSet)
      }
    }

  	val res = (domains-1) + ""
    outLn(res)
    val durFull = System.currentTimeMillis() - start
    debug(s"durFull=$durFull")

//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
""" //2

val sa2 = """
3 0
""" //0

val sa3 = genBig

def genBig(): String = {
  val verts = 100000
  val edges = 100000
  var res = s"""
$verts $edges
"""
  val sr = new SecureRandom()
  val allEdges = (0 until edges).map{i =>
    val a = sr.nextInt(verts-1) + 1
    val b = sr.nextInt(verts-1) + 1
    s"$a $b"
  }.mkString("\n")
  res += allEdges
  println(res.take(100))
  res
}
 }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.security.SecureRandom
import scala.annotation.tailrec

object CF_599_D {   var br = createBufferedReader(); var debugV = false

    //import scala.collection.mutable.{Map => MyMap}
    import scala.collection.mutable.{Set => MySet}

    //COMMENT ME !
//    runTest(Test.sa3)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val start = System.currentTimeMillis()
    val line = readLine
  	val n = line.int //vertices
  	val m = line.int //edge w1

  	var w1Edges = Array.fill(n)(MySet[Int]())
  	for(i <- 0 until m) {
  	  val vLine = readLine
  	  val a = vLine.int - 1
      val b = vLine.int - 1

      w1Edges(a) += b
      w1Edges(b) += a
  	}

    val durRead = System.currentTimeMillis() - start
    debug("durRead="+durRead)

    var domains = 0
    w1Edges = w1Edges.sortBy(x => if(x!=null)x.size else 0)
    val processed = MySet[Int]()
    while (processed.size < n) {
      domains += 1
      val startV = (0 until n).find(i => !processed(i)).get
      goBreadth(Set(startV))
    }

    def goBreadth(verts: Set[Int]): Unit = {
//      verts.foreach(v => processed += v)
      processed ++= verts
//      var all1ConnectionsVec = Vector[Int]()
      val all1Connections = MySet[Int]()
//      verts.foreach(v => all1ConnectionsVec = (all1ConnectionsVec ++ w1Edges(v)) )
      verts.foreach(v => all1Connections ++= w1Edges(v) )
//      val all1Connections = all1ConnectionsVec.toSet
//      val all1Connections = verts.flatMap{v =>
//        w1Edges(v)}
//      val unproc = (0 until n).filter(v => !processed(v))
//      val connectedToThisLevel =  unproc.filterNot(all1Connections)
//      val connectedToThisLevel = (0 until n).filter(v => !processed(v) && !all1Connections(v))

      var nextLevel = Vector[Int]()
      for (v <- 0 until n) {
        if (!processed(v) && !all1Connections(v)) nextLevel = nextLevel :+ v
      }

      if (nextLevel.size > 0) {
        goBreadth(nextLevel.toSet)
      }
    }

  	val res = (domains-1) + ""
    outLn(res)
    val durFull = System.currentTimeMillis() - start
    debug(s"durFull=$durFull")

//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
""" //2

val sa2 = """
3 0
""" //0

val sa3 = genBig

def genBig(): String = {
  val verts = 100000
  val edges = 100000
  var res = s"""
$verts $edges
"""
  val sr = new SecureRandom()
  val allEdges = (0 until edges).map{i =>
    val a = sr.nextInt(verts-1) + 1
    val b = sr.nextInt(verts-1) + 1
    s"$a $b"
  }.mkString("\n")
  res += allEdges
  println(res.take(100))
  res
}
 }
}


The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon.

Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

object ProblemC extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  import scala.collection.mutable
  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 t = in.nextInt()
  for (_ <- 1 to t) {
    val n = in.nextInt
    val p = n

    val r = 1.toDouble / (2 * math.sin(math.Pi / (2 * n)) / math.cos(math.Pi / (2 * n)))

    println(r * 2)
  }

}