import scala.collection.mutable

object C extends App {

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

  case class Song(t: Long, b: Long)

  val Array(n, k) = readInts(2)
  val songs = Array.fill(n) {
    val Array(t, b) = readLongs(2)
    Song(t, b)
  }.sortBy(-_.b)

  var max = 0L
  val pq = new mutable.PriorityQueue[Song]()(Ordering.by(-_.t))
  var len = 0L

  for (song <- songs) {
    pq += song
    len += song.t
    if (pq.size > k) {
      val r = pq.dequeue()
      len -= r.t
    }
    val score = song.b * len
    if (score > max) max = score
  }

  println(max)
}

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

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

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N, K = ni()
    case class Song(t: Int, b: Int) extends Comparable[Song] {
      override def compareTo(o: Song): Int = Integer.compare(t, o.t) // PriorityQueueでtが低い順に抜けていって欲しい
    }

    val S = Array.ofDim[Song](N)
    REP(N) { i =>
      val t, b = ni()
      S(i) = Song(t, b)
    }

    // bの降順で並べる
    Arrays.sort(S, new Comparator[Song] {
      override def compare(o1: Song, o2: Song): Int = Integer.compare(o2.b, o1.b)
    })

    debug(S.mkString(","))

    val q = new java.util.PriorityQueue[Song]
    var ans = 0L
    var s = 0L
    REP(N) { i =>
      if (i < K) {
        s += S(i).t
        q.add(S(i))
        ans = max(ans, s * S(i).b) // 数がK以下のときはbが大きい順に選ぶだけ。そうでないと数を増やした方が得になる
      } else {
        q.add(S(i))
        s += S(i).t
        s -= q.poll().t
        ans = max(ans, s * S(i).b)
      }
    }
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.collection.mutable

object C extends App {

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

  case class Song(t: Long, b: Long)

  val Array(n, k) = readInts(2)
  val songs = Array.fill(n) {
    val Array(t, b) = readLongs(2)
    Song(t, b)
  }.sortBy(-_.b)

  var max = 0L
  val pq = new mutable.PriorityQueue[Song]()(Ordering.by(-_.b))
  var len = 0L

  for (song <- songs) {
    pq += song
    len += song.t
    if (pq.size > k) {
      val r = pq.dequeue()
      len -= r.t
    }
    val score = song.b * len
    if (score > max) max = score
  }

  println(max)
}

import scala.collection.mutable

object C extends App {

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

  case class Song(t: Long, b: Long)

  val Array(n, k) = readInts(2)
  val songs = Array.fill(n) {
    val Array(t, b) = readLongs(2)
    Song(t, b)
  }.sortBy(-_.b)

  var max = 0L
  val pq = new mutable.PriorityQueue[Song]()(Ordering.by(_.b))
  var len = 0L

  for (song <- songs) {
    pq += song
    len += song.t
    if (pq.size > k) {
      val r = pq.dequeue()
      len -= r.t
    }
    val score = song.b * len
    if (score > max) max = score
  }

  println(max)
}


//package codeforces.contests._1353

object ConstructingTheArray {

  import math.abs
  import scala.collection.mutable

  def main(args: Array[String]): Unit = {
    println {
      {
        for (_ <- 1 to io.StdIn.readInt) yield {
          val n = io.StdIn.readInt

          val arr = new Array[Int](n)

          implicit val tuple2Ordering: Ordering[(Int, Int)] = Ordering.fromLessThan[(Int, Int)] {
            case ((x, y), (l, r)) =>
              if (abs(x - y) == abs(l - r)) x > l else abs(x - y) < abs(l - r)
          }

          val queue = mutable.PriorityQueue[(Int, Int)](1 -> n)

          @scala.annotation.tailrec
          def loop(i: Int): Unit =
            if (i <= n) {
              val (l, r) = queue.dequeue()
              val m = (l + r) / 2

              arr(m - 1) = i

              if (l != m)
                queue.enqueue(l -> (m - 1))
              if (l != r)
                queue.enqueue((m + 1) -> r)

              loop(i + 1)
            }

          loop(1)

          arr.mkString(" ")
        }
      }.mkString("\n")
    }

  }
}

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

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

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

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

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

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

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

  case class SmartPair(left: Int, right: Int) {
    val size: Int = right - left
  }

  implicit val ordering: Ordering[SmartPair] = new Ordering[SmartPair]() {
    override def compare(x: SmartPair, y: SmartPair): Int = if (x.size != y.size) {
      y.size - x.size
    } else {
      x.left - y.left
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()

    val result = new Array[Int](n)

    val pairs = scala.collection.mutable.SortedSet[SmartPair]()
    pairs += SmartPair(1, n)
    var step = 1
    while (pairs.nonEmpty) {
      val xy = pairs.head
      val x = xy.left
      val y = xy.right
      pairs.remove(xy)

      if (x <= y) {
        if ((y - x + 1) % 2 == 1) {
          val mid = (y + x) / 2
          result(mid - 1) = step
          if (y != x) {
            pairs += SmartPair(x, mid - 1)
            pairs += SmartPair(mid + 1, y)
          }
        } else {
          val mid = (y + x - 1) / 2
          result(mid - 1) = step
          pairs += SmartPair(mid + 1, y)
          pairs += SmartPair(x, mid - 1)
        }
        step = step + 1
      }

    }

    println(result.mkString(" "))
  }

}

object D extends App {
  import InOut._
  import scala.collection.mutable.TreeSet

  object SegOrdering extends Ordering[(Int, Int)] {
    implicit def compare(x: (Int, Int), y: (Int, Int)): Int = {
      val (l1, r1)     = x
      val (l2, r2)     = y
      val (len1, len2) = (r1 - l1 + 1, r2 - l2 + 1)

      if (len1 > len2) -1
      else if (len1 < len2) 1
      else if (l1 < l2) -1
      else if (l1 > l2) 1
      else 0
    }
  }

  val t = nextInt

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

    var an   = Array.ofDim[Int](n)
    var segs = TreeSet[(Int, Int)]((0, n - 1))(SegOrdering)

    (1 to n).foreach { v =>
      val (l, r) = segs.head

      val i = (l + r) / 2

      segs -= ((l, r))
      if (i > l) segs += ((l, i - 1))
      if (i < r) segs += ((i + 1, r))

      an(i) = v
    }

    out.println(an.mkString(" "))
    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
  }
}

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

object D {

  def solution(n: Int): Array[Int] = {
    val result = Array.ofDim[Int](n)
    val subsByLength =
      mutable.SortedMap((n - 1) -> mutable.SortedSet(0))

    def add(length: Int, start: Int): Unit =
      subsByLength
        .getOrElseUpdate(length - 1, mutable.SortedSet.empty[Int])
        .add(start)

    var iteration = 1
    while (subsByLength.nonEmpty) {
      val length = subsByLength.lastKey + 1
      subsByLength.remove(length - 1).foreach { subs =>
        subs.foreach { start =>
          length match {
            case 1 =>
              result(start) = iteration
            case 2 =>
              result(start) = iteration
              add(1, start + 1)
            case _ =>
              val halfLength = length / 2
              if (length % 2 == 0) {
                add(halfLength - 1, start)
                result(start + halfLength - 1) = iteration
                add(halfLength, start + halfLength)
              } else {
                add(halfLength, start)
                result(start + halfLength) = iteration
                add(halfLength, start + halfLength + 1)
              }
          }
          iteration += 1
        }
      }
    }
    result
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val n = readLine.toInt
      println(solution(n).mkString(" "))
    }
  }
}

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

object D {

  def solution(n: Int): Seq[Int] = {
    val a = Array.fill(n)(0)
    val m = mutable.Map(n -> mutable.Set(0))
    for(i <- 0 until n)
      m(i) = mutable.Set.empty[Int]
    var (len, i) = (n, 1)
    while (len > 0) {
      m.remove(len).foreach { s =>
        s.toSeq.sorted.foreach { start =>
          val l2 = len / 2
          if (len % 2 == 0) {
            m(l2 - 1).add(start)
            a(start + l2 - 1) = i
            m(l2).add(start + l2)
          } else {
            m(l2).add(start)
            a(start + l2) = i
            m(l2).add(start + l2 + 1)
          }
          i += 1
        }
      }
      len -= 1
    }
    a.toSeq
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val n = readLine.toInt
      println(solution(n))
    }
  }
}


import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

import CodeForcesApp._

object _591A extends CodeForcesApp {
  override type Result = Double

  override def solve(scanner: Scanner) = {
    import scanner._
    val (l, p, q) = (nextInt(), nextInt(), nextInt())
    p*l.toDouble/(p + q)
  }

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/********************************[Scala Scanner]*********************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines: Iterator[String] = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  def tokens: Iterator[String] = for {
    line <- lines
    tokenizer = new StringTokenizer(line)
    _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokenizer.nextToken()

  private[this] var current = tokens
  override def hasNext = current.hasNext
  @inline override def next() = current.next()

  /**
   * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line
   */
  def nextLine(): String = {
    current = tokens   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def nextString(): String = next()
  def nextChar(): Char = next().head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

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

object A {

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  def solve: Int = {
    val l = nextInt
    val p = nextInt
    val q = nextInt
    val t = (1.0d * l) / (1.0d * p + q * 1.0d)
    val first = 1.0d * t * p
    println(first)
    return 0
  }
}

import scala.io.StdIn._

object A extends App {
  val L = readLine().toInt
  val p = readLine().toInt
  val q = readLine().toInt

  val t = L * 1.0 / (p + q)
  val answer = p * t
  println("%.4f".format(answer))
}

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

object A {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val l = br.readLine().toInt
    val p = br.readLine().toInt
    val q = br.readLine().toInt
    //---------------------------- parameters reading end --------------------------------

    val sumSpeed = p + q
    val firstColT = l/sumSpeed.toDouble
    val distP1 = firstColT * p
    val secondColT = (l*2) / sumSpeed.toDouble
    val distP2 = (p*secondColT - distP1)

    println(distP2)
  }

//========================= samples ========================
val sa1 = """

"""

//========================= samples end ====================
}

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

object Codeforces591A extends App {
  def Harry(l: Double, p: Int, q: Int): Double = {
    val time = l / (p + q)
    p * time
  }

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

  val l = in.nextInt
  val p = in.nextInt
  val q = in.nextInt

  print(Harry(l, p, q))
}

import scala.io.StdIn._
object program {
	def main(args: Array[String]) {
		var l = readInt(); var a = readInt(); var b = readInt()
		println((l.toDouble/ (a + b)) * a);
	}
}

import java.nio.channels.Pipe.SourceChannel

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

object A5 {
  def solution(d : Int, s1 : Int, s2 : Int) : Double = {
    val (ds1,ds2, maxs) = (s1.toDouble, s2.toDouble, max(s1,s2).toDouble)
    val b = Iterator.iterate((0.0,0.0))(a =>(a._1 + ds1/maxs/10000, a._2+ds2/maxs/10000)).dropWhile(a=>a._1 +a._2 < d).take(1).toArray
    b(0)._1
  }
  def main(args: Array[String]): Unit = {
   val xs = Source.stdin.getLines().take(3).map(_.toInt).toArray
    //assert(abs(solution(100,50,50)-50) < 1e-4)
    //assert(abs(solution(199,60,40)-119.4)<1e-4)
    println(solution(xs(0),xs(1), xs(2)))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val l = in.next().toInt
  val p = in.next().toInt
  val q = in.next().toInt
  println(p * l / (p + q).toFloat)
}

object A591 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(l) = readInts(1)
    val Array(p) = readInts(1)
    val Array(q) = readInts(1)

    println((p.toDouble * l)/(p.toDouble + q.toDouble))
  }
}

import scala.collection._

object A extends App {

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

  val Array(l) = readDoubles(1)
  val Array(p) = readDoubles(1)
  val Array(q) = readDoubles(1)

  val t = l / (p + q)

  println(p * t)
}

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

object Codeforces591A extends App {
  def Harry(l: Double, p: Int, q: Int): Double = {
    val time = l / (p + q)
    p * time
  }

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

  val l = in.nextInt
  val p = in.nextInt
  val q = in.nextInt

  out.write(Harry(l, p, q).toString)
}


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


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

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

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

/**
 * 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) }
  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()
  }
}


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

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

}

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