Little Dormi received a histogram with $$$n$$$ bars of height $$$a_1, a_2, \ldots, a_n$$$ for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.To modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times: Select an index $$$i$$$ ($$$1 \le i \le n$$$) where $$$a_i>0$$$, and assign $$$a_i := a_i-1$$$.Little Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.However, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.Consider the following example where the histogram has $$$4$$$ columns of heights $$$4,8,9,6$$$:  The blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is $$$4+4+1+3+6 = 18$$$, so if Little Dormi does not modify the histogram at all, the ugliness would be $$$18$$$.However, Little Dormi can apply the operation once on column $$$2$$$ and twice on column $$$3$$$, resulting in a histogram with heights $$$4,7,7,6$$$:  Now, as the total vertical length of the outline (red lines) is $$$4+3+1+6=14$$$, the ugliness is $$$14+3=17$$$ dollars. It can be proven that this is optimal.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 4 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case output one integer, the minimal ugliness Little Dormi can achieve with the histogram in that test case.

NoteExample $$$1$$$ is the example described in the statement.The initial histogram for example $$$2$$$ is given below:  The ugliness is currently $$$2+1+6+3+4=16$$$.By applying the operation once on column $$$1$$$, six times on column $$$3$$$, and three times on column $$$4$$$, we can end up with a histogram with heights $$$1,1,1,1,0,0$$$:  The vertical length of the outline is now $$$1+1=2$$$ and Little Dormi made $$$1+6+3=10$$$ operations, so the final ugliness is $$$2+10=12$$$, which can be proven to be optimal.

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

  val t = readInt()

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

    def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)

    val ans = (0 to n)
      .foldLeft((0L, 0)) {
        case ((s, _), i) if ai(i) > ai(i - 1) && ai(i) > ai(i + 1) =>
          val h = ai(i - 1) max ai(i + 1)
          val l = h - ai(i - 1)
          (s + ai(i) - h + l, h)
        case ((s, aj), i)                                          =>
          (s + Math.abs(ai(i) - aj), ai(i))
      }
      ._1

    println(ans)
  }
}

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

  val t = readInt()

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

    def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)

    val ans = (0 to n)
      .foldLeft((0L, 0)) {
        case ((s, _), i) if an(i) > ai(i - 1) && an(i) > ai(i + 1) =>
          val h = ai(i - 1) max ai(i + 1)
          val l = h - ai(i - 1)
          (s + an(i) - h + l, h)
        case ((s, aj), i)                                          =>
          val ai = an(i)
          (s + Math.abs(ai - aj), ai)
      }
      ._1

    println(ans)
  }
}

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

  val t = readInt()

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

    def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)

    val ans = {
      val (a, b) = (0 until n).foldLeft((0L, 0)) {
        case ((s, _), i) if an(i) > ai(i - 1) && an(i) > ai(i + 1) =>
          val h = ai(i - 1) max ai(i + 1)
          val l = h - ai(i - 1)
          (s + an(i) - h + l, h)
        case ((s, aj), i)                                          =>
          val ai = an(i)
          (s + Math.abs(ai - aj), ai)
      }

      a + b
    }

    println(ans)
  }
}

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

  val t = readInt()

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

    def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)

    val ans = (0 until n)
      .foldLeft((0L, 0)) {
        case ((s, _), i) if an(i) > ai(i - 1) && an(i) > ai(i + 1) =>
          val h = ai(i - 1) max ai(i + 1)
          val l = h - ai(i - 1)
          (s + an(i) - h + l, h)
        case ((s, aj), i)                                          =>
          val ai = an(i)
          (s + Math.abs(ai - aj), ai)
      }
      ._1

    println(ans)
  }
}

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

  val t = readInt()

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

    def ai(i: Int): Int = if (i < 0 || i > n - 1) 0 else an(i)

    val ans = {
      val (a, b) = (0 until n).foldLeft((0, 0)) {
        case ((s, _), i) if an(i) > ai(i - 1) && an(i) > ai(i + 1) =>
          val h = ai(i - 1) max ai(i + 1)
          val l = h - ai(i - 1)
          (s + an(i) - h + l, h)
        case ((s, aj), i)                                          =>
          val ai = an(i)
          (s + Math.abs(ai - aj), ai)
      }

      a + b
    }

    println(ans)
  }
}

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

  val t = readInt()

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

    def f(i: Int): Long =
      an.foldLeft((0L, 0)) { case ((acc, prev), curr) =>
        (acc + Math.abs(curr.min(i) - prev.min(i)) + 0.max(curr - i), curr)
      }._1

    @annotation.tailrec
    def go(i: Int, result: Long): Long =
      if (i < 0) result
      else go(i - 1, result min f(i))

    val ans = go(an.max - 1, f(an.max))

    println(ans)
  }
}

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

  val t = readInt()

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

    def f(i: Int): Long =
      an.foldLeft((0L, 0)) { case ((acc, prev), curr) =>
        val diff = curr.min(i) - prev.min(i)
        (acc + diff * diff.signum + (curr - i).max(0), curr)
      }._1

    def go(i: Int, result: Long): Long =
      if (i < 0) result
      else {
        val t = f(i)
        if (t > result) result
        else go(i - 1, t)
      }

    val ans = go(an.max - 1, f(an.max))

    println(ans)
  }
}


Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.

The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai — integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.

Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10 - 6.

import java.util.Scanner
object Zhlob {

  class Point(_x:Int, _y:Int){
    def x = _x
    def y = _y
    def len(p:Point):Double = {
      Math.sqrt(0.0+(x - p.x)*(x - p.x) + (y-p.y)*(y-p.y))
    }
  }

  val scanner = new Scanner(System.in);

  def main(args: Array[String]) {
    val n,k = scanner.nextInt()
    val points = (1 to n) map {i => new Point(scanner.nextInt(), scanner.nextInt())}
    var sum = 0.0
    for (i <- 1 until n){
      sum += points(i).len(points(i-1))
    }
    println("%.9f".format(sum/50*k))

  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  def dis(x: Int, y: Int, x1: Int, y1: Int) = {
    val dx = x1 - x
    val dy = y1 - y
    Math.sqrt(dx * dx + dy * dy)
  }
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val Array(startX, startY) = in.next().split(' ').map(_.toInt)
  val distance = (2 to n).foldLeft((0d, startX, startY)){
    case ((d, x, y), _) =>
      val Array(nx, ny) = in.next().split(' ').map(_.toInt)
      (d + dis(x, y, nx, ny), nx, ny)
  }._1
  println(distance / 50 * k)
}

import scala.math
object Main
{
	def ro(x1:Int, y1:Int, x2:Int, y2:Int):Double =
	{
		return math.pow(math.pow(x2-x1, 2) + math.pow(y2-y1, 2), 0.5)
	}
	def main(args:Array[String])
	{
		val rd = readLine.split(" ").map(i => i.toInt)
		val k = rd(1)
		val n = rd(0)
		val crd = (0 until n).map(i => readLine.split(" ").map(j => j.toInt)).toList;
		println((1 until crd.length).map(i => ro(crd(i - 1)(0), crd(i - 1)(1), crd(i)(0), crd(i)(1))).sum / 50 * k)
	}
}

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

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

  val N, K = sc.nextInt
  val a = Array.fill(N, 2)(sc.nextInt)

  def solve: Double = {
    @tailrec
    def loop(acc: Double, i: Int): Double =
      if (i == N) acc
      else {
        val x0 = a(i - 1)(0)
        val y0 = a(i - 1)(1)
        val x1 = a(i)(0)
        val y1 = a(i)(1)
        val dx = x0 - x1
        val dy = y0 - y1
        loop(acc + math.sqrt(dx * dx + dy * dy), i + 1)
      }
    loop(0, 1) * K / 50
  }

  out.println(solve)
  out.close
}

/**
 * @author pvasilyev
 * @since 08 Aug 2016
 */
object A127 extends App {

  def solve() = {
    val Array(n, k): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var x: Double = 0D
    var y: Double = 0D
    var signCost: Double = 0D
    for (i <- 0 until n) {
      val Array(nextX, nextY): Array[Double] = scala.io.StdIn.readLine().split(" ").map(_.toDouble)
      if (i != 0) {
        signCost += math.sqrt((x - nextX) * (x - nextX) + (y - nextY) * (y - nextY))
      }
      x = nextX
      y = nextY
    }
    println("%.9f".format(signCost * k / 50))
  }

  solve()

}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  type Point = Array[Int]
  class PointWrapper(p: Point) {
    def ×(o: Point) = (p zip o).map(x => x._1 * x._2).sum
    def -(o: Point) = (p zip o).map(x => x._1 - x._2)
    def len = Math.sqrt(×(p))
  }
  implicit def p2pw(p: Point) = new PointWrapper(p)
  val Array(n, k) = readInts
  val points = for(_ <- 1 to n) yield readInts
  val p1 = points.take(1) ++ points
  val p2 = points ++ points.drop(n - 1)
  def ans = (p1 zip p2).map(x => (x._1 - x._2).len).sum * 0.02 * k

  def main(a: Array[String]) {
    println("%.10f".formatLocal(Locale.US, ans))
  }
}

object Main {
  def readxy(): (Float, Float) = {
    val a = readLine().split(" ").map(_.toFloat)
    (a(0), a(1))
  }

  def main(args: Array[String]) {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(1)

    var prev = readxy()
    var length = 0.0f
    for (_ <- 1 until n) {
      val cur = readxy()
      val v = (cur._1 - prev._1, cur._2 - prev._2)
      length += Math.sqrt(v._1 * v._1 + v._2 * v._2).toFloat
      prev = cur
    }
    println(length * k / 50.0f)
  }
}


You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.It is guaranteed that you have to color each vertex in a color different from 0.You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).

The first line contains a single integer n (2 ≤ n ≤ 104) — the number of vertices in the tree. The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi means that there is an edge between vertices i and pi. The third line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ n), where ci is the color you should color the i-th vertex into. It is guaranteed that the given graph is a tree.

Print a single integer — the minimum number of steps you have to perform to color the tree into given colors.

NoteThe tree from the first sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):On seond step we color all vertices in the subtree of vertex 5 into color 1:On third step we color all vertices in the subtree of vertex 2 into color 1:The tree from the second sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):On second step we color all vertices in the subtree of vertex 3 into color 1:On third step we color all vertices in the subtree of vertex 6 into color 2:On fourth step we color all vertices in the subtree of vertex 4 into color 1:On fith step we color all vertices in the subtree of vertex 7 into color 3:

import java.util

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

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val adjacency = readIntLine().map(_ - 1)

    val adj = Array.fill(n){List() : List[Int]}
    for ((a, i) <- adjacency.zipWithIndex) {
      adj(i + 1) ::= a
      adj(a) ::= i + 1
    }

    val colors = readIntLine()
    println(color(List((0, 0)), colors, adj, Array.fill(n){false}, 0))
  }

  def color(queue: List[(Int, Int)], colors : Array[Int], adj : IndexedSeq[List[Int]], visited : Array[Boolean], cost : Int): Int = {
    queue match {
      case Nil => cost
      case first :: rest =>
        val node = first._1
        var newCost = cost
        visited(node) = true
        if (first._2 != colors(node)) {
          newCost = cost + 1
        }
        if (node < adj.length - 1) {
          val children = adj(node).map(c => (c, colors(node))).filterNot(p => visited(p._1))
          color(children ::: rest, colors, adj, visited, newCost)
        } else {
          color(rest, colors, adj, visited, newCost)
        }
    }
  }

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

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

}

import scala.annotation.tailrec
import scala.collection.mutable

object B extends App {
  def color(g: mutable.HashMap[Int, List[Int]]): Int = {
    @tailrec
    def dfs(h: List[(Int, Int, List[Int])], t: Int = 1): Int = {
      if (h.isEmpty) t
      else {
        val (p, u, adj) = h.head
        if (adj.isEmpty) dfs(h.tail, if (c(p - 1) == c(u - 1)) t else t + 1)
        else {
          val v = adj.head
          if (v == p) dfs((p, u, adj.tail) :: h.tail, t)
          else dfs((u, v, g(v)) :: (p, u, adj.tail) :: h.tail, t)
        }
      }
    }

    dfs(List((2, 2, g(2))))
  }

  val n = scala.io.StdIn.readInt()
  val p = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val c = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val g = p.foldLeft((new mutable.HashMap[Int, List[Int]], 2)) { (t, u) => {
    t._1(t._2) = u :: t._1.getOrElse(t._2, Nil)
    t._1(u) = t._2 :: t._1.getOrElse(u, Nil)
    (t._1, t._2 + 1)
  }}._1

  println(color(g))
}

/**
  * @see http://codeforces.com/contest/902/problem/B
  */

import scala.annotation.tailrec

object B extends App {
  def coloring(g: Vector[List[Int]], cs: Array[Int]): Int = {
    @tailrec
    def dfs(h: List[(Int, Int, List[Int])], t: Int): Int =
      if (h.isEmpty) t
      else {
        val (p, u, adj) = h.head
        if (adj.isEmpty) dfs(h.tail, if (cs(p) == cs(u)) t else t + 1)
        else {
          val v = adj.head
          if (v == p) dfs((p, u, adj.tail) :: h.tail, t)
          else dfs((u, v, g(v)) :: (p, u, adj.tail) :: h.tail, t)
        }
      }

    dfs(List((0, 0, g(0))), 1)
  }

  val n = scala.io.StdIn.readInt()
  val ps = scala.io.StdIn.readLine().split(" ").map(_.toInt - 1)
  val cs = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val g = ps.indices.foldLeft(Vector.fill(n)(List.empty[Int])) ((g, i) => {
    val u = i + 1
    val v = ps(i)
    g.updated(u, v :: g(u)).updated(v, u :: g(v))
  })

  val t = coloring(g, cs)
  println(t)
}

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]

    val edges = io.read[Seq, Int](n-1)
      .zipWithIndex
      .map({case (i, j) => i -> (j+2)})
      .flatMap({edge => Set(edge, edge.swap)})
      .toMultiMap
      .withDefaultValue(Vector.empty)

    val expectedColor = io.read[Vector, Int](n)

    val visited = mutable.Set.empty[Int]

    def solve(u: Int, color: Int): Int = {
      visited += u
      (if (color == expectedColor(u-1)) 0 else 1) + edges(u).filterNot(visited).sumWith(v => solve(v, expectedColor(u-1)))
    }

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn

object Main extends App {
  val n = StdIn.readInt()
  val g = ints.iterator.zip(Iterator.from(1)).foldLeft(Array.fill(n){ scala.collection.mutable.ArrayBuffer.empty[Int] }){ (g, p) =>
    g(p._1 - 1).append(p._2)
    g(p._2).append(p._1 - 1)
    g
  }
  val cs = ints

  print(dfs(g) { (u: Int, vs: Iterable[(Int, Int) => Int]) => (c: Int, s: Int) => {
    val cu = cs(u)
    vs.foldLeft(s + (if (cu != c) 1 else 0)){ (s1, f) => f(cu, s1) }
  }}(0, 0))

  def ints = StdIn.readLine().split(' ').map(_.toInt)

  def dfs[B](g: IndexedSeq[Iterable[Int]])(f: (Int, Iterable[B]) => B): B = {
    def go(p: Int)(u: Int): B = f(u, g(u).filter(_ != p).map(go(u)))
    go(0)(0)
  }
}

import scala.collection.mutable.ListBuffer

object Main extends App {
  import scala.io.StdIn

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

  def readInt: Int = StdIn.readLine.toInt

  val n = readInt

  val children = Array.fill(n + 1)(ListBuffer[Int]())

  for ((p, i1) <- readInts.zipWithIndex; i = i1 + 2)
    children(p) += i

  val c = Array(0) ++ readInts

  def f(v: Int, color: Int): Int =
    (if (color == c(v)) 0 else 1) + children(v).map(u => f(u, c(v))).sum

  println(f(1, 0))
}


Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.

The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.

If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes).

10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer

10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever

7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck

bcdefghijklmnopqrsatuvwxyz Impossible aghjlnopefikdmbcqrstuvwxyz acbdefhijklmnogpqrstuvwxyz

/**
 * Created by helfper on 02/02/2015.
 */
import scala.collection.mutable._

object FoxAndNames {
  def main(args: Array[String]) {
    val n = io.StdIn.readInt
    val strs = List.range(0, n).map(i => io.StdIn.readLine)

    solve(strs)
  }

  def solve(strs: List[String]): Unit = {
    val inEdges = Map.empty[Char, List[Char]].withDefaultValue(Nil)
    val outEdges = Map.empty[Char, List[Char]].withDefaultValue(Nil)

    def iterate(s1: String, s2: String): Boolean = {
      val idx = s1.zipAll(s2, '.', '.').indexWhere{case (c1, c2) => c1 != c2}

      if (idx == -1 || idx >= s1.length) true
      else if (idx >= s2.length) false
      else {
        val c1 = s1(idx)
        val c2 = s2(idx)
        inEdges.update(c2, c1 :: inEdges(c2))
        outEdges.update(c1, c2 :: outEdges(c1))
        true
      }
    }

    strs.init.zip(strs.tail).foreach { case (s1, s2) =>
      if(!iterate(s1, s2)) {
        println("Impossible")
        return
      }
    }

    var set = 'a'.to('z').filter(c => inEdges(c).isEmpty).toSet
    var list = List.empty[Char]
    while (!set.isEmpty) {
      val n = set.head
      set -= n
      list = n :: list
      outEdges(n).foreach { m =>
        inEdges.update(m, inEdges(m).filter(_ != n))
        if (inEdges(m).isEmpty) {
          set += m
        }
      }
    }
    if (inEdges.exists{case (c, l) => l.nonEmpty}) {
      println("Impossible")
      return
    }
    println(list.reverse.mkString)
  }
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val names = Array.fill(n) { (readLine + '{').toCharArray }
  val precBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }

  var err = false

  for {
    i <- 0 until n
    n1 = names(i)
    j <- i + 1 until n
    n2 = names(j)
  } {
    var equal = true
    var p = 0
    val l = n1.length min n2.length
    while (equal & p < l) {
      if (n2(p) == '{') err = true
      if (n1(p) != n2(p)) {
        precBuilders(n2(p)) += n1(p)
        equal = false
      }
      p += 1
    }
  }

  val preceeding = precBuilders.map(_.result.distinct)

  val sorted = mutable.ArrayBuffer.empty[Int]

  val color = Array.fill('{'.toInt + 1)(0)

  def dfs(u: Int): Unit = {
    color(u) = 1
    for (v <- preceeding(u)) {
      if (color(v) == 0) dfs(v)
      else if (color(v) == 1) err = true
    }
    color(u) = 2
    sorted += u
  }

  for (i <- 'a'.toInt to '{'.toInt) if (color(i) == 0) dfs(i)

  println(if (err) "Impossible" else sorted.map(_.toChar).filter(_ != '{').mkString)

  Console.flush
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val names = Array.fill(n) { (readLine + '{').toCharArray }
  val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }
  val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)

  for {
    i <- 0 until n
    n1 = names(i)
    j <- i + 1 until n
    n2 = names(j)
  } {
    var equal = true
    var p = 0
    val l = n1.length min n2.length
    while (equal & p < l) {
      if (n1(p) != n2(p)) {
        adjBuilders(n1(p)) += n2(p)
        after(n1(p))(n2(p)) = true
        equal = false
      }
      p += 1
    }
  }

  for (c <- 'a' to 'z') after('{')(c) = true

  for (c <- 'a' to '{')
  for (a <- 'a' to '{') for (b <- 'a' to '{') if (after(a)(b) && after(b)(c)) after(a)(c) = true

  val adj = adjBuilders.map(_.result.distinct)

  val visited = new mutable.BitSet
  val stack = mutable.Stack.empty[Char]
  var err = false

  def dfs1(u: Char, root: Boolean = false): Unit = {
    //println(u)
    if (!visited(u)) {
      visited += u
      for (v <- adj(u)) {
        if (after(v)(u)) {
          err = true
        }
        dfs1(v)
      }
      stack.push(u)
    /*} else if (!root) {
     err = true*/
    }
  }

  for (i <- '{'.toInt to 'a'.toInt by -1) if (!visited(i)) dfs1(i.toChar, true)

  println(if (err) "Impossible" else stack.toArray.filter(_ != '{').mkString)

  Console.flush
}

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val names = Array.fill(readInt)(readString)
  val longest = names.maxBy(s => s.length).length
  val base = ('a' - 1).toChar

  case class Node(c: Char) extends Ordered[Node] {
    var before = mutable.Set[Node]()
    var after = mutable.Set[Node]()

    def compare(n: Node) = c - n.c
  }
  val nodes = for(i <- 0 to 26) yield Node((i + base).toChar)
  for(i <- 1 to 26) {
    nodes(i).after += nodes(0)
    nodes(0).before += nodes(i)
  }
  def addOrdering(strings: List[String]) {
    val chars = strings.map(s => s(0) - base)
    for(i <- 1 until chars.length; if chars(i-1) != chars(i)) {
      nodes(chars(i-1)).before += nodes(chars(i))
      nodes(chars(i)).after += nodes(chars(i-1))
    }
    val grouped = strings.groupBy(s => s(0)).map(x => x._2.map(s => s.drop(1)))
    for(group <- grouped; if group.size > 1)
      addOrdering(group)
  }
  addOrdering(names.toList.map(s => s.padTo(longest, base)))

  //for(node <- nodes)
  //  println(s"${node.c} -> ${node.before},${node.after}")

  val unusedNodes = mutable.TreeSet(nodes: _*)
  var str = ""
  while(!unusedNodes.isEmpty) unusedNodes.find(n => n.after.isEmpty) match {
    case Some(node) =>
      for(n <- node.before)
        n.after -= node
      unusedNodes -= node
      if(node.c != base)
        str += node.c
    case None =>
      println("Impossible")
      System.exit(0)
  }
  println(str)
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string.toString
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

import java.util.StringTokenizer

import scala.collection.mutable.Queue

object _510C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val m = 26
  val name = (1 to n).map(i => next).toArray
  val g = Array.fill(m, m)(false)
  var impossible = false

  def less(a: List[Char], b: List[Char]): Unit = (a, b) match {
    case (a, Nil) => impossible = true
    case (Nil, b) =>
    case (aa :: aTail, bb :: bTail) => if (aa != bb) g(aa - 'a')(bb - 'a') = true else less(aTail, bTail)
  }

  for (i <- 0 until n - 1) less(name(i).toList, name(i + 1).toList)
  if (impossible) println("Impossible")
  else {
    val inDegree = Array.fill(m)(0)
    for (i <- 0 until m; j <- 0 until m) if (g(i)(j)) inDegree(j) = inDegree(j) + 1
    val queue = Queue[Int]()
    for (i <- 0 until m) if (inDegree(i) == 0) queue.enqueue(i)

    val builder = new StringBuilder()
    while (!queue.isEmpty) {
      val u = queue.dequeue
      builder += (u + 'a').toChar

      for (v <- 0 until m)
        if (g(u)(v)) {
          inDegree(v) = inDegree(v) - 1
          if (inDegree(v) == 0) queue.enqueue(v)
        }
    }

    val ans = builder.result
    println(if (ans.length() == m) ans else "Impossible")
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().map(_ - 'a'))
  val nodes = Array.ofDim[Boolean](26, 26)

  def fill(start: Int, end: Int, letter: Int) {
    val indices = (start to end).filter(i => data(i).length > letter)
    if (indices.length > 1) {
      val letters = indices.map(i => data(i)(letter))
      letters.tail.foldLeft(letters.head) {
        case (prev, el) =>
          if (prev != el)
            nodes(el)(prev) = true
          el
      }
      val res = indices.tail.foldLeft(indices.head) {
        case(startSoFar, el) if data(startSoFar)(letter) == data(el)(letter) => startSoFar
        case(startSoFar, el) =>
          fill(startSoFar, el - 1, letter + 1)
          el
      }
      fill(res, indices.last, letter + 1)
    }
  }

  fill(0, n - 1, 0)
//  println(nodes.map(_.mkString("\t")).mkString("\n"))

  def isValid(marked: Array[Boolean], current: Int, start: Int): Boolean =
    if (marked(current)) true
    else {
      marked(current) = true
      nodes(current).indices.forall { i =>
        !nodes(current)(i) || (i != start && isValid(marked, i, start))}
    }

  val sol = (0 until 26).forall { i =>
    isValid(Array.ofDim[Boolean](26), i, i)
  }

  def parent(marked: Array[Int], i: Int): Int = {
    (0 until 26).find(j => nodes(i)(j) && marked(j) == -1).map(parent(marked, _)).getOrElse(i)
  }

  if (!sol)
    println("Impossible")
  else {
    val marked = Array.fill[Int](26)(-1)
    var number = 0
    val sol = (0 until 26).foreach { i =>
      while (marked(i) == -1) {
        marked(parent(marked, i)) = number
        number += 1
      }
    }
    val nString = marked.zip('a' to 'z').sortBy(_._1).map(_._2).mkString
    val r = data.map(_.map(i => (marked(i) + 'a').toChar).mkString)
//    println(r.mkString("\n"))
    if (r == r.sorted)
      println(nString)
    else
      println("Impossible")
  }

}

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

object C {

  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 java.lang.Long.parseLong(next)
  }

  def compare(s: String, t: String): (Int, Int) = {
    val len = Math.min(s.length, t.length)
    (0 until len).foreach(i => {
      val t1 = t.charAt(i)
      val s1 = s.charAt(i)
      if (s1 != t1) {
        return (t1 - 'a', s1 - 'a')
      }
    })
    if (t.length > s.length) {
      return (0, 0)
    }
    return (-1, -1)
  }

  def solve: Int = {
    val n = nextInt
    val names = new Array[String](n)
    (0 until n).foreach(names(_) = next)
    val len = 26
    val g = new Array[Array[Boolean]](27)
    (0 until len).foreach(g(_) = new Array[Boolean](len))
    (0 until n - 1).foreach(i => {
      val edge = compare(names(i), names(i + 1))
      if (edge ==(-1, -1)) {
        out.println("Impossible")
        return 1
      }
      if (edge !=(0, 0)) {
        g(edge._1)(edge._2) = true
      }
    })
    var flag = true
    val color = new Array[Int](len)
    val ans = new util.ArrayList[Int]()
    class Utils {
      def dfs(v: Int): Unit = {
        color(v) = 1
        (0 until len).foreach(i => {
          if (g(v)(i))
            if (color(i) == 0) {
              dfs(i)
            } else if (color(i) == 1) {
              flag = false
            }
        })
        color(v) = 2
        ans.add(v)
      }
    }
    val u = new Utils
    for (i <- 0 until len) {
      if (color(i) == 0) {
        u.dfs(i)
      }
    }
    if (!flag) {
      out.println("Impossible")
      return 1
    }
    (0 until ans.size()).foreach(i => out.print((ans.get(i) + 'a').toChar))
    return 1
  }

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

  import collection.mutable.Set
  import collection.mutable.Queue
  import scala.util.{Try, Success, Failure}

  def prefix(p: String, w1: String, w2: String): String = {
    if(w1 == "") p
    else if (w2 == "") p
    else {
     val c1 = w1.head
     val c2 = w2.head
     if(c1 == c2) prefix(p+c1.toString, w1.tail, w2.tail)
     else p
    }
  }

  def topological(r: Seq[(Char, Char)]): List[Char] = {
    val graph = r.groupBy(_._1).map({ case (g, v) => (g, v.map(_._2))}).toMap
    val order = Queue[Char]()
    val enter = Set(r.map(_._1): _*)
    val gray = Set[Char]()
    val black = Set[Char]()

    def dfs(node: Char): Unit = {
       enter.remove(node)
       gray.add(node)
       graph.getOrElse(node, List[Char]()) foreach { k =>
         if(gray.contains(k)) {
           throw new RuntimeException("cycle")
         }
         if(!black.contains(k)) dfs(k)
       }
       order.enqueue(node)
       gray.remove(node)
       black.add(node)
    }

    while(enter.size > 0) dfs(enter.head)
    order.toList.reverse
  }

  def rules(w1: String, w2: String): List[(Char, Char)] = {
    val p = prefix("", w1, w2)
    val ps = p.size
    if(w1.size == ps) {
      List()
    } else if (w2.size == ps) {
      println("Impossible")
      System.exit(0)
      List()
    } else {
      List(w1.drop(ps).head -> w2.drop(ps).head)
    }
  }

  val n = readInt
  val words = (1 to n) map { _ => readLine }
  val r = (words zip words.tail) flatMap { case (w1, w2) => rules(w1, w2)  }
  Try(topological(r)) match {
    case Failure(_) => println("Impossible")
    case Success(tr) => {
      println(tr.mkString + ("abcdefghijklmnopqrstuvwxyz".toSet.diff(tr.toSet)).mkString)
    }
  }
}

/**
 * Created by mros on 2015/3/29.
 */

import scala.io.StdIn
object Hi {
  var topo = Array.fill[List[Int]](26)(List[Int]())
  var count = Array.fill[Int](26)(0)
  def toInt(a: Char): Int = {
    a.toInt - 'a'.toInt
  }

  def mark(a: Char, b: Char): Unit = {
    val n = toInt(a)
    topo(n) = toInt(b) :: topo(n)
    count(toInt(b)) += 1
  }

  def printTopoSort(): Unit = {
    var visited = Array.fill[Boolean](26)(false)
    def select_one(): Char = {
      for (node <- 0 to 25) {
        if (!visited(node) && count(node) == 0) {
          for (nextNode <- topo(node)) {
            count(nextNode) -= 1
          }
          visited(node) = true
          return (node + 'a'.toInt).toChar
        }
      }
      return '#'
    }
    var ans = List[Char]()
    var OK = true
    for (_ <- 0 to 25) {
      val newone = select_one()
      if (newone == '#') {
        OK = false
      }
      else {
        ans = newone :: ans
      }
    }
    if (OK) {
      for (c <- ans.reverse) {
        print(c)
      }
    }
    else {
      println("Impossible")
    }
  }

  def whatChar(big: String, small: String): (Char, Char) = {
    val limit = math.min(big.length, small.length)
    def rec(i: Int): (Char, Char) = {
      if (i >= limit) { return ('#', '#') }
      if (big(i) != small(i)) { return (big(i), small(i)) }
      else { return rec(i + 1) }
    }
    return rec(0)
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val authors = new Array[String](n)
    for (i <- 0 to (n-1)) {
      authors(i) = StdIn.readLine()
      if (i > 0 && authors(i-1).startsWith(authors(i)) && authors(i-1).length > authors(i).length) {
        println("Impossible")
        return
      }
    }
    for (i <- 0 to (n - 2)) {
      whatChar(authors(i), authors(i + 1)) match {
        case ('#', '#') => ()
        case (a, b) => mark(a, b)
      }
    }
    printTopoSort()
  }
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val names = Array.fill(n) { (readLine + '{').toCharArray }
  val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }
  val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)

  for {
    i <- 0 until n
    n1 = names(i)
    j <- i + 1 until n
    n2 = names(j)
  } {
    var equal = true
    var p = 0
    val l = n1.length min n2.length
    while (equal & p < l) {
      if (n1(p) != n2(p)) {
        adjBuilders(n1(p)) += n2(p)
        after(n1(p))(n2(p)) = true
        equal = false
      }
      p += 1
    }
  }

  val adj = adjBuilders.map(_.result.distinct)

  val visited = new mutable.BitSet(n)
  val stack = mutable.Stack.empty[Char]
  var err = false

  def dfs1(u: Char): Unit = {
    if (!visited(u)) {
      visited += u
      for (v <- adj(u)) {
        if (after(v)(u)) {
          err = true
        }
        dfs1(v)
      }
      stack.push(u)
    }
  }

  for (i <- 'a' to '{') dfs1(i)

  println(if (err) "Impossible" else stack.toArray.filterNot(_ == '{').mkString)

  Console.flush
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val names = Array.fill(n) { (readLine + '{').toCharArray }
  val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }
  val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)

  for {
    i <- 0 until n
    n1 = names(i)
    j <- i + 1 until n
    n2 = names(j)
  } {
    var equal = true
    var p = 0
    val l = n1.length min n2.length
    while (equal & p < l) {
      if (n1(p) != n2(p)) {
        adjBuilders(n1(p)) += n2(p)
        after(n1(p))(n2(p)) = true
        equal = false
      }
      p += 1
    }
  }

  for (c <- 'a' to 'z') after('{')(c) = true

  val adj = adjBuilders.map(_.result.distinct)

  val visited = new mutable.BitSet
  val stack = mutable.Stack.empty[Char]
  var err = false

  def dfs1(u: Char): Unit = {
    if (!visited(u)) {
      visited += u
      for (v <- adj(u)) {
        if (after(v)(u)) {
          err = true
        }
        dfs1(v)
      }
      stack.push(u)
    }
  }

  for (i <- '{'.toInt to 'a'.toInt by -1) dfs1(i.toChar)

  println(if (err) "Impossible" else stack.toArray.filter(_ != '{').mkString)

  Console.flush
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val names = Array.fill(n) { (readLine + '{').toCharArray }
  val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }
  val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)

  for {
    i <- 0 until n
    n1 = names(i)
    j <- i + 1 until n
    n2 = names(j)
  } {
    var equal = true
    var p = 0
    val l = n1.length min n2.length
    while (equal & p < l) {
      if (n1(p) != n2(p)) {
        adjBuilders(n1(p)) += n2(p)
        after(n1(p))(n2(p)) = true
        equal = false
      }
      p += 1
    }
  }

  val adj = adjBuilders.map(_.result.distinct)

  val visited = new mutable.BitSet(n)
  val stack = mutable.Stack.empty[Char]
  var err = false

  def dfs1(u: Char): Unit = {
    if (!visited(u)) {
      visited += u
      for (v <- adj(u)) {
        if (after(v)(u)) {
          err = true
        }
        dfs1(v)
      }
      stack.push(u)
    }
  }

  for (i <- 'a' to '{') dfs1(i)

  println(if (err || stack.pop != '{') "Impossible" else stack.toArray.mkString)

  Console.flush
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val names = Array.fill(n) { (readLine + '{').toCharArray }
  val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }
  val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)

  for {
    i <- 0 until n
    n1 = names(i)
    j <- i + 1 until n
    n2 = names(j)
  } {
    var equal = true
    var p = 0
    val l = n1.length min n2.length
    while (equal & p < l) {
      if (n1(p) != n2(p)) {
        adjBuilders(n1(p)) += n2(p)
        after(n1(p))(n2(p)) = true
        equal = false
      }
      p += 1
    }
  }

  for (c <- 'a' to 'z') after('{')(c) = true

  val adj = adjBuilders.map(_.result.distinct)

  val visited = new mutable.BitSet(n)
  val stack = mutable.Stack.empty[Char]
  var err = false

  def dfs1(u: Char): Unit = {
    if (!visited(u)) {
      visited += u
      for (v <- adj(u)) {
        if (after(v)(u)) {
          err = true
        }
        dfs1(v)
      }
      stack.push(u)
    }
  }

  for (i <- 'a' to '{') dfs1(i)

  println(if (err || stack.pop != '{') "Impossible" else stack.toArray.mkString)

  Console.flush
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val names = Array.fill(n) { (readLine + '{').toCharArray }
  val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }
  val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)

  for {
    i <- 0 until n
    n1 = names(i)
    j <- i + 1 until n
    n2 = names(j)
  } {
    var equal = true
    var p = 0
    val l = n1.length min n2.length
    while (equal & p < l) {
      if (n1(p) != n2(p)) {
        adjBuilders(n1(p)) += n2(p)
        after(n1(p))(n2(p)) = true
        equal = false
      }
      p += 1
    }
  }

  for (c <- 'a' to 'z') after('{')(c) = true

  val adj = adjBuilders.map(_.result.distinct)

  val visited = new mutable.BitSet(n)
  val stack = mutable.Stack.empty[Char]
  var err = false

  def dfs1(u: Char): Unit = {
    if (!visited(u)) {
      visited += u
      for (v <- adj(u)) {
        if (after(v)(u)) {
          err = true
        }
        dfs1(v)
      }
      stack.push(u)
    }
  }

  for (i <- '{'.toInt to 'a'.toInt by -1) dfs1(i.toChar)

  println(if (err) "Impossible" else stack.toArray.filter(_ != '{').mkString)

  Console.flush
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val names = Array.fill(n) { (readLine + '{').toCharArray }
  val adjBuilders = Array.fill('{'.toInt + 1) { new mutable.ArrayBuilder.ofChar }
  val after = Array.fill('{'.toInt + 1, '{'.toInt + 1)(false)

  for {
    i <- 0 until n
    n1 = names(i)
    j <- i + 1 until n
    n2 = names(j)
  } {
    var equal = true
    var p = 0
    val l = n1.length min n2.length
    while (equal & p < l) {
      if (n1(p) != n2(p)) {
        adjBuilders(n1(p)) += n2(p)
        after(n1(p))(n2(p)) = true
        equal = false
      }
      p += 1
    }
  }

  for (c <- 'a' to 'z') after('{')(c) = true

  for (c <- 'a' to '{')
  for (a <- 'a' to '{') for (b <- 'a' to '{') if (after(a)(b) && after(b)(c)) after(a)(b) = true

  val adj = adjBuilders.map(_.result.distinct)

  val visited = new mutable.BitSet
  val stack = mutable.Stack.empty[Char]
  var err = false

  def dfs1(u: Char, root: Boolean = false): Unit = {
    //println(u)
    if (!visited(u)) {
      visited += u
      for (v <- adj(u)) {
        if (after(v)(u)) {
          err = true
        }
        dfs1(v)
      }
      stack.push(u)
    /*} else if (!root) {
     err = true*/
    }
  }

  for (i <- '{'.toInt to 'a'.toInt by -1) if (!visited(i)) dfs1(i.toChar, true)

  println(if (err) "Impossible" else stack.toArray.filter(_ != '{').mkString)

  Console.flush
}

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val names = Array.fill(readInt)(readString)
  val longest = names.maxBy(s => s.length).length

  case class Node(c: Char) extends Ordered[Node] {
    var before = mutable.Set[Node]()
    var after = mutable.Set[Node]()

    def compare(n: Node) = c - n.c
  }
  val nodes = for(i <- 0 until 26) yield Node((i + 'a').toChar)
  def addOrdering(strings: List[String]) {
    val chars = strings.map(s => s(0)-'a')
    for(i <- 1 until chars.length; if chars(i-1) != chars(i)) {
      nodes(chars(i-1)).before += nodes(chars(i))
      nodes(chars(i)).after += nodes(chars(i-1))
    }
    val grouped = strings.filter(s => s.length > 1).groupBy(s => s(0)).map(x => x._2.map(s => s.drop(1)))
    for(group <- grouped; if group.size > 1)
      addOrdering(group)
  }
  addOrdering(names.toList)

  //for(node <- nodes)
  //  println(s"${node.c} -> ${node.before},${node.after}")

  val unusedNodes = mutable.TreeSet(nodes: _*)
  var str = ""
  while(!unusedNodes.isEmpty) unusedNodes.find(n => n.after.isEmpty) match {
    case Some(node) =>
      for(n <- node.before)
        n.after -= node
      unusedNodes -= node
      str += node.c
    case None =>
      println("Impossible")
      System.exit(0)
  }
  println(str)
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string.toString
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val names = Array.fill(readInt)(readString)
  val longest = names.maxBy(s => s.length).length

  case class Node(c: Char) extends Ordered[Node] {
    var before = mutable.Set[Node]()
    var after = mutable.Set[Node]()

    def compare(n: Node) = c - n.c
  }
  val nodes = for(i <- 0 until 26) yield Node((i + 'a').toChar)
  def addOrdering(strings: List[String]) {
    val chars = strings.map(s => s(0)-'a')
    for(i <- 1 until chars.length; if chars(i-1) != chars(i)) {
      nodes(chars(i-1)).before += nodes(chars(i))
      nodes(chars(i)).after += nodes(chars(i-1))
    }
    val grouped = strings.groupBy(s => s(0)).map(x => x._2.drop(1))
    for(group <- grouped; if group.size > 1)
      addOrdering(group)
  }
  addOrdering(names.toList)

  //for(node <- nodes)
  //  println(s"${node.c} -> ${node.before},${node.after}")

  val unusedNodes = mutable.TreeSet(nodes: _*)
  var str = ""
  while(!unusedNodes.isEmpty) unusedNodes.find(n => n.after.isEmpty) match {
    case Some(node) =>
      for(n <- node.before)
        n.after -= node
      unusedNodes -= node
      str += node.c
    case None =>
      println("Impossible")
      System.exit(0)
  }
  println(str)
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string.toString
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().map(_ - 'a'))
  val nodes = Array.ofDim[Boolean](26, 26)

  def fill(start: Int, end: Int, letter: Int) {
    val indices = (start to end).filter(i => data(i).length > letter)
    if (indices.length > 1) {
      val letters = indices.map(i => data(i)(letter))
      letters.tail.foldLeft(letters.head) {
        case (prev, el) =>
          if (prev != el)
            nodes(el)(prev) = true
          el
      }
      val res = indices.tail.foldLeft(indices.head) {
        case(startSoFar, el) if data(startSoFar)(letter) == data(el)(letter) => startSoFar
        case(startSoFar, el) =>
          fill(startSoFar, el - 1, letter + 1)
          el
      }
      fill(res, indices.last, letter + 1)
    }
  }

  fill(0, n - 1, 0)
//  println(nodes.map(_.mkString("\t")).mkString("\n"))

  def isValid(marked: Array[Boolean], current: Int, start: Int): Boolean =
    if (marked(current)) true
    else {
      marked(current) = true
      nodes(current).indices.forall { i =>
        !nodes(current)(i) || (i != start && isValid(marked, i, start))}
    }

  val sol = (0 until 26).forall { i =>
    isValid(Array.ofDim[Boolean](26), i, i)
  }

  def parent(marked: Array[Int], i: Int): Int = {
    (0 until 26).find(j => nodes(i)(j) && marked(j) == -1).map(parent(marked, _)).getOrElse(i)
  }

  if (!sol)
    println("Impossible")
  else {
    val marked = Array.fill[Int](26)(-1)
    var number = 0
    val sol = (0 until 26).foreach { i =>
      while (marked(i) == -1) {
        marked(parent(marked, i)) = number
        number += 1
      }
    }
    println(marked.zip('a' to 'z').sortBy(_._1).map(_._2).mkString)
  }

}

object Main extends App {

  import collection.mutable.Set
  import collection.mutable.Queue
  import scala.util.{Try, Success, Failure}

  def prefix(p: String, w1: String, w2: String): String = {
    if(w1 == "") p
    else if (w2 == "") p
    else {
     val c1 = w1.head
     val c2 = w2.head
     if(c1 == c2) prefix(p+c1.toString, w1.tail, w2.tail)
     else p
    }
  }

  def topological(r: Seq[(Char, Char)]): Queue[Char] = {
    val graph = r.groupBy(_._1).map({ case (g, v) => (g, v.map(_._2))}).toMap
    val order = Queue[Char]()
    val enter = Set(r.map(_._1): _*)
    val gray = Set[Char]()
    val black = Set[Char]()

    def dfs(node: Char): Unit = {
       enter.remove(node)
       gray.add(node)
       graph.getOrElse(node, List[Char]()) foreach { k =>
         if(gray.contains(k)) {
           throw new RuntimeException("cycle")
         }
         if(!black.contains(k)) dfs(k)
       }
       order.enqueue(node)
       gray.remove(node)
       black.add(node)
    }

    while(enter.size > 0) dfs(enter.head)
    order
  }

  def rules(w1: String, w2: String): List[(Char, Char)] = {
    val p = prefix("", w1, w2)
    val ps = p.size
    if(w1.size == ps) {
      List()
    } else if (w2.size == ps) {
      println("Impossible")
      System.exit(0)
      List()
    } else {
      List(w1.drop(ps).head -> w2.drop(ps).head)
    }
  }

  val n = readInt
  val words = (1 to n) map { _ => readLine }
  val r = (words zip words.tail) flatMap { case (w1, w2) => rules(w1, w2)  }
  Try(topological(r)) match {
    case Failure(_) => println("Impossible")
    case Success(tr) => {
      println(tr.mkString + ("abcdefghijklmnopqrstuvwxyz".toSet - tr.toSet).mkString)
    }
  }
}

object Main extends App {

  import collection.mutable.Set
  import collection.mutable.Queue
  import scala.util.{Try, Success, Failure}

  def prefix(p: String, w1: String, w2: String): String = {
    if(w1 == "") p
    else if (w2 == "") p
    else {
     val c1 = w1.head
     val c2 = w2.head
     if(c1 == c2) prefix(p+c1.toString, w1.tail, w2.tail)
     else p
    }
  }

  def topological(r: Seq[(Char, Char)]): Queue[Char] = {
    val graph = r.groupBy(_._1).map({ case (g, v) => (g, v.map(_._2))}).toMap
    val order = Queue[Char]()
    val enter = Set(r.map(_._1): _*)
    val gray = Set[Char]()
    val black = Set[Char]()

    def dfs(node: Char): Unit = {
       enter.remove(node)
       gray.add(node)
       graph.getOrElse(node, List[Char]()) foreach { k =>
         if(gray.contains(k)) {
           throw new RuntimeException("cycle")
         }
         if(!black.contains(k)) dfs(k)
       }
       order.enqueue(node)
       gray.remove(node)
       black.add(node)
    }

    while(enter.size > 0) dfs(enter.head)
    order
  }

  def rules(w1: String, w2: String): List[(Char, Char)] = {
    val p = prefix("", w1, w2)
    val ps = p.size
    if(w1.size == ps) {
      List()
    } else if (w2.size == ps) {
      println("Impossible")
      System.exit(0)
      List()
    } else {
      List(w1.drop(ps).head -> w2.drop(ps).head)
    }
  }

  val n = readInt
  val words = (1 to n) map { _ => readLine }
  val r = (words zip words.tail) flatMap { case (w1, w2) => rules(w1, w2)  }
  Try(topological(r)) match {
    case Failure(_) => println("Impossible")
    case Success(tr) => {
      println(tr.mkString + ("abcdefghijklmnopqrstuvwxyz".toSet.diff(tr.toSet)).mkString)
    }
  }
}

/**
 * Created by mros on 2015/3/29.
 */

import scala.io.StdIn
object Hi {
  var topo = Array.fill[List[Int]](26)(List[Int]())
  var count = Array.fill[Int](26)(0)
  def toInt(a: Char): Int = {
    a.toInt - 'a'.toInt
  }

  def mark(a: Char, b: Char): Unit = {
    val n = toInt(a)
    topo(n) = toInt(b) :: topo(n)
    count(toInt(b)) += 1
  }

  def printTopoSort(): Unit = {
    var visited = Array.fill[Boolean](26)(false)
    def select_one(): Char = {
      for (node <- 0 to 25) {
        if (!visited(node) && count(node) == 0) {
          for (nextNode <- topo(node)) {
            count(nextNode) -= 1
          }
          visited(node) = true
          return (node + 'a'.toInt).toChar
        }
      }
      return '#'
    }
    var ans = List[Char]()
    var OK = true
    for (_ <- 0 to 25) {
      val newone = select_one()
      if (newone == '#') {
        OK = false
      }
      else {
        ans = newone :: ans
      }
    }
    if (OK) {
      for (c <- ans.reverse) {
        print(c)
      }
    }
    else {
      println("Impossible")
    }
  }

  def whatChar(big: String, small: String): (Char, Char) = {
    val limit = math.min(big.length, small.length)
    def rec(i: Int): (Char, Char) = {
      if (i >= limit) { return ('#', '#') }
      if (big(i) != small(i)) { return (big(i), small(i)) }
      else { return rec(i + 1) }
    }
    return rec(0)
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val authors = new Array[String](n)
    for (i <- 0 to (n-1)) {
      authors(i) = StdIn.readLine()
    }
    for (i <- 0 to (n - 2)) {
      whatChar(authors(i), authors(i + 1)) match {
        case ('#', '#') => ()
        case (a, b) => mark(a, b)
      }
    }
    printTopoSort()
  }
}


You are given a binary string of length $$$n$$$ (i. e. a string consisting of $$$n$$$ characters '0' and '1').In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than $$$k$$$ moves? It is possible that you do not perform any moves at all.Note that you can swap the same pair of adjacent characters with indices $$$i$$$ and $$$i+1$$$ arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6, 1 \le k \le n^2$$$) — the length of the string and the number of moves you can perform. The second line of the test case contains one string consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).

For each test case, print the answer on it: the lexicographically minimum possible string of length $$$n$$$ you can obtain from the given one if you can perform no more than $$$k$$$ moves.

NoteIn the first example, you can change the string as follows: $$$1\underline{10}11010 \rightarrow \underline{10}111010 \rightarrow 0111\underline{10}10 \rightarrow 011\underline{10}110 \rightarrow 01\underline{10}1110 \rightarrow 01011110$$$. In the third example, there are enough operations to make the string sorted.

object D1256 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      var Array(_, k) = readLongs(2)
      val str = read.toCharArray
      var firstOne = str.indexWhere(_ == '1')
      var firstZeroAfter =
        if (firstOne != -1) str.indexWhere(_ == '0', firstOne) else -1
      while (k > 0 && firstOne != -1 && firstZeroAfter != -1) {
        if (k >= firstZeroAfter - firstOne) {
          str(firstOne) = '0'
          str(firstZeroAfter) = '1'
          k -= firstZeroAfter - firstOne
          if (k > 0) {
            firstOne = str.indexWhere(_ == '1', firstOne)
            firstZeroAfter =
              if (firstOne != -1) str.indexWhere(_ == '0', firstZeroAfter)
              else -1
          }
        } else {
          str(firstZeroAfter) = '1'
          str(firstZeroAfter - k.toInt) = '0'
          k = 0
        }
      }
      out.println(str.mkString)
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

  override def apply(io: IO): io.type = {
    // val q = io.read[Int]
    val q = io.read[Int]
    repeat(q) {
      val n = io.read[Int]
      var k = io.read[Long]
      var ones : Int = 0
      val str = io.read[String].toCharArray()
      for(i <- 0 until n) {
        if(str(i) == '0') {
          while(ones > k) {
            ones = ones - 1
          }
          str(i) = '1'
          str(i-ones) = '0'
          k -= ones
        } else {
          ones = ones + 1
        }
      }
      for(i <- 0 until n) {
        io.write(str(i))
      }
      io.writeLine()
    }
    io
  }
}
/****************************[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 = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

import java.util.Scanner

import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val sc = new Scanner(System.in)
  val q = sc.nextInt

  0 until q foreach { _ =>
    var (n, k) = (sc.nextInt, sc.nextLong)
    val bin = sc.next.map(_ - '0').toArray
    var cnt = 0
    bin.zipWithIndex.filter(_._1 == 0).foreach { case (_, i) =>
      val shift = min(i - cnt, k).toInt
      bin(i) = 1
      bin(i - shift) = 0
      k -= shift
      cnt += 1
    }
    println(bin.mkString)
  }
}


You are given an integer array $$$a_1, a_2, \dots, a_n$$$ and integer $$$k$$$.In one step you can   either choose some index $$$i$$$ and decrease $$$a_i$$$ by one (make $$$a_i = a_i - 1$$$);  or choose two indices $$$i$$$ and $$$j$$$ and set $$$a_i$$$ equal to $$$a_j$$$ (make $$$a_i = a_j$$$). What is the minimum number of steps you need to make the sum of array $$$\sum\limits_{i=1}^{n}{a_i} \le k$$$? (You are allowed to make values of array negative).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^{15}$$$) — the size of array $$$a$$$ and upper bound on its sum. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the minimum number of steps to make $$$\sum\limits_{i=1}^{n}{a_i} \le k$$$.

NoteIn the first test case, you should decrease $$$a_1$$$ $$$10$$$ times to get the sum lower or equal to $$$k = 10$$$.In the second test case, the sum of array $$$a$$$ is already less or equal to $$$69$$$, so you don't need to change it.In the third test case, you can, for example:   set $$$a_4 = a_3 = 1$$$;  decrease $$$a_4$$$ by one, and get $$$a_4 = 0$$$.  As a result, you'll get array $$$[1, 2, 1, 0, 1, 2, 1]$$$ with sum less or equal to $$$8$$$ in $$$1 + 1 = 2$$$ steps.In the fourth test case, you can, for example:   choose $$$a_7$$$ and decrease in by one $$$3$$$ times; you'll get $$$a_7 = -2$$$;  choose $$$4$$$ elements $$$a_6$$$, $$$a_8$$$, $$$a_9$$$ and $$$a_{10}$$$ and them equal to $$$a_7 = -2$$$.  As a result, you'll get array $$$[1, 2, 3, 1, 2, -2, -2, -2, -2, -2]$$$ with sum less or equal to $$$1$$$ in $$$3 + 4 = 7$$$ steps.

object C {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val _n, k = nextLong
      val n = _n.toInt
      val as = nextLongs(n).sorted.reverse
      val min = as.last
      val sum = as.sum

      var res = Math.max(0L, min - (k - (sum - min)))
      var prefixSum = 0L
//      if (sum <= k) {
//        res = 0
//      }
      if (n == 1) {
        res = min - k
      }

      for (i <- 0 until n - 1) {
        prefixSum += as(i)
        val numTouched = i + 2L
        val untouchedSum = sum - prefixSum - min
        val maxTouchedSum = k - untouchedSum
//        val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)
        var maxTouchedLevel = if (maxTouchedSum >= 0) maxTouchedSum / numTouched
        else if (maxTouchedSum % numTouched == 0) maxTouchedSum / numTouched
        else (maxTouchedSum - (numTouched - Math.abs(maxTouchedSum) % numTouched)) / numTouched
        if (maxTouchedLevel > min) {
          maxTouchedLevel = min
        }
        val steps = i + 1 + min - maxTouchedLevel
//        println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)
        if (steps < res) {
          res = steps
        }
      }
      if (res < 0) res = 0

      out.println(res)
    }

    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)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object C {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val _n, k = nextLong
      val n = _n.toInt
      val as = nextLongs(n).sorted.reverse
      val min = as.last
      val sum = as.sum

      var res = Math.max(0, min - (k - (sum - min)))
      var prefixSum = 0L
//      if (sum <= k) {
//        res = 0
//      }
      if (n == 1) {
        res = min - k
      }

      for (i <- 0 until n - 1) {
        prefixSum += as(i)
        val untouched = sum - prefixSum - min
        val maxTouched = k - untouched
//        val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)
        var maxLevel = if (maxTouched >= 0) maxTouched / (i + 2)
        else (maxTouched - ((i + 2) - Math.abs(maxTouched) % (i + 2))) / (i + 2)
        if (maxLevel > min) {
          maxLevel = min
        }
        val steps = i + 1 + min - maxLevel
//        println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)
        if (steps < res) {
          res = steps
        }
      }
      if (res < 0) res = 0

      out.println(res)
    }

    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)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object C {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val _n, k = nextLong
      val n = _n.toInt
      val as = nextLongs(n).sorted.reverse
      val min = as.last
      val sum = as.sum

      var res = Math.max(0, min - (k - (sum - min)))
      var prefixSum = 0L
//      if (sum <= k) {
//        res = 0
//      }
      if (n == 1) {
        res = min - k
      }

      for (i <- 0 until n - 1) {
        prefixSum += as(i)
        val untouched = sum - prefixSum - min
        val maxTouched = k - untouched
//        val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)
        var maxLevel = if (maxTouched >= 0) maxTouched / (i + 2)
        else (maxTouched - Math.abs(maxTouched) % (i + 2)) / (i + 2)
        if (maxLevel > min) {
          maxLevel = min
        }
        val steps = i + 1 + min - maxLevel
//        println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)
        if (steps < res) {
          res = steps
        }
      }
      if (res < 0) res = 0

      out.println(res)
    }

    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)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object C {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val _n, k = nextLong
      val n = _n.toInt
      val as = nextLongs(n).sorted.reverse
      val min = as.last
      val sum = as.sum

      var res = Long.MaxValue
      var prefixSum = 0L
      if (n == 1) {
        res = min - k
      }

      for (i <- 0 until n - 1) {
        prefixSum += as(i)
        val untouched = sum - prefixSum - min
        val maxTouched = k - untouched
//        val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)
        val maxLevel = if (maxTouched >= 0) maxTouched / (i + 2)
        else (maxTouched - Math.abs(maxTouched) % (i + 2)) / (i + 2)
        val steps = i + 1 + min - maxLevel
//        println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)
        if (steps < res) {
          res = steps
        }
      }
      if (res < 0) res = 0

      out.println(res)
    }

    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)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object C {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val _n, k = nextLong
      val n = _n.toInt
      val as = nextLongs(n).sorted.reverse
      val min = as.last
      val sum = as.sum

      var res = Long.MaxValue
      var prefixSum = 0L
      if (n == 1) {
        res = min - k
      }

      for (i <- 0 until n - 1) {
        prefixSum += as(i)
        val untouched = sum - prefixSum - min
        val maxTouched = k - untouched
        val maxLevel = Math.floor(maxTouched / (i + 2.0)).toLong //* math.signum(maxTouched)
        val steps = i + 1 + min - maxLevel
//        println(i, prefixSum, min, untouched, maxTouched, maxLevel, steps)
        if (steps < res) {
          res = steps
        }
      }
      if (res < 0) res = 0

      out.println(res)
    }

    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)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}