General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier.On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers.Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.

The first line contains two integers n, k (1 ≤ n ≤ 50; 1 ≤ k ≤  ) — the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the beauties of the battalion soldiers. It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty.

Print k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer ci (1 ≤ ci ≤ n) — the number of soldiers in the detachment on the i-th day of the pageant and ci distinct integers p1, i, p2, i, ..., pci, i — the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order. Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions, print any of them.

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

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

  val n, k = sc.nextInt()
  val a = Array.tabulate(n)(_ => sc.nextInt())

  val mm = Map[Int, List[Int]]()

  for (i <- 0 until n if mm.size <= k) {
    val nm = mm map { x => (x._1 + a(i), x._2 :+ a(i)) } filter { x => !mm.contains(x._1) }
    mm ++= nm
    mm(a(i)) = List(a(i))
  }

  mm.take(k) foreach { x =>
    println(x._2.size + " " + x._2.mkString(" "))
  }
}

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

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

  val n, k = sc.nextInt()
  val a = Array.tabulate(n)(_ => sc.nextInt())

  val mm = Map[Int, List[Int]]()

  for (i <- 0 until n if mm.size <= k) {
    val nm = mm map { x => (x._1 + a(i), x._2 :+ (i+1)) } filter { x => !mm.contains(x._1) }
    mm ++= nm
    mm(a(i)) = List(i+1)
  }

  mm.take(k) foreach { x =>
    println(x._2.size + " " + x._2.mkString(" "))
  }
}


Polycarp likes arithmetic progressions. A sequence $$$[a_1, a_2, \dots, a_n]$$$ is called an arithmetic progression if for each $$$i$$$ ($$$1 \le i < n$$$) the value $$$a_{i+1} - a_i$$$ is the same. For example, the sequences $$$[42]$$$, $$$[5, 5, 5]$$$, $$$[2, 11, 20, 29]$$$ and $$$[3, 2, 1, 0]$$$ are arithmetic progressions, but $$$[1, 0, 1]$$$, $$$[1, 3, 9]$$$ and $$$[2, 3, 1]$$$ are not.It follows from the definition that any sequence of length one or two is an arithmetic progression.Polycarp found some sequence of positive integers $$$[b_1, b_2, \dots, b_n]$$$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $$$1$$$, an element can be increased by $$$1$$$, an element can be left unchanged.Determine a minimum possible number of elements in $$$b$$$ which can be changed (by exactly one), so that the sequence $$$b$$$ becomes an arithmetic progression, or report that it is impossible.It is possible that the resulting sequence contains element equals $$$0$$$.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 100\,000)$$$ — the number of elements in $$$b$$$. The second line contains a sequence $$$b_1, b_2, \dots, b_n$$$ $$$(1 \le b_i \le 10^{9})$$$.

If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).

NoteIn the first example Polycarp should increase the first number on $$$1$$$, decrease the second number on $$$1$$$, increase the third number on $$$1$$$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $$$[25, 20, 15, 10]$$$, which is an arithmetic progression.In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.In the third example it is impossible to make an arithmetic progression.In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like $$$[0, 3, 6, 9, 12]$$$, which is an arithmetic progression.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)

    if (N == 1) {
      out.println(0)
      return
    }

    def count(head: Int, last: Int): Option[Int] = {
      val inc = (last - head) / (N - 1)
      var cnt = 0
      REP(N) { i =>
        abs(A(i) - (head + i * inc)) match {
          case 0 =>
          case 1 => cnt +=1
          case _ => return None
        }
      }
      Some(cnt)
    }

    val ans = for {
      f <- Seq(-1, 0, 1)
      l <- Seq(-1, 0, 1)
      head = A(0) + f
      last = A(N - 1) + l
      if (last - head) % (N - 1) == 0
      res <- count(head, last)
    } yield res

    if (ans.isEmpty) out.println(-1)
    else out.println(ans.min)
  }

  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[Long]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object CF_978D {
	def check(b: Array[Int], d: Int) : Int = {
		var result = 0
		for(i <- 1 to b.length - 1)
		{
			if(math.abs(b(i) - b(0) - i*d) > 1)	return -1
			if(b(i) != b(0) + i*d)	result += 1
		}
		return result
	}
	def main(args: Array[String]) {
		val n = readInt()
		val temp_b = readLine().split(" ")
		if( n == 1 )
		{
			println(0)
			return
		}
		val b = for(x <- temp_b)	yield(x.toInt)
		var ans = n + 1
		for(i <- -1 to 1; j <- -1 to 1)
		{
			b(0) += i
			val res = check(b,b(1) + j - b(0))
			if(res != -1)
				ans = math.min(ans, (if(i == 0) 0 else 1) + res)
			b(0) -= i
		}

		if(ans > n)
			ans = -1
		println(ans)
	}
}


You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers.Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then:$$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$The sum of an empty array is $$$0$$$.Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.

Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).

NoteIn the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$.In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$.In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val cum = cumSum(A)
    var r = N - 1

    var ans = 0L
    REP(N) { l =>
      while(l < r && cum(l + 1) > cum(N) - cum(r)) r-= 1
      if (l < r && cum(l + 1) == cum(N) - cum(r)) ans = max(ans, cum(l + 1))
    }

    out.println(ans)
  }

  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 CF498C extends App {

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

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

  def solve = {
    val n = in.nextInt
    val array = new Array[Int](n).map(_ => in.nextInt)

    var a = 0
    var c = 0

    var leftSum = 0: Long
    var rightSum = 0: Long

    var max = 0: Long

    while (a+c <= n) {
      if (leftSum == rightSum)
        max = leftSum

      if (leftSum < rightSum) {
        a += 1
        if (a+c <= n)
          leftSum += array(a-1)
      }
      else {
        c += 1
        if (a + c <= n)
          rightSum += array(array.length - c)
      }
    }

    out.println(max)
  }

  solve
  out.flush
  out.close
}

object CF498C extends App {

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

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

  def solve = {
    val n = in.nextInt
    val array = new Array[Int](n).map(_ => in.nextInt)

    var a = 0
    var c = 0

    var leftSum = 0
    var rightSum = 0

    var max = 0

    while (a+c <= n) {
      if (leftSum == rightSum)
        max = leftSum

      if (leftSum < rightSum) {
        a += 1
        if (a+c <= n)
          leftSum += array(a-1)
      }
      else {
        c += 1
        if (a + c <= n)
          rightSum += array(array.length - c)
      }
    }

    out.println(max)
  }

  solve
  out.flush
  out.close
}


This is an interactive problem.You're given a tree consisting of $$$n$$$ nodes, rooted at node $$$1$$$. A tree is a connected graph with no cycles.We chose a hidden node $$$x$$$. In order to find this node, you can ask queries of two types:   d $$$u$$$ ($$$1 \le u \le n$$$). We will answer with the distance between nodes $$$u$$$ and $$$x$$$. The distance between two nodes is the number of edges in the shortest path between them.  s $$$u$$$ ($$$1 \le u \le n$$$). We will answer with the second node on the path from $$$u$$$ to $$$x$$$. However, there's a plot twist. If $$$u$$$ is not an ancestor of $$$x$$$, you'll receive "Wrong answer" verdict! Node $$$a$$$ is called an ancestor of node $$$b$$$ if $$$a \ne b$$$ and the shortest path from node $$$1$$$ to node $$$b$$$ passes through node $$$a$$$. Note that in this problem a node is not an ancestor of itself.Can you find $$$x$$$ in no more than $$$36$$$ queries? The hidden node is fixed in each test beforehand and does not depend on your queries.

The first line contains the integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.

To print the answer, print "! x" (without quotes).

NoteIn the first example, the hidden node is node $$$5$$$.  We first ask about the distance between node $$$x$$$ and node $$$2$$$. The answer is $$$3$$$, so node $$$x$$$ is either $$$4$$$ or $$$5$$$. We then ask about the second node in the path from node $$$3$$$ to node $$$x$$$. Note here that node $$$3$$$ is an ancestor of node $$$5$$$. We receive node $$$5$$$ as the answer. Finally, we report that the hidden node is node $$$5$$$.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def query(v: Int, tpe: Char): Int = {
    out.println(s"$tpe ${v+1}")
    out.flush()
    ni()
  }

  def solve(): Unit = {
    val N = ni()
    val (from, to) = na2(N - 1, -1)
    val g = packUGraph(N, from, to)
    val (depth, parent, queue) = traceBfs(g)
    val sz = Array.fill[Int](N)(1)
    REP_r(N) { i =>
      val v = queue(i)
      if (parent(v) != -1) sz(parent(v)) += sz(v)
    }
    debug(sz)

    def heavyPath(rt: Int): ArrayBuffer[Int] = {
      val res = ArrayBuffer[Int](rt)
      var it = rt
      while(it != -1) {
        var next = -1
        REP(g(it).length) { i =>
          val u = g(it)(i)
          if (parent(it) != u && (next == -1 || sz(u) > sz(next))) {
            next = u
          }
        }
        if (next != -1) res += next
        it = next
      }
      res
    }

    def step(rt: Int, d1: Int): Int = {
      val path = heavyPath(rt)
      debug(path.mkString(" "))
      val w = path.last
      if (rt == w) rt
      else {
        val d2 = query(w, 'd')
        val dist = depth(w) - depth(rt)

        debug(s"rt:$rt w:$w d1:$d1 d2:$d2 dist:$dist")

        if (dist == d1 + d2) {
          path(d1)
        } else {
          val d = (d1 + d2 - dist) / 2
          val joint = path(d1 - d)
          val next = query(joint, 's') - 1
          step(next, d - 1)
        }
      }
    }

    val ans = step(0, query(0, 'd'))
    out.println(s"! ${ans+1}")
    out.flush()
  }

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  var queryCnt = 36

  def query1(v: Int): Int = {
    queryCnt -= 1
    out.println(s"d ${v+1}")
    out.flush()
    ni()
  }

  def query2(v: Int): Int = {
    queryCnt -= 1
    out.println(s"s ${v+1}")
    out.flush()
    ni() - 1
  }

  def solve(): Unit = {
    val N = ni()
    val (from, to) = na2(N - 1, -1)
    val g = packUGraph(N, from, to)
    val (depth, parent, _) = traceBfs(g)
    debug(depth)
    debug(parent)

    def farthest(rt: Int): Int = {
      val n = g.length
      val q = Array.ofDim[Int](n)
      q(0) = rt
      var cur = 0
      var last = 1

      var farthest = rt

      while (cur < last) {
        val v = q(cur)
        if (depth(v) > depth(farthest)) farthest = v
        REP(g(v).length) { i =>
          val u = g(v)(i)
          if (u != parent(v)) {
            q(last) = u
            last += 1
          }
        }
        cur += 1
      }

      farthest
    }

    def up(s: Int, cnt: Int): Int = {
      var it = s
      REP(cnt) { _ =>
        it = parent(it)
      }
      it
    }

    def step(rt: Int, d1: Int): Int = {
      if (queryCnt >= d1) {
        var it = rt
        REP(d1) { _ =>
          it = query2(it)
        }
        return it
      }

      val u = farthest(rt)
      if (u == rt) return rt

      val d = depth(u) - depth(rt)
      debug(s"rt:$rt u:$u d:$d")
      val d2 = query1(u)
      debug(s"d1:$d1 d2:$d2")
      if (d1 + d2 == d) {
        up(u, d2)
      } else {
        val dd = (d1 + d2 - d) / 2
        val dd2 = d2 - dd
        val joint = up(u, dd2)
        step(query2(joint), dd - 1)
      }
    }

    val ans = step(0, query1(0))
    out.println(s"! ${ans+1}")
  }

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  var queryCnt = 36

  def query1(v: Int): Int = {
    queryCnt -= 1
    out.println(s"d ${v+1}")
    out.flush()
    ni()
  }

  def query2(v: Int): Int = {
    queryCnt -= 1
    out.println(s"s ${v+1}")
    out.flush()
    ni() - 1
  }

  def solve(): Unit = {
    val N = ni()
    val (from, to) = na2(N - 1, -1)
    val g = packUGraph(N, from, to)
    val (depth, parent, _) = traceBfs(g)
    debug(depth)
    debug(parent)

    def farthest(rt: Int): Int = {
      val n = g.length
      val q = Array.ofDim[Int](n)
      q(0) = rt
      var cur = 0
      var last = 1

      var farthest = rt

      while (cur < last) {
        val v = q(cur)
        if (depth(v) > depth(farthest)) farthest = v
        REP(g(v).length) { i =>
          val u = g(v)(i)
          if (u != parent(v)) {
            q(last) = u
            last += 1
          }
        }
        cur += 1
      }

      farthest
    }

    def downUntilJoint(rt: Int): (Int, Int) = {
      var cur = rt
      var cnt = 0

      while (g(cur).length == 2) {
        REP(g(rt).length) { i =>
          if (g(rt)(i) != parent(cur)) {
            cur = g(rt)(i)
          }
        }
        cnt += 1
      }
      (cur, cnt)
    }

    def up(s: Int, cnt: Int): Int = {
      var it = s
      REP(cnt) { _ =>
        it = parent(it)
      }
      it
    }

    def step(rt: Int, d1: Int): Int = {
      if (queryCnt >= d1) {
        var it = rt
        REP(d1) { _ =>
          it = query2(it)
        }
        return it
      }

      val u = farthest(rt)
      if (u == rt) return rt

      val d = depth(u) - depth(rt)
      debug(s"rt:$rt u:$u d:$d")
      val d2 = query1(u)
      debug(s"d1:$d1 d2:$d2")
      if (d1 + d2 == d) {
        up(u, d2)
      } else {
        val dd = (d1 + d2 - d) / 2
        val dd2 = d2 - dd
        val joint = up(u, dd2)
        val (nextRt, move) = downUntilJoint(joint)
        step(query2(nextRt), dd - move - 1)
      }
    }

    val ans = step(0, query1(0))
    out.println(s"! ${ans+1}")
  }

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def query1(v: Int): Int = {
    out.println(s"d ${v+1}")
    out.flush()
    ni()
  }

  def query2(v: Int): Int = {
    out.println(s"s ${v+1}")
    out.flush()
    ni() - 1
  }

  def solve(): Unit = {
    val N = ni()
    val (from, to) = na2(N - 1, -1)
    val g = packUGraph(N, from, to)
    val (depth, parent, _) = traceBfs(g)
    debug(depth)
    debug(parent)

    def farthest(rt: Int): Int = {
      val n = g.length
      val q = Array.ofDim[Int](n)
      q(0) = rt
      var cur = 0
      var last = 1

      var farthest = rt

      while (cur < last) {
        val v = q(cur)
        if (depth(v) > depth(farthest)) farthest = v
        REP(g(v).length) { i =>
          val u = g(v)(i)
          if (u != parent(v)) {
            q(last) = u
            last += 1
          }
        }
        cur += 1
      }

      farthest
    }

    def up(s: Int, cnt: Int): Int = {
      var it = s
      REP(cnt) { _ =>
        it = parent(it)
      }
      it
    }

    def step(rt: Int, d1: Int): Int = {
      val u = farthest(rt)
      if (u == rt) return rt

      val d = depth(u) - depth(rt)
      debug(s"rt:$rt u:$u d:$d")
      val d2 = query1(u)
      debug(s"d1:$d1 d2:$d2")
      if (d1 + d2 == d) {
        up(u, d2)
      } else {
        val dd = (d1 + d2 - d) / 2
        val dd2 = d2 - dd
        val joint = up(u, dd2)
        step(query2(joint), dd - 1)
      }
    }

    val ans = step(0, query1(0))
    out.println(s"! ${ans+1}")
  }

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }
}


Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.You're given $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. Using each of them exactly at once, you're to make such sequence $$$b_1, b_2, \dots, b_n$$$ that sequence $$$c_1, c_2, \dots, c_n$$$ is lexicographically maximal, where $$$c_i=GCD(b_1,\dots,b_i)$$$ - the greatest common divisor of the first $$$i$$$ elements of $$$b$$$. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$)  — the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\dots,a_n$$$ ($$$1 \le a_i \le 10^3$$$)  — the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.

For each test case output the answer in a single line  — the desired sequence $$$b$$$. If there are multiple answers, print any.

NoteIn the first test case of the example, there are only two possible permutations $$$b$$$  — $$$[2, 5]$$$ and $$$[5, 2]$$$: for the first one $$$c=[2, 1]$$$, for the second one $$$c=[5, 1]$$$.In the third test case of the example, number $$$9$$$ should be the first in $$$b$$$, and $$$GCD(9, 3)=3$$$, $$$GCD(9, 8)=1$$$, so the second number of $$$b$$$ should be $$$3$$$.In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation $$$b$$$.

//package codeforces.contests._1407

object BigVova {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val n = io.StdIn.readInt()
      val seq = io.StdIn.readLine.split(" ").map(_.toInt)

      @scala.annotation.tailrec
      def gcd(a: Int, b: Int): Int = {
        if (b == 0) a else gcd(b, a % b)
      }

      val maximumIdx = (0 until n).maxBy(seq)

      val done: collection.mutable.Set[Int] = collection.mutable.Set(maximumIdx)

      @scala.annotation.tailrec
      def loop(accGcd: Int = seq(maximumIdx), accRes: List[Int] = seq(maximumIdx) :: Nil): List[Int] = {
        if (done.size == n) accRes.reverse
        else {
          val toRemoveIdx = (0 until n).filter(!done(_)).maxBy(i => gcd(seq(i), accGcd))
          done += toRemoveIdx
          loop(gcd(seq(toRemoveIdx), accGcd), seq(toRemoveIdx) :: accRes)
        }
      }

      println(loop().mkString(" "))
    }
  }
}

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

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

  val t = readInt()

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

    val bn = Array.ofDim[Int](n)
    bn(0) = an.head

    @annotation.tailrec
    def go(i: Int, c: Int): Unit =
      if (i < n) {

        val (j, d) = ((i + 1) until n).foldLeft(i -> gcd(c, an(i))) {
          case ((j, d), k) =>
            val p = gcd(c, an(k))

            if (p > d) k -> p
            else j -> d
        }

        bn(i) = an(j)
        an(j) = an(i)

        go(i + 1, d)
      }

    go(1, an.head)

    println(bn.mkString(" "))
  }
}

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

  @annotation.tailrec
  def gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)
    val bn = Array.ofDim[Int](n)

    val counts = Array.fill(an.max + 1)(0)
    an.foreach(a => counts(a) += 1)

    @annotation.tailrec
    def go(i: Int, c: Int): IndexedSeq[Int] =
      if (i == n) bn
      else {
        val (b, d) = counts.zipWithIndex.foldLeft(0 -> 0) {
          case (state, (0, a)) => state
          case (state @ (_, d), (_, a)) =>
            val g = gcd(c, a)

            if (g >= d) a -> g else state
        }

        bn(i) = b
        counts(b) -= 1

        go(i + 1, d)
      }

    go(0, an.max)

    println(bn.mkString(" "))
  }
}

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

  @annotation.tailrec
  def gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)

  val t = readInt()

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

    @annotation.tailrec
    def go(an: Seq[Int], bn: List[Int], c: Int): Seq[Int] = an match {
      case Seq() => bn
      case _ =>
        val (ak, bk, d) = an.foldLeft((List.empty[Int], List.empty[Int], 0)) {
          case ((ak, bk, d), a) =>
            val g = gcd(c, a)

            if (g > d) (bk ::: ak, a :: Nil, g)
            else if (g == d) (ak, a :: bk, d)
            else (a :: ak, bk, d)
        }

        go(ak, bn ::: bk, d)
    }

    val bn = go(an, List.empty[Int], 0)

    println(bn.mkString(" "))
  }
}

//package codeforces.contests._1407

object BigVova {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val n = io.StdIn.readInt()
      val seq = io.StdIn.readLine.split(" ").map(_.toInt)

      @scala.annotation.tailrec
      def gcd(a: Int, b: Int): Int = {
        if (b == 0) a else gcd(b, a % b)
      }

      val maximum = seq.max

      @scala.annotation.tailrec
      def loop(elements: Set[Int] = seq.toSet-maximum, accRes: List[Int] = maximum :: Nil): List[Int] = {
        if (elements.isEmpty) accRes.reverse
        else {
          val accGcd = accRes.head
          val toRemove = elements.maxBy(gcd(_, accGcd))
          loop(elements - toRemove, toRemove :: accRes)
        }
      }

      println(loop().mkString(" "))
    }
  }
}

//package codeforces.contests._1407

object BigVova {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val n = io.StdIn.readInt()
      val seq = io.StdIn.readLine.split(" ").map(_.toInt)

      @scala.annotation.tailrec
      def gcd(a: Int, b: Int): Int = {
        if (b == 0) a else gcd(b, a % b)
      }

      val maximumIdx = (0 until n).maxBy(seq)

      val done: collection.mutable.Set[Int] = collection.mutable.Set(maximumIdx)

      @scala.annotation.tailrec
      def loop(accRes: List[Int] = seq(maximumIdx) :: Nil): List[Int] = {
        if (done.size == n) accRes.reverse
        else {
          val accGcd = accRes.head
          val toRemoveIdx = (0 until n).filter(!done(_)).maxBy(i => gcd(seq(i), accGcd))
          done += toRemoveIdx
          loop(seq(toRemoveIdx) :: accRes)
        }
      }

      println(loop().mkString(" "))
    }
  }
}


You are given a sequence of n integers a1, a2, ..., an. Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible.The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.The poorness of a segment is defined as the absolute value of sum of the elements of segment.

The first line contains one integer n (1 ≤ n ≤ 200 000), the length of a sequence. The second line contains n integers a1, a2, ..., an (|ai| ≤ 10 000).

Output a real number denoting the minimum possible weakness of a1 - x, a2 - x, ..., an - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.

NoteFor the first case, the optimal value of x is 2 so the sequence becomes  - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case. For the second sample the optimal value of x is 2.5 so the sequence becomes  - 1.5,  - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case.

import scala.collection._

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) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

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

  def calc(x: Double): Double = {

    var negSum, posSum = 0
    var negLen, posLen = 0
    var max = 0d

    for (a <- as) {

      negSum += a
      negLen += 1

      posSum += a
      posLen += 1

      val pos = posSum - x * posLen
      val neg = x * negLen - negSum

      if (pos < 0) {
        posSum = 0
        posLen = 0
      }
      if (neg < 0) {
        negSum = 0
        negLen = 0
      }

      if (neg > max) max = neg
      if (pos > max) max = pos
    }
    max
  }

  var done = false
  var left = as.min.toDouble
  var right = as.max.toDouble
  var min = Double.PositiveInfinity

  while (!done) {

    if (Math.abs(right - left) < 0.00000000001d) {
      min = Math.min(min, calc((right + left) / 2d))
      done = true
    } else {
      val leftThird = left + (right - left) / 3d
      val rightThird = right - (right - left) / 3d
      val l = calc(leftThird)
      val r = calc(rightThird)
      if (l < min) min = l
      if (r < min) min = r
      if (l > r) left = leftThird
      else right = rightThird
    }
  }

  println(min)
}

import scala.collection._

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) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

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

  def calc(x: Double): Double = {

    var negSum, posSum = 0L
    var negLen, posLen = 0L
    var max = 0d

    for (a <- as) {

      negSum += a
      negLen += 1

      posSum += a
      posLen += 1

      val pos = posSum - x * posLen
      val neg = x * negLen - negSum

      if (pos < 0) {
        posSum = 0
        posLen = 0
      }
      if (neg < 0) {
        negSum = 0
        negLen = 0
      }

      if (neg > max) max = neg
      if (pos > max) max = pos
    }
    max
  }

  var done = false
  var left = -10000d
  var right = 10000d
  var min = Double.PositiveInfinity

  while (!done) {

    if (Math.abs(right - left) < 0.0000000001d) {
      min = Math.min(min, calc((right + left) / 2d))
      done = true
    } else {
      val leftThird = left + (right - left) / 3d
      val rightThird = right - (right - left) / 3d
      val l = calc(leftThird)
      val r = calc(rightThird)
      if (l < min) min = l
      if (r < min) min = r
      if (l > r) left = leftThird
      else right = rightThird
    }
  }

  println(min)
}

import scala.collection._

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) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val as = readInts(n)
  //val x = (as.min + as.max) * 0.5d

  def calc(x: Double): Double = {
    var negSum, posSum = 0d
    var max = 0d
    for (a <- as) {
      negSum += (x - a)
      if (negSum < 0d) negSum = 0d
      posSum += (a - x)
      if (posSum < 0d) posSum = 0d
      if (negSum > max) max = negSum
      if (posSum > max) max = posSum
    }
    max
  }

  var done = false
  var left = -10000d
  var right = 10000d
  var min = Double.PositiveInfinity

  while (!done) {

    if (Math.abs(right - left) < 0.0000000001) {
      min = Math.min(min, calc((right + left) / 2))
      done = true
    } else {
      val leftThird = left + (right - left) / 3
      val rightThird = right - (right - left) / 3
      val l = calc(leftThird)
      val r = calc(rightThird)
      if (l < min) min = l
      if (r < min) min = r
      if (l > r) left = leftThird
      else right = rightThird
    }
  }

  println(min)
}

import scala.collection._

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) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val as = readInts(n)
  //val x = (as.min + as.max) * 0.5d

  def calc(x: Double): Double = {
    var negSum, posSum = 0L
    var negLen, posLen = 0L
    var max = 0d
    for (a <- as) {
      if (a < x) {
        negSum += a
        negLen += 1
        posSum = 0
        posLen = 0
      } else if (a > x) {
        posSum += a
        posLen += 1
        negSum = 0
        negLen = 0
      }
      val pos = posSum - x * posLen
      val neg = x * negLen - negSum
      if (neg > max) max = neg
      if (pos > max) max = pos
    }
    max
  }

  var done = false
  var left = -10000d
  var right = 10000d
  var min = Double.PositiveInfinity

  while (!done) {

    if (Math.abs(right - left) < 0.00000000001d) {
      min = Math.min(min, calc((right + left) / 2))
      done = true
    } else {
      val leftThird = left + (right - left) / 3
      val rightThird = right - (right - left) / 3
      val l = calc(leftThird)
      val r = calc(rightThird)
      if (l < min) min = l
      if (r < min) min = r
      if (l > r) left = leftThird
      else right = rightThird
    }
  }

  println(min)
}

import scala.collection._

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) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

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

  def calc(x: Double): Double = {

    var negSum, posSum = 0L
    var negLen, posLen = 0L
    var max = 0d

    for (a <- as) {

      negSum += a
      negLen += 1

      posSum += a
      posLen += 1

      val pos = posSum - x * posLen
      val neg = x * negLen - negSum

      if (pos < 0) {
        posSum = 0
        posLen = 0
      }
      if (neg < 0) {
        negSum = 0
        negLen = 0
      }

      if (neg > max) max = neg
      if (pos > max) max = pos
    }
    max
  }

  var done = false
  var left = -10000d
  var right = 10000d
  var min = Double.PositiveInfinity

  while (!done) {

    if (Math.abs(right - left) < 0.0000000001) {
      min = Math.min(min, calc((right + left) / 2))
      done = true
    } else {
      val leftThird = left + (right - left) / 3
      val rightThird = right - (right - left) / 3
      val l = calc(leftThird)
      val r = calc(rightThird)
      if (l < min) min = l
      if (r < min) min = r
      if (l > r) left = leftThird
      else right = rightThird
    }
  }

  println(min)
}

import scala.collection._

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) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val as = readInts(n)
  //val x = (as.min + as.max) * 0.5d

  def calc(x: Double): Double = {
    var negSum, posSum = 0d
    var max = 0d
    for (a <- as) {
      if (a < x) {
        negSum += (x - a)
        posSum = 0
      } else if (a > x) {
        posSum += (a - x)
        negSum = 0
      }
      if (negSum > max) max = negSum
      if (posSum > max) max = posSum
    }
    max
  }

  var done = false
  var left = -10000d
  var right = 10000d
  var min = Double.PositiveInfinity

  while (!done) {

    if (Math.abs(right - left) < 0.0000000001) {
      min = Math.min(min, calc((right + left) / 2))
      done = true
    } else {
      val leftThird = left + (right - left) / 3
      val rightThird = right - (right - left) / 3
      val l = calc(leftThird)
      val r = calc(rightThird)
      if (l < min) min = l
      if (r < min) min = r
      if (l > r) left = leftThird
      else right = rightThird
    }
  }

  println(min)
}

import scala.collection._

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) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val as = readInts(n)
  //val x = (as.min + as.max) * 0.5d

  def calc(x: Double): Double = {
    var negSum, posSum = 0L
    var negLen, posLen = 0L
    var max = 0d
    for (a <- as) {
      if (a <= x) {
        negSum += a
        negLen += 1
      } else {
        negSum = 0
        negLen = 0
      }
      if (a >= x) {
        posSum += a
        posLen += 1
      } else {
        posSum = 0
        posLen = 0
      }
      val pos = posSum - x * posLen
      val neg = x * negLen - negSum
      if (neg > max) max = neg
      if (pos > max) max = pos
    }
    max
  }

  var done = false
  var left = -10000d
  var right = 10000d
  var min = Double.PositiveInfinity

  while (!done) {

    if (Math.abs(right - left) < 0.00000000001d) {
      min = Math.min(min, calc((right + left) / 2))
      done = true
    } else {
      val leftThird = left + (right - left) / 3
      val rightThird = right - (right - left) / 3
      val l = calc(leftThird)
      val r = calc(rightThird)
      if (l < min) min = l
      if (r < min) min = r
      if (l > r) left = leftThird
      else right = rightThird
    }
  }

  println(min)
}


One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?

The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.

In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a: Array[Long] = in.next().split(' ').map(_.toLong).sorted
  val x = a.sum / (n - 1) + (if (a.sum % (n - 1) > 0) 1 else 0)
  println(Math.max(x, a.max))
}

import scala.collection._

object A extends App {

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

  val n = readString.toInt
  val as = readLongs(n).sorted

  def can(m: Long): Boolean = {
    var i = 0
    var games = 0L
    while (i < as.size && games < m) {
      games += (m - as(i))
      i += 1
    }
    games >= m
  }

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) >>> 1
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  println(binSearch(as.max, as.sum))
}

import java.util.Scanner

import scala.collection.mutable
import scala.io.StdIn._

object Main {
  val scanner = new Scanner(System.in)
  import scanner._
  def main(args: Array[String]): Unit = {
      val n = readInt()
      val v = readLine().split(" ").map(_.toLong)
      val totSum: Long = v.sum
      val ans: Long =  (totSum/(n-1) + (if(totSum%(n-1) == 0)  0 else 1))
      println(ans.max(v.max))
  }
}

import java.util.Scanner

import scala.collection.mutable
import scala.io.StdIn._

object Main {
  val scanner = new Scanner(System.in)
  import scanner._
  def main(args: Array[String]): Unit = {
      val n = readInt()
      val v = readLine().split(" ").map(_.toInt)
      val totSum = v.sum
      val ans =  (totSum/(n-1) + (if(totSum%(n-1) == 0)  0 else 1))
      println(ans)
  }
}

import java.util.Scanner

import scala.collection.mutable
import scala.io.StdIn._

object Main {
  val scanner = new Scanner(System.in)
  import scanner._
  def main(args: Array[String]): Unit = {
      val n = readInt()
      val v = readLine().split(" ").map(_.toInt)
      val totSum = v.sum
      val ans =  (totSum/(n-1) + (if(totSum%(n-1) == 0)  0 else 1))
      println(ans.max(v.max))
  }
}


It's election time in Berland. The favorites are of course parties of zublicanes and mumocrates. The election campaigns of both parties include numerous demonstrations on n main squares of the capital of Berland. Each of the n squares certainly can have demonstrations of only one party, otherwise it could lead to riots. On the other hand, both parties have applied to host a huge number of demonstrations, so that on all squares demonstrations must be held. Now the capital management will distribute the area between the two parties.Some pairs of squares are connected by (n - 1) bidirectional roads such that between any pair of squares there is a unique way to get from one square to another. Some squares are on the outskirts of the capital meaning that they are connected by a road with only one other square, such squares are called dead end squares.The mayor of the capital instructed to distribute all the squares between the parties so that the dead end squares had the same number of demonstrations of the first and the second party. It is guaranteed that the number of dead end squares of the city is even.To prevent possible conflicts between the zublicanes and the mumocrates it was decided to minimize the number of roads connecting the squares with the distinct parties. You, as a developer of the department of distributing squares, should determine this smallest number.

The first line of the input contains a single integer n (2 ≤ n ≤ 5000) — the number of squares in the capital of Berland. Next n - 1 lines contain the pairs of integers x, y (1 ≤ x, y ≤ n, x ≠ y) — the numbers of the squares connected by the road. All squares are numbered with integers from 1 to n. It is guaranteed that the number of dead end squares of the city is even.

Print a single number — the minimum number of roads connecting the squares with demonstrations of different parties.

/**
 * @author netman
 */

import java.io._
import scala._
import scala.Array._
import java.util.ArrayList
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  class InputReader(reader: BufferedReader) {

    var tokenizer: StringTokenizer = null;

    def this(stream: InputStream) = {
      this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));
    }

    def this(f: File) = {
      this(new BufferedReader(new FileReader(f), (1 << 20)));
    }

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

    def nextInt(): Int = next().toInt

    def nextDouble(): Double = next().toDouble

    def close() = reader.close();
  }

  class OutputWriter(writer: PrintWriter) {
    def this(stream: OutputStream) {
      this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));
    }

    def this(f: File) = {
      this(new PrintWriter(new BufferedWriter(new FileWriter(f))));
    }

    def print(x: Any) = writer.print(x);

    def println(x: Any) = writer.println(x);

    def close() = writer.close();
  }

  val in = new InputReader(System.in)
  val out = new OutputWriter(System.out)

  val WHITE = 0
  val BLACK = 1

  class DP {
    var dp = ofDim[Short](2, 0)
    def addUpEdge = {
      val res = initDP(dp(0).length, 0)
      for (cnt <- 0 until dp(0).length) {
        res.dp(0)(cnt) = math.min(dp(0)(cnt), dp(1)(cnt) + 1).toShort
        res.dp(1)(cnt) = math.min(dp(0)(cnt) + 1, dp(1)(cnt)).toShort
      }
      res
    }
  }

  def initDP(n: Int, value: Short): DP = {
    val res = new DP
    res.dp = Array.fill[Short](2, n)(value)
    res
  }

  def combineArrays(a: Array[Short], b: Array[Short]): Array[Short] = {
    if (a.length == 0) return b
    if (b.length == 0) return a
    val c = Array.fill[Short](a.length + b.length - 1)((Short.MaxValue / 2).toShort)
    for (i <- 0 until a.length) {
      for (j <- 0 until b.length) {
        if (a(i) + b(j) < c(i + j)) c(i + j) = (a(i) + b(j)).toShort
      }
    }
    c
  }

  def combineDP(a: DP, b: DP): DP = {
    val res = new DP
    res.dp(0) = combineArrays(a.dp(0), b.dp(0))
    res.dp(1) = combineArrays(a.dp(1), b.dp(1))
    res
  }

  var n = 0
  var g: Array[ArrayBuffer[Int]] = null

  def dfs(v: Int, p: Int): DP = {
    if (g(v).length == 1) {
      val res = initDP(2, 0)
      res.dp(0)(0) = Short.MaxValue / 2
      res.dp(1)(1) = Short.MaxValue / 2
      return res
    }
    var res = new DP
    for (to <- g(v)) {
      if (to != p) {
        res = combineDP(res, dfs(to, v).addUpEdge)
      }
    }
    return res
  }

  def main(args: Array[String]): Unit = {
    n = in.nextInt

    g = Array.fill[ArrayBuffer[Int]](n + 1)(new ArrayBuffer[Int])

    for (i <- 1 to n - 1) {
      val (x, y) = (in.nextInt, in.nextInt)
      g(x) += y
      g(y) += x
    }

    var root = 1
    var cntLeafs = 0

    for (i <- 1 to n) {
      if (g(i).length != 1) root = i
      else cntLeafs += 1
    }

    val z = dfs(root, -1)

    val res = math.min(z.dp(0)(cntLeafs / 2).toInt, z.dp(1)(cntLeafs / 2).toInt)

    out.println(res)

    out.close
  }
}


Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.

The only line contains three integers b, d and s (0 ≤ b, d, s ≤ 1018,  b + d + s ≥ 1) — the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium.

Print single integer — the minimum possible number of meals which Vasiliy could have missed during his vacation.

NoteIn the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival) and then have left after breakfast on the third day. In the second sample, Vasiliy could have arrived before breakfast, have had it, and immediately have left the sanatorium, not missing any meal.In the third sample, Vasiliy could have been in the sanatorium for one day, not missing any meal.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val visits = in.next().split(' ').map(_.toLong)
  val max = visits.max
  val maxCount = visits.count(_ == max)
  if (maxCount == 3)
    println(0)
  else if (maxCount == 2)
    println(max - visits.min  - 1)
  else
    println(max + max - visits.filter(_ != max).sum - 2)

}

import java.io._
import scala.io.Source

import scala.annotation.tailrec

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val line = lines.next()
    val strings = line.split(" ")
    val b = strings(0).toLong
    val d = strings(1).toLong
    val s = strings(2).toLong
    val soln = solve(b, d, s)
    bw.write(soln.toString)
    bw.newLine()
  }

  def solve(b: Long, d: Long, s: Long): Long = {
    // rebase time, so that at least as many of first meal as any other, and call that breakfast...
    if (d > b && d >= s) solve(d, s, b)  // Measure from before dinner on the first day
    else if (s > d && s >= b) solve(s, b, d)  // Measure from before supper on the first day
    else math.max(b - d - 1, 0) + math.max(b - s - 1, 0)
        // don't count last dinner and/or supper as missed, but beware that b, d and s could be equal
  }
}

object C732 {

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

  def main(args: Array[String]): Unit = {
    val in = readLongs(3).sorted.reverse
    if(in.max - in.min <= 1) {
      println("0")
    } else {
      for(i <- in.indices)
        if(in(i) != in.max)
          in(i) += 1
      println(in.map(a => in.max-a).sum)
    }
  }

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

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

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

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

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

}

object source{
  def main(args: Array[String]): Unit = {
    val in = io.Source.stdin.getLines()
    val visits = in.next().split(' ').map(_.toLong)
    val max = visits.max
    val maxCnt = visits.count(_ == max)
    if (maxCnt == 3) println(0)
    else if (maxCnt == 2)
      println(max - visits.min  - 1)
    else
      println(max + max - visits.filter(_ != max).sum - 2)
  }
}

import java.io._
import scala.io.Source

import scala.annotation.tailrec

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val line = lines.next()
    val strings = line.split(" ")
    val b = strings(0).toLong
    val d = strings(1).toLong
    val s = strings(2).toLong
    val soln = solve(b, s, d)
    bw.write(soln.toString)
    bw.newLine()
  }

  def solve(b: Long, d: Long, s: Long): Long = {
    // rebase time, so that at least as many of first meal as any other, and call that breakfast...
    if (d > b && d >= s) solve(d, s, b)  // Measure from before dinner on the first day
    else if (s > d && s > b) solve(s, b, d)  // Measure from before supper on the first day
    else {
      if (s == b) b - d  // Stay for full last day
      else math.max(b - d - 1, 0) + b - s - 1
        // don't count last dinner and supper as missed, but beware that d could equal b
    }
  }
}

import java.io._
import scala.io.Source

import scala.annotation.tailrec

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val line = lines.next()
    val strings = line.split(" ")
    val b = strings(0).toLong
    val d = strings(1).toLong
    val s = strings(2).toLong
    val soln = solve(b, d, s)
    bw.write(soln.toString)
    bw.newLine()
  }

  def solve(b: Long, d: Long, s: Long): Long = {
    // rebase time, so that at least as many of first meal as any other, and call that breakfast...
    if (d > b && d >= s) solve(d, s, b)  // Measure from before dinner on the first day
    else if (s > d && s > b) solve(s, b, d)  // Measure from before supper on the first day
    else {
      if (s == b) b - d  // Stay for full last day
      else math.max(b - d - 1, 0) + b - s - 1
        // don't count last dinner and supper as missed, but beware that d could equal b
    }
  }
}

object C732 {

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

  def main(args: Array[String]): Unit = {
    val in = readLongs(3).sorted.reverse
    in(0) -= in(2) + 1
    in(1) -= in(2) + 1
    in(2) = 0
    val res = math.max(0, in(0) - (if(in(1) > 0) in(0)-in(1) else 0))
    println(res)
  }

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

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

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

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

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

}

object C732 {

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

  def main(args: Array[String]): Unit = {
    val in = readLongs(3)
    val res = math.max(0, in.max - in.min - 1)
    println(res)
  }

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

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

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

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

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

}

object C732 {

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

  def main(args: Array[String]): Unit = {
    var in = readLongs(3).sorted
    in(2) -= in(0)
    in(1) -= in(0)
    val res = math.max(0, 2*in(2) - in(1) - in(0) - (if(in(1) == 0)2 else 1))
    println(res)
  }

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

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

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

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

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

}