object SystemAdministrator22C extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val m = in.nextInt()
    val v = in.nextInt()

    val stringBuilder = new StringBuilder()
    if(m>=n-1 && m <= (((n-1)*(n-2))/2+1)){
      val x = if(v == 1) 2 else 1

      def printEdges(node: Int,edgesToPrint: Int): Int = {

        if(node == v){
          for(i <- 1 to n){

            if(i != v) {
              stringBuilder.append(s"$v $i").append(System.lineSeparator())
            }
          }
          edgesToPrint-(n-1)
        }else{
          if(node == x){
            edgesToPrint
          }else{
            var i = node+1
            var counter = edgesToPrint
            while( counter > 0 && i<=n){
              if(i != x && i != v){
                stringBuilder.append(s"$node $i").append(System.lineSeparator())
                counter -= 1
              }
              i += 1
            }
            counter
          }
        }
      }

      var restEdges = printEdges(v,m)
      var indx = 1

      while(restEdges > 0){
        if(indx != v){
          restEdges = printEdges(indx,restEdges)
        }
        indx += 1

      }

    }else{
      stringBuilder.append(-1)
    }

    out.println(stringBuilder.toString())

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int = return next().toInt
  }
}

object SystemAdministrator22C extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val m = in.nextInt()
    val v = in.nextInt()

    val stringBuilder = new StringBuilder()
    if(m>=n-1 && m <= (((n-1)*(n-2))/2+1)){
      val x = if(v == 1) 2 else 1

      def printEdges(node: Int,edgesToPrint: Int): Int = {

        if(node == v){
          for(i <- 1 to n){

            if(i != v) {
              stringBuilder.append(s"$v $i").append(System.lineSeparator())
            }
          }
          edgesToPrint-(n-1)
        }else{
          if(node == x){
            edgesToPrint
          }else{

            (node +1 to n).foldLeft(edgesToPrint)((edges,i) => {
              if(i == x || i == v || edges == 0){
                edges
              }else{
                stringBuilder.append(s"$node $i").append(System.lineSeparator())
                edges-1
              }
            })

          }
        }
      }

      (1 to n).foldLeft(printEdges(v,m))((restEdges,indx) => {
        if(indx == v || restEdges==0){
          restEdges
        }else{
          printEdges(indx,restEdges)
        }
      })

    }else{
      stringBuilder.append(-1)
    }

    out.println(stringBuilder.toString())

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int = return next().toInt
  }
}


import scala.util.control.Breaks

//https://codeforces.com/problemset/problem/1327/B
object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val testCases = in.readLine().toInt
    for (t <- 0 until testCases) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      for (i <- 0 until n) {
        val l=in.readLine()
        if(l.length>1) {
          arr(i) = l.substring(l.indexOf(" ") + 1).split(" ").map(_.toInt - 1)
        }
      }
      val marriedPrinces=Array.fill[Boolean](n)(false)
      val marriedPrincesses=Array.fill[Boolean](n)(false)
      var unmarriedPrincesses=0
      for (i <- 0 until n) {
        Breaks.breakable {
          if( arr(i)!=null) {
            for (j <- 0 until arr(i).length) {
              if (marriedPrinces(arr(i)(j)) == false) {
                marriedPrinces(arr(i)(j)) = true
                marriedPrincesses(i) = true
                Breaks.break()
              }
            }
          }
          unmarriedPrincesses+=1
        }
      }
      if(unmarriedPrincesses==0){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        var unmarriedPriceIndex=0
        var unmarriedPrincessIndex=0
        if (unmarriedPrincesses!=0){
          unmarriedPrincesses-=1
          while (marriedPrinces(unmarriedPriceIndex)) {
            unmarriedPriceIndex+=1
          }
          while (marriedPrincesses(unmarriedPrincessIndex)) {
            unmarriedPrincessIndex+=1
          }
          marriedPrincesses(unmarriedPrincessIndex)=true
          marriedPrinces(unmarriedPriceIndex)=true

          println((unmarriedPrincessIndex+1)+" "+(unmarriedPriceIndex+1))
        }
      }
    }
  }
}

import scala.util.control.Breaks

object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val tC = in.readLine().toInt
    for (t <- 0 until tC) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      for (i <- 0 until n) {
        val l=in.readLine()
        if(l.length>1)
          arr(i)=l.substring(l.indexOf(" ")+1).split(" ").map(_.toInt-1)
        else
          arr(i)=new Array[Int](0)
      }
      val p=Array.fill[Boolean](n)(false)
      val m=Array.fill[Boolean](n)(false)
      var um=0
      for (i <- 0 until n) {
        Breaks.breakable {
          for (j <- 0 until arr(i).length) {
            if(p(arr(i)(j))==false){
              p(arr(i)(j))=true
              m(i)=true
              Breaks.break()
            }
          }
          um+=1
        }
      }
      if(um==0){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        var pri=0
        var gri=0
        if (um!=0){
          um-=1
          while (p(pri)) pri+=1
          while (m(gri)) gri+=1
          m(gri)=true
          p(pri)=true
          println((gri+1)+" "+(pri+1))
        }
      }
    }
  }
}

import scala.util.control.Breaks
import scala.collection.mutable.HashSet

//https://codeforces.com/problemset/problem/1327/B
object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val testCases = in.readLine().toInt
    for (t <- 0 until testCases) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      val unmarriedPrinces=HashSet[Int]()
      for (i <- 0 until n) {
        unmarriedPrinces+=i
        val l=in.readLine()
        if(l.length>1) {
          arr(i) = l.substring(l.indexOf(" ") + 1).split(" ").map(_.toInt - 1)
        }
      }
      var unmarriedPrincessIndex= -1
      for (i <- 0 until n) {
        Breaks.breakable {
          if( arr(i)!=null) {
            for (j <- 0 until arr(i).length) {
              if (unmarriedPrinces.contains(arr(i)(j))) {
                unmarriedPrinces-=(arr(i)(j))
                Breaks.break()
              }
            }
          }
          unmarriedPrincessIndex=i
        }
      }
      if(unmarriedPrincessIndex== -1){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        println((unmarriedPrincessIndex+1)+" "+(unmarriedPrinces.head+1))
      }
    }
  }
}

import scala.util.control.Breaks

//https://codeforces.com/problemset/problem/1327/B
object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val testCases = in.readLine().toInt
    for (t <- 0 until testCases) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      for (i <- 0 until n) {
        val l=in.readLine()
        if(l.length>1) {
          arr(i) = l.substring(l.indexOf(" ") + 1).split(" ").map(_.toInt - 1)
        }
      }
      val marriedPrinces=Array.fill[Boolean](n)(false)
      val marriedPrincesses=Array.fill[Boolean](n)(false)
      var unmarriedPrincesses=0
      for (i <- 0 until n) {
        Breaks.breakable {
          if( arr(i)!=null) {
            for (j <- 0 until arr(i).length) {
              if (marriedPrinces(arr(i)(j)) == false) {
                marriedPrinces(arr(i)(j)) = true
                marriedPrincesses(i) = true
                Breaks.break()
              }
            }
          }
          unmarriedPrincesses+=1
        }
      }
      if(unmarriedPrincesses==0){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        var unmarriedPriceIndex=0
        var unmarriedPrincessIndex=0
        /*if (unmarriedPrincesses!=0){
          unmarriedPrincesses-=1*/
          while (marriedPrinces(unmarriedPriceIndex)) {
            unmarriedPriceIndex+=1
          }
          while (marriedPrincesses(unmarriedPrincessIndex)) {
            unmarriedPrincessIndex+=1
          }
          marriedPrincesses(unmarriedPrincessIndex)=true
          marriedPrinces(unmarriedPriceIndex)=true

          println((unmarriedPrincessIndex+1)+" "+(unmarriedPriceIndex+1))
        //}
      }
    }
  }
}

import scala.util.control.Breaks
import scala.collection.mutable.HashSet

//https://codeforces.com/problemset/problem/1327/B
object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val testCases = in.readLine().toInt
    for (t <- 0 until testCases) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      val unmarriedPrinces=HashSet[Int]()
      var unmarriedPrincessIndex= -1
      for (i <- 0 until n) {
        unmarriedPrinces+=i
        val l=in.readLine()
        if(l.length>1) {
          arr(i) = l.substring(l.indexOf(" ") + 1).split(" ").map(_.toInt - 1)
        }
      }
      for (i <- 0 until n) {
        Breaks.breakable {
          if( arr(i)!=null) {
            for (j <- 0 until arr(i).length) {
              if (unmarriedPrinces.contains(arr(i)(j))) {
                unmarriedPrinces-=(arr(i)(j))
                Breaks.break()
              }
            }
          }
          unmarriedPrincessIndex=i
        }
      }
      if(unmarriedPrincessIndex== -1){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        println((unmarriedPrincessIndex+1)+" "+(unmarriedPrinces.head+1))
      }
    }
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    val maxN = 100002

    val ps = Array.fill(maxN)(true)
    val lista = Array.fill(maxN)(List.empty[Int])
    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      ps(0) = false
      (1 to n).foreach{ i =>

        ps(i) = true
      }

      (1 to n).foreach{ i =>
        val k = in.nextInt()
        lista(i) = (1 to k).map(_ => in.nextInt()).toList
      }
      var dsFree = -1
      (1 to n).foreach{ i =>
        lista(i).find(ps) match {
          case Some(p) => ps(p) = false
          case None => dsFree = i
        }
      }
      if(dsFree == -1){
        out.println("OPTIMAL")
      }else{
        val psFree = ps.indexWhere(p => p)
        out.println("IMPROVE")
        out.println(s"$dsFree $psFree")
      }

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, 200000, score) - n

    println(ans)
  }
}

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, 500000, score) - n

    println(ans)
  }
}

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, n << 1, score) - n

    println(ans)
  }
}

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, 175000, score) - n

    println(ans)
  }
}

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, 100000, score) - n

    println(ans)
  }
}

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

  def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }
    go(l, r)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(k: Int): Boolean = {
      val r = k - k / 4

      val ascore =
        if (k <= n) aprefix(n) - aprefix(n - r)
        else {
          val e = r min (k - n)
          e * 100 + aprefix(n) - aprefix(n - r + e)
        }

      val bscore = bprefix(n) - bprefix(0 max (n - r))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else {
        val right = {
          @annotation.tailrec
          def go(r: Int): Int = if (score(r)) r else go(r << 1)
          go(1)
        }
        binarySearch(n, right, score) - n
      }

    println(ans)
  }
}

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

  def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }
    go(l, r)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(k: Int): Boolean = {
      val r = k - k / 4

      val (ascore, bscore) =
        if (k <= n) (aprefix(n) - aprefix(n - r), bprefix(n) - bprefix(n - r))
        else {
          val e = r min (k - n)
          (e * 100 + aprefix(n) - aprefix(n - r + e), bprefix(n))
        }

      ascore >= bscore
    }

    val ans = if (score(n)) 0 else binarySearch(n, 100005, score) - n

    println(ans)
  }
}

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

  def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }
    go(l, r)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(k: Int): Boolean = {
      val r = k - k / 4

      val (ascore, bscore) =
        if (k <= n) (aprefix(n) - aprefix(n - r), bprefix(n) - bprefix(n - r))
        else {
          val e = r min (k - n)
          (e * 100 + aprefix(n) - aprefix(n - r + e), bprefix(n))
        }

      ascore >= bscore
    }

    val ans = if (score(n)) 0 else binarySearch(n, 200, score) - n

    println(ans)
  }
}


object A1004 extends App {
  def read: Array[Int] = readLine.split(" ").map(_.toInt)

  val (n, d) = {
    val fl = read
    (fl(0), fl(1))
  }

  val hotels = read

  def result = {
    (0 to n - 1)
      .map { i =>
        if (i == n - 1) 1
        else {
          val diff = (hotels(i + 1) - hotels(i)) / d
          val residual = (hotels(i + 1) - hotels(i)) % d
          if (diff == 2 && residual > 0 || diff > 2) 2
          else if (diff == 2) 1
          else 0
        }
      }
      .reduce(_ + _) + 1
  }

  println(result)
}

import scala.io.StdIn

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var d = array1(1)

  var count = 2

  val arr = StdIn.readLine().split(" ").map(_.toInt)

  for (i <- 0 until arr.size - 1)
    {
      val a = arr(i) + d
      val b = arr(i + 1) - d
      if (a <= b)
        {
          if (a != b) count = count + 2 else count = count + 1
        }
    }
  println(count)
}

import scala.io.StdIn.readLine

object a1004 {
  def main(args: Array[String]): Unit = {
    def getInts() =  readLine().split(" ").map(_.toInt)
    val Array(n, d) = getInts()
    val hs = getInts()
    println((hs zip hs.tail map{ a=> val c = a._2 - a._1 -1 - (2*(d-1)) ; if (c<0) 0 else if (c>2) 2 else c} sum) + 2)
  }
}


import scala.collection.mutable._

object Solution {
  def main(args: Array[String]) {
    val n = io.StdIn.readLine.toInt
    val stairs = io.StdIn.readLine.split(" ").map(_.toInt)

    var count = 0
    var lastStep = new ListBuffer[Int]()
    for (i <- 0 until stairs.length) {
      if (stairs(i) == 1) {
        count += 1
        if (i != 0) {
          lastStep += stairs(i-1)
        }
      }
    }
    lastStep += stairs(n-1)
    println(count)
    println(lastStep.toList.mkString(" "))

  }
}

/**
  * @author ShankarShastri
  *         Algorithm: ProblemA
  */
import scala.io.StdIn._
import scala.annotation.tailrec

object ProblemA {

  def getAllIndicesOfElement[T](element: T, l: List[T]): List[Int] = {
    @tailrec
    def getAllIndicesHelper(l: List[T], accumList: List[Int] = List[Int](), index: Int=0): List[Int] = {
      if(l.length == 0) {
        (index :: accumList).reverse
      }  else {
        l match {
          case head :: tail if head == element => getAllIndicesHelper(tail, index :: accumList, index+1)
          case _ :: tail => getAllIndicesHelper(tail, accumList, index+1)
        }
      }
    }
    getAllIndicesHelper(l)
  }

  def tanyaStairwayStr(list: List[Int]): String = {
    getAllIndicesOfElement(1, list).sliding(2).toList.map(_.reduce((a,b) => b - a)).mkString(" ")
  }

  def main(args: Array[String]): Unit = {
    val _ = readInt
    val arr = readLine().split(" ").map(_.toInt).toList
    println(arr.count(_ == 1))
    println(tanyaStairwayStr(arr))
  }
}

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

object Codeforces1005A {

  def parseStairs(sounds: Array[Int]): Seq[Int] = {
    val stairs = new ListBuffer[Int]
    for (sound <- sounds) {
      if (sound == 1) {
        stairs.append(1)
      } else {
        stairs(stairs.length - 1) += 1
      }
    }
    stairs
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val sounds = StdIn.readLine.split(" ").map(_.trim.toInt)

    val stairs = parseStairs(sounds)
    println(stairs.length)
    println(stairs.mkString(" "))
  }
}

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

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

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

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

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

    val cnts = ArrayBuffer[Int]()
    var cnt = 0
    var prev = 0
    REP(N) { i =>
      if (A(i) == prev + 1) {
        cnt += 1
      } else {
        cnts += cnt
        cnt = 1
      }
      prev = A(i)
    }
    if (cnt > 0) cnts += cnt
    out.println(cnts.length)
    out.println(cnts.mkString(" "))
  }

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

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

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

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

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

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

object CF496A extends App {

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

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

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

    def count(numbers: Array[Int], stairs: List[Int], current: Int): List[Int] = {
      if (numbers.isEmpty)
        return stairs :+ current
      if (numbers.head == 1)
        return count(numbers.tail, stairs :+ current, 1)
      else
        return count(numbers.tail, stairs, current + 1)
    }

    val stairs = count(numbers, List[Int](), 0).tail

    out.println(stairs.length)
    out.println(stairs.mkString(" "))
  }

  solve
  out.flush
  out.close
}


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

object C extends App {

  case class Point(x: Int, segId: Int, isBegin: Boolean)

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val points = Array.ofDim[Point](n * 2)
    (0 until n).foreach { i =>
      points(i * 2) = Point(in.nextInt, i, isBegin = true)
      points(i * 2 + 1) = Point(in.nextInt, i, isBegin = false)
    }
    util.Sorting.quickSort(points)((x: Point, y: Point) => Ordering[Int].compare(x.x, y.x))
    //points.sortBy(_.x)
    //points.foreach(println)
    var k = 0
    var ans = 0
    (0 until n * 2 - 1).foreach { i =>
      if (points(i).isBegin)
        k += 1
      else
        k -= 1
      if (k == n - 1) {
        ans = math.max(ans, points(i + 1).x - points(i).x)
      }
      if (k == n) {
        if (points(i).segId == points(i + 1).segId) {
          ans = math.max(ans, points(i + 2).x - points(i - 1).x)
        }
        ans = math.max(ans, points(i + 1).x - points(i - 1).x)
        ans = math.max(ans, points(i + 2).x - points(i).x)
      }
    }
    print(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    case class Seg(l: Int, r: Int) {
      def len = max(0, r - l)
    }
    val S = map(N) { _ =>
      val l, r = sc.nextInt()
      Seg(l, r)
    }

    var msR = 0
    var mxL = 0
    rep(N) { i =>
      val s = S(i)
      if (s.r < S(msR).r || (s.r == S(msR).r && s.len < S(msR).len)) {
        msR = i
      }
      if (S(mxL).l < s.l || (s.l == S(mxL).l && s.len < S(mxL).len)) {
        mxL = i
      }
    }

    def intersect(ignore: Int): Int = {
      var msR = Integer.MAX_VALUE
      var mxL = 0
      rep(N) { i =>
        if (i != ignore) {
          val s = S(i)
          if (s.r < msR) {
            msR = s.r
          }
          if (mxL < s.l) {
            mxL = s.l
          }
        }
      }
      max(0, msR - mxL)
    }

    out.println(max(intersect(msR), intersect(mxL)))
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  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)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import scala.collection.mutable.ListBuffer

object CF506C extends App {
  import scala.io.StdIn
  val n = StdIn.readLine.toInt
  val segments = new Array[Int](n).map(_ => StdIn.readLine.split(' ').map(_.toInt))

  val shrink = ListBuffer[Int]()

  var min = Int.MinValue
  var max = Int.MaxValue

  for (i <- 0 until n) {
    val segment = segments(i)
    if (segment(0) > min || segment(1) < max) {
      shrink += i
    }
    if (segment(0) > min)
      min = segment(0)
    if (segment(1) < max)
      max = segment(1)
  }

  var maxLength = 0
  for (drop <- shrink) {
    min = Int.MinValue
    max = Int.MaxValue
    for (i <- (0 until n).filter(_ != drop)) {
      if (segments(i)(0) > min)
        min = segments(i)(0)
      if (segments(i)(1) < max)
        max = segments(i)(1)
    }
    maxLength = maxLength.max(max-min)
  }

  println(maxLength)
}

import java.io.FileReader
import java.util
import java.util.Comparator

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

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  case class Interval(l: Int, r: Int) {
    def intersect(o: Option[Interval]): Option[Interval] = {
      o match {
        case Some(Interval(ol, or)) =>
          if (ol < r && l < or) {
            Some(Interval(Math.max(ol, l), Math.min(or, r)))
          } else {
            None
          }
        case None => None
      }
    }

    def contains(o: Option[Interval]): Boolean = {
      intersect(o).exists(this.equals(_))
    }

    def len(): Int = {
      r - l
    }
  }

  def doCase(): Unit ={
    val N = readInt()
    val ints: Array[Interval] = Array.fill(N)(null)
    var i = 0
    while (i < N) {
      ints(i) = readIntLine() match {case Array(a, b) => Interval(a, b)}
      i += 1
    }

    var full = Some(Interval(Integer.MIN_VALUE, Integer.MAX_VALUE)): Option[Interval]
    var other = List[Option[Interval]]()
    for (int <- ints) {
      var n = full
      full = full.flatMap(_.intersect(Some(int)))
      val intersected = other.map(int.intersect)
      other = n :: intersected.distinct
    }

    print(other.map(_.map(_.len()).getOrElse(0)).max)
  }

  def main(args: Array[String]): Unit = {
    val noCases = 1
    for (i <- 0 until noCases) {
      doCase()
    }
  }

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

  def readLongLine(): Array[Long] = {
    StdIn.readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    StdIn.readLine().split(" ").map(BigInt.apply)
  }
}


object Main{

    def main(args: Array[String]){
         val Array(a, b, n) = readLine().split(" ").map(_.toInt)
         val d = (b - (a*10)%b) % b
         if (d >= 10) println("-1") else{
            print(a)
            print(d)
            for (i <- 1 to n-1)
                print(0)
            println()
         }
    }                                         //> main: (args: Array[String])Unit
}

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

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

  val k        = math.floor(a * 10.0 / b).toInt
  val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)
  val (a1, a2) = (a * 10 + x1, a * 10 + x2)

  val ans =
    if (x1 >= 0 && x1 < 10 && a1 % b == 0)
      a1.toString + "0" * (n - 1)
    else if (x2 >= 0 && x2 < 10 && a2 % b == 0)
      a2.toString + "0" * (n - 1)
    else
      "-1"

  println(ans)
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toInt)
  val d              = (b - (a * 10) % b) % b

  if (d > 9)
    println("-1")
  else
    println(s"$a$d${"0" * (n - 1)}")
}

object Main {
  def main(args: Array[String]) {
    val abn =  readLine().split(" ").map(_.toInt)
    val a = abn(0)
    val b = abn(1)
    val n = abn(2)

    val max = (a * 10 + 9).toFloat / b.toFloat
    val min = (a * 10).toFloat / b.toFloat

    val dec = if (max.floor >= min.ceil) (min.ceil.toInt * b - a * 10)
    else -1

    if (dec == -1) println("-1")
    else {
      val s = Seq(a, dec) ++ (1 until n).map(_ => 0)
      println(s.mkString)
    }
  }
}

import scala.Math.pow;

object App {
  def f1(n: Long, m: Int) = {
    val k = n * 10
    for {
        i <- (0 to 9).toList
        if ((k + i) % m == 0)
    } yield k + i
  }                                               //> f1: (n: Int, m: Int)List[Int]

  def f1_io() = {
    val Array(a, b, n) = (readLine split " ") map (_.toInt)
    val l = f1(a, b)
    if (l.isEmpty) print(-1)
    else {
        print(l(0))
        for (i <- (1 to n - 1)) print(0)
    }
  }                                 //> f: (input: String)Double

  def main(args: Array[String]): Unit = {
    f1_io
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(a, b, n) = in.next().split(' ').map(_.toInt)
  val r = (0 to 9).find(i => (a * 10 + i) % b == 0)
  if (r.isEmpty)
    println(-1)
  else
    println(s"$a${r.get}" + "0" * (n - 1))
}

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

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

  val A, B, N = sc.nextInt

  def solve(): String = {
    val sb = new StringBuilder(A.toString)

    @inline
    def extend(x: Int): Int = {
      val rem = x * 10 % B
      if (rem == 0) 0
      else {
        val d = B - rem
        if (d > 9) -1
        else d
      }
    }

    val d = extend(A)
    if (d < 0) "-1"
    else {
      sb += ('0' + d).toChar
      for (_ <- 1 until N)
        sb += '0'
      sb.toString
    }
  }

  out.println(solve)
  out.close
}

object Main{

    def main(args: Array[String]){
         val Array(a, b, n) = readLine().split(" ").map(_.toInt)
         val d = b - (a*10)%b
         if (d >= 10) println("-1") else{
            print(a)
            print(d)
            for (i <- 1 to n-1)
                print(0)
            println()
         }
    }                                         //> main: (args: Array[String])Unit
}

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

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

  val A, B, N = sc.nextInt

  def solve(): String = {
    val sb = new StringBuilder(A.toString)

    @inline
    def extend(x: Int): Int = {
      val rem = x * 10 % B
      if (rem == 0) 0
      else {
        val d = B - rem
        if (d > 9) -1
        else d
      }
    }

    @tailrec
    def loop(acc: Int, n: Int): String = {
      if (n == 0) sb.toString
      else {
        val d: Int = extend(acc)
        sb += (d + '0').toChar
        if (d < 0) "-1"
        else loop(d, n - 1)
      }
    }

    loop(A % B, N)
  }

  out.println(solve)
  out.close
}

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

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

  val A, B, N = sc.nextInt

  def solve(): BigInt = {

    def lengthen(x: BigInt): BigInt = {
      val x10: BigInt = x * 10
      val a: BigInt = B - x10 % B
      if (a < 10) x10 + a
      else -1
    }

    @tailrec
    def loop(acc: BigInt, n: Int): BigInt = {
      if (n == 0 || acc < 0) acc
      else loop(lengthen(acc), n - 1)
    }

    loop(BigInt(A), N)
  }

  out.println(solve)
  out.close
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toInt)
  val d              = (b - (a * 10) % b) % b

  if (d > 0)
    println("-1")
  else
    println(s"$a$d${"0" * (n - 1)}")
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toLong)

  @annotation.tailrec
  def go(a: Long, n: Long): Long =
    if (n == 0) a
    else {
      val k        = math.floor(a * 10 / b).toLong
      val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)

      if (x1 >= 0 && x1 < 10) go(a * 10 + x1, n - 1)
      else if (x2 >= 0 && x2 < 10) go(a * 10 + x2, n - 1)
      else -1L
    }

  val ans = go(a, n)

  println(ans)
}

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

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

  val k        = math.floor(a * 10 / b).toInt
  val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)

  val ans =
    if (x1 >= 0 && x1 < 10)
      (a * 10 + x1).toString + "0" * (n - 1)
    else if (x2 >= 0 && x2 < 10)
      (a * 10 + x2).toString + "0" * (n - 1)
    else
      "-1"

  println(ans)
}

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

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

  val k        = math.floor(a * 10.0 / b).toInt
  val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)

  val ans =
    if (x1 >= 0 && x1 < 10)
      (a * 10 + x1).toString + "0" * (n - 1)
    else if (x2 >= 0 && x2 < 10)
      (a * 10 + x2).toString + "0" * (n - 1)
    else
      "-1"

  println(ans)
}

object Main {
  def main(args: Array[String]) {
    val abn =  readLine().split(" ").map(_.toInt)
    val a = abn(0)
    val b = abn(1)
    val n = abn(2)

    val max = (a * 10 + 9).toFloat / b.toFloat
    val min = (a * 10).toFloat / b.toFloat

    val dec = if (max.floor >= min.ceil) (min.ceil.toInt - a * 10)
    else -1

    if (dec == -1) println("-1")
    else {
      val s = Seq(a, n) ++ (1 until n).map(_ => 0)
      println(s.mkString)
    }
  }
}

import scala.Math.pow;

object App {
  def f1(n: Long, m: Int) = {
    val k = n * 10
    for {
        i <- (0 to 9).toList
        if ((k + i) % m == 0)
    } yield k + i
  }                                               //> f1: (n: Int, m: Int)List[Int]

  def f1_io() = {
    val Array(a, b, n) = (readLine split " ") map (_.toInt)
    val l = f1(a, b)
    if (l.isEmpty) print(-1)
    else {
        print(l(0))
        for (i <- (1 to n + 1 - l(0).toString.length)) print(0)
    }
  }                                 //> f: (input: String)Double

  def main(args: Array[String]): Unit = {
    f1_io
  }

}

import scala.Math.pow;

object App {
  def f1(n: Int, m: Int) = {
    val k = n * 10
    for {
        i <- (0 to 9).toList
        if ((k + i) % m == 0)
    } yield k + i
  }                                               //> f1: (n: Int, m: Int)List[Int]

  def f1_io() = {
    val Array(a, b, n) = (readLine split " ") map (_.toInt)
    val l = f1(a, b)
    if (l.isEmpty) print(-1)
    else {
        print(l(0))
        for (i <- (1 to n + 1 - l(0).toString.length)) print(0)
    }
  }                                 //> f: (input: String)Double

  def main(args: Array[String]): Unit = {
    f1_io
  }

}

import scala.Math.pow;

object App {
  def f1(n: Int, m: Int) = {
    val k = n * 10
    for {
        i <- (0 to 9).toList
        if ((k + i) % m == 0)
    } yield k + i
  }                                               //> f1: (n: Int, m: Int)List[Int]

  def f1_io() = {
    val Array(a, b, n) = (readLine split " ") map (_.toInt)
    val l = f1(a, b)
    if (l.isEmpty) print(-1)
    else {
        print(l(1))
        for (i <- (1 to n - l(1).toString.length)) print(0)
    }
  }                                 //> f: (input: String)Double

  def main(args: Array[String]): Unit = {
    f1_io
  }

}


import java.util.Scanner

/**
  * Created by MZKL7315 on 4/12/2016.
  */

object Main {

  def calc(s: String, k: Int): String = s match {
    case "" => ""
    case s => {
      val c = s.count(_ == s.head)
      if (c % k != 0) throw new Error("-1") else (1 to c / k).map(_ => s.head).mkString + calc(s filter (_ != s.head), k)
    }
  }

  def gen(s: String, k: Int): String = (s, k) match {
    case (s, 0) => ""
    case _ => s + gen(s, k - 1)
  }

  def main(args: Array[String]) = {
    val in: Scanner = new Scanner(System.in)
    val k = in.nextInt()
    val s = in.next()
    try {
      val res = calc(s, k)
      println(gen(res, k))
    } catch {
      case e: Error => println(e.getMessage)
    }
  }
}

import java.util.Scanner

/**
  * Created by MZKL7315 on 4/12/2016.
  */

object Main {

  def main(args: Array[String]) = {
    val in: Scanner = new Scanner(System.in)
    val k = in.nextInt()
    val s = in.next()

    val m = s.map(x => (x, s.count(y => y == x))).toMap
    if (m.exists(_._2 % k != 0)) println(-1)
    else {
      val res = m.map({ case (x, y) => (1 to y / k).map(_ => x).mkString }).mkString
      println((1 to k).map(_ => res).mkString)
    }

  }
}

import java.util.Scanner

/**
  * Created by MZKL7315 on 4/12/2016.
  */

object Main {

  def charCounts(s: String): Map[Char, Int] = s match {
    case "" => Map()
    case s => charCounts(s filter (_ != s.head)) + (s.head -> s.count(_ == s.head))
  }

  def main(args: Array[String]) = {
    val in: Scanner = new Scanner(System.in)
    val k = in.nextInt()
    val s = in.next()

    val m = charCounts(s)
    if (m.exists(_._2 % k != 0)) println(-1)
    else {
      println((1 to k).map(_ => m.map({ case (x, y) => (1 to y / k).map(_ => x).mkString }).mkString).mkString)
    }

  }
}

import java.util.StringTokenizer

object _219A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val k = next.toInt
  val s = next
  val grouped = s.groupBy(ch => ch)
  if (grouped.exists(pair => pair._2.length % k != 0)) println(-1)
  else {
    val map = grouped.map(pair => (pair._1, pair._2.length / k))
    val one = map.map(i => (0 until i._2).map(j => i._1).mkString).mkString
    val ans = (0 until k).map(i => one).mkString
    println(ans)
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val k = in.next().toInt
  val str = in.next().foldLeft(Map.empty[Char, Int]) {
    case (acc, el) if acc.contains(el) => acc + (el -> (acc(el) + 1))
    case (acc, el) => acc + (el -> 1)
  }
  if (str.values.exists(_ % k > 0))
    println("-1")
  else {
    val s = str.map{
      case(key, v) => List.fill(v / k){key}.mkString
    }.mkString
    println(List.fill(k){s}.mkString)
  }
}

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

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

  val N = sc.nextLine.toInt
  val S = sc.nextLine.sorted
  val len = S.length

  val base: String = {
    @tailrec
    def loop(acc: List[Char], i: Int): String =
      if (i >= len) acc.mkString
      else loop(acc :+ S(i), i + N)
    loop(Nil, 0)
  }

  val answer: String = {
    val res = base * N
    if (S == res.sorted) res
    else "-1"
  }

  out.println(answer)
  out.close
}

import annotation.tailrec
import java.io._

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

  val k = readInt
  val s = reader.readLine().groupBy(x => x)
  val ans = Map(false -> (() => "-1"), true -> (() => s.values.map(str => str.take(str.length / k)).mkString * k)) apply {
    s.values.forall(_.length % k == 0)
  }

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

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val s = readLine
    val map = scala.collection.mutable.Map[Char, Int]()
    s.foreach(c => map(c) = map.getOrElse(c, 0) + 1)
    var r = Seq[Char]()
    var cor = true
    map.foreach { case (c, i) =>
      if (i % n == 0) r ++= Seq.fill(i / n)(c)
      else cor = false
    }
    if(cor) println(Seq.fill(n)(r.mkString).mkString)
    else println("-1")
  }
}

import Console._

object Main extends App {

  def getCountMap(str: String): Map[Char, Int] = {
    str.groupBy(_.toChar).map(p => (p._1, p._2.length))
  }

  val k = readInt
  val str = readLine

  // check if str.length % k == 0
  if (str.length % k != 0) {
    print(-1)
    exit
  }

  // fill map(letter, count) sorted by count
  val freqMap = getCountMap(str).toSeq.sortBy(_._2).toMap

  // Precondition check - every map count % k must be == 0
  freqMap.keys.map(chr => {
    if (freqMap(chr) % k != 0) {
      print(-1)
      exit
    }
  })

  // form initial sequence
  val chrSeq = freqMap.flatMap(chr => {
    List.fill(chr._2 / k)(chr._1)
  }).toList
  for(i <- 0 until k) {
      print(chrSeq.mkString)
  }

  // print all ? - generate not repeating sequences
  // chrSeq.permutations.toList.map(x => println(List.fill(k)(x.mkString).mkString))

}

import java.util.Scanner

/**
  * Created by MZKL7315 on 4/12/2016.
  */

object Main {

  def calc(s: String): String = s match {
    case "" => ""
    case s => {
      val c = s.count(_ == s.head)
      if (c % 2 == 1) throw new Error("-1") else (1 to c / 2).map(_ => s.head).mkString + calc(s filter (_ != s.head))
    }
  }

  def main(args: Array[String]) = {
    val in: Scanner = new Scanner(System.in)
    val n = in.nextInt()
    val s = in.next()
    try {
      val res = calc(s)
      println(res + res)
    } catch {
      case e: Error => println(e.getMessage)
    }
  }
}

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

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

  val N = sc.nextLine.toInt
  val S = sc.nextLine.sorted
  val len = S.length

  val base: String = {
    @tailrec
    def loop(acc: List[Char], i: Int): String =
      if (i >= len) acc.mkString
      else loop(acc :+ S(i), i + N)
    loop(Nil, 0)
  }

  val answer: String =
    if (S == (base * N).sorted) base
    else "-1"

  out.println(answer)
  out.close
}

import Console._

object Main extends App {

  def getCountMap(str: String): Map[Char, Int] = {
    str.groupBy(_.toChar).map(p => (p._1, p._2.length))
  }

  val k = readInt
  val str = readLine

  // check if str.length % k == 0
  if (str.length % k != 0) {
    print(-1)
    exit
  }

  // fill map(letter, count) sorted by count
  val freqMap = getCountMap(str).toSeq.sortBy(_._2).toMap

  // Precondition check - every map count % k must be == 0
  freqMap.keys.map(chr => {
    if (freqMap(chr) % k != 0) {
      print(-1)
      exit
    }
  })

  // form initial sequence
  val chrSeq = freqMap.flatMap(chr => {
    List.fill(chr._2 / k)(chr._1)
  }).toList

  // generate not repeating sequences
  chrSeq.permutations.toList.map(x => println(List.fill(k)(x.mkString).mkString))

}


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

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

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

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

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

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

object Workspace {
  import Main._
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val A = na(N)
      if (N == 1) {
        out.println(-1)
      } else {
        val inf = 1e9.toInt
        var d = inf
        val lst = mutable.Map[Int, Int]().withDefaultValue(-1)
        REP(N) { i =>
          val a = A(i)
          if (lst(a) != -1) {
            d = min(d, i - lst(a))
          }
          lst(a) = i
        }
        if (d == inf) out.println(-1)
        else out.println(d + 1)
      }
    }
  }
}

object C1257 {

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

  def main(args: Array[String]): Unit = {
    var t = readInt
    while (t > 0) {
      val n = readInt
      val arr = readInts(n)
      var res = Integer.MAX_VALUE
      val lastPos = cu.Map.empty[Int, Int]
      var i = 0
      while (i < n) {
        if (lastPos.contains(arr(i)) && i - lastPos(arr(i)) >= 1) {
          res = math.min(res, i - lastPos(arr(i)) + 1)
        }
        lastPos(arr(i)) = i
        i += 1
      }
      if (res == Integer.MAX_VALUE)
        res = -1
      out.println(res)
      t -= 1
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  in.next()
  val pair = in.next().foldLeft(0, 0) {
    case ((a, d), 'A') => (a + 1, d)
    case ((a, d), 'D') => (a, d + 1)
    case (acc, _) => acc
  }
  if (pair._1 == pair._2)
    println("Friendship")
  else if (pair._1 > pair._2)
    println("Anton")
  else
    println("Danik")
}

object _734 extends App {
  implicit class Pipe[T](val v: T) extends AnyVal {
    def |>[U](f: T => U): U = f(v)
  }

  val std = scala.io.StdIn
  val _ = std.readLine()
  val line = std.readLine()
  val aCount = line.filter(c => c == 'A').size
  val dCount = line.size - aCount
  (if (aCount > dCount) "Anton"
   else if (dCount > aCount) "Danik"
   else "Friendship") |> print
}

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

object _734A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val s = read[String].toSeq.toMultiSet

    val ans = if (s('A') > s('D')) {
      "Anton"
    } else if (s('A') < s('D')) {
      "Danik"
    } else {
      "Friendship"
    }

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

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

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

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

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

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

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

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

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

import scala.io.StdIn._
object Solution {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val ds = readLine.count(_ == 'D')
    val as = n - ds
    println(if (as == ds) "Friendship" else if (as > ds) "Anton" else "Danik")
  }
}

/**
  * Created by yusaku on 17/06/14.
  */

import scala.io.StdIn

object App {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val s = StdIn.readLine()
    var a, d = 0
    for (c <- s) {
      if (c == 'A') {
        a += 1
      } else {
        d += 1
      }
    }

    if (a > d) {
      print("Anton")
    } else if (d > a) {
      print("Danik")
    } else {
      print("Friendship")
    }
  }
}

import java.util.Scanner

object Main2 extends App {
    val scanner = new Scanner(System.in)
    val gameNumber = scanner.nextInt()
    val gameResults = scanner.next()
    val res = (gameResults.count(_ == 'A'), gameResults.count(_ == 'D')) match {
      case (a, d) if a > d => "Anton"
      case (a, d) if a < d => "Danik"
      case (a, d) if a == d => "Friendship"
    }
    println(res)
}

object Solution extends App {
  val n = readInt
  val gs = readLine

  val a = gs.count(_ == 'A')
  val d = gs.count(_ == 'D')

  if(a == d) {
    println("Friendship")
  } else if(a < d ) {
    println("Danik")
  } else {
    println("Anton")
  }

}

import scala.io.StdIn._

object TaskA extends App {
  readInt()
  val (a, d) = readLine().toSeq.partition(_ == 'A')
  println(if (a.size > d.size) "Anton" else if (a.size < d.size) "Danik" else "Friendship")
}

object ScannerTest {

  def getWinner(games: String): String = {
    val occ = games.groupBy(c => c) mapValues (s => s.length) withDefaultValue 0
    val danikWins = occ('D')
    val antonWins = occ('A')

    if (danikWins > antonWins) "Danik"
    else if (antonWins > danikWins) "Anton"
    else "Friendship"
  }

  def main(args: Array[String]) {
    readLine()
    println(getWinner(readLine()))
  }
}

import scala.io.StdIn._

object M734A {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val an = readLine.count(_ == 'A')
    val dn = n - an
    val winner = if(an == dn) {"Friendship" } else if(an > dn){"Anton"} else {"Danik"}
    println(winner)
  }
}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    val anton = results.count(_ == 'A')
    //val danik = results.length() - anton
    val danik = results.count(_ == 'D')

    if (anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    val anton = results.filter(_ == 'A').length()
    val danik = results.filter(_ == 'D').length()

    if (anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    val anton = results.count(_ == 'A')
    val danik = results.length() - anton

    if (anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    val anton = results.filter(_ == 'A').size
    val danik = results.length() - anton

    if (anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    var anton = 0
    var danik = 0

    results.foreach(c =>
        if(c == 'A') anton+=1
        else danik+=1
    )

    if( anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object CF0734A extends App {
  val n = readInt()
  val str = readLine().split("").toList

  val A = str.filter(_ == "A").size
  val D = str.filter(_ == "D").size

  if(A > D) {
    println("Anton")
  } else if (A < D) {
    println("Danik")
  } else {
    println("Friendship")
  }
}

import scala.io.StdIn

object AntonAndDanik extends App {

  val games = StdIn.readLine().toInt
  val results = StdIn.readLine()
  print(impl(results))

  def impl(results: String): String = {
    var antonWins = 0
    var danikWins = 0
    for (result <- results) {
      if (result == 'A') {
        antonWins += 1
      } else {
        danikWins += 1
      }
    }

    if (antonWins > danikWins) {
      "Anton"
    } else if (danikWins > antonWins) {
      "Danik"
    } else {
      "Friendship"
    }
  }
}

import java.util.Scanner

object Ex extends App {
  val scanner = new Scanner(System.in)
  val n: Int = scanner.nextInt()
  val games: String = scanner.next()
  var a = 0
  var b = 0
  games.foreach(ch => if (ch == 'A') a += 1 else b += 1)
  println(if (a > b) "Anton" else if (a == b) "Friendship" else "Danik")
}

// package codeforces.problemset.p734A

object Main {
  def main(args: Array[String]): Unit = {
    val a = scala.io.Source.stdin.getLines()
    val n = a.next().toInt
    //    println(n)
    val s = a.next()
    //    println(s)
    val x = s.count(_ == 'A')
    val y = s.count(_ == 'D')
    println(if (x > y) "Anton" else if (x < y) "Danik" else "Friendship")

  }
}

import scala.io.StdIn
object AntonDanik extends App
{
    val numOfGames = StdIn.readInt()
    val input = StdIn.readLine()

    val anton = input.filter(_ == 'A').length
    val danik = numOfGames - anton

    if(anton > danik)
    {
        println("Anton")
    }
    else if(anton < danik)
    {
        println("Danik")
    } else println("Friendship")
}

object A734 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = scala.io.StdIn.readLine
    val A = input.count(_=='A')
    val D = input.size - A
    val ans = if(A > D) {
      "Anton"
    }  else if(A < D) {
      "Danik"
    } else {
      "Friendship"
    }
    println(ans)
  }
}

import scala.io.StdIn._
object Solution {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val ds = readLine.count(_ == 'd')
    val as = n - ds
    println(if (as == ds) "Friendship" else if (as > ds) "Anton" else "Danik")
  }
}

object ScannerTest {

  def getWinner(games: String): String = {
    val occ = "AADDA".groupBy(c => c) mapValues (s => s.length) withDefaultValue 0
    val danikWins = occ('D')
    val antonWins = occ('A')

    if (danikWins > antonWins) "Danik"
    else if (antonWins > danikWins) "Anton"
    else "Friendship"
  }

  def main(args: Array[String]) {
    readLine()
    println(getWinner(readLine()))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val pair = in.next().foldLeft(0, 0) {
    case ((a, d), 'A') => (a + 1, d)
    case ((a, d), 'D') => (a, d + 1)
    case (acc, _) => acc
  }
  if (pair._1 == pair._2)
    println("Friendship")
  else if (pair._1 > pair._2)
    println("Anton")
  else
    println("Danik")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val pair = in.next().foldLeft(0, 0) {
    case ((a, d), 'A') => (a + 1, d)
    case ((a, d), 'B') => (a, d + 1)
    case (acc, _) => acc
  }
  if (pair._1 == pair._2)
    println("Friendship")
  else if (pair._1 > pair._2)
    println("Anton")
  else
    println("Danik")
}


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

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach { _ =>
       val nq = readLine.split(" ").map(_.toInt)
       val n = nq.head
       val a = readLine.split(" ").map(_.toLong)
       val d1 = new Array[Long](n + 1)
       val d2 = new Array[Long](n + 1)
       d1(0) = -(300000 + 1)
       d2(0) = 0
       var i = 0
       for (k <- a) {
         d1(i + 1) = max(d1(i), d2(i) + k)
         d2(i + 1) = max(d2(i), d1(i) - k)
         i = i + 1
       }
       println(max(d1(n), d2(n)))
    }
  }
}

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

  val t = readInt()

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

    val (ans1, ans2) = an.foldLeft((0L, 0L)) {
      case ((dp1, dp2), a) => (dp1 max (dp2 - a), dp2 max (dp1 + a))
    }

    val ans = ans1 max ans2

    println(ans)
  }
}

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

  val t = readInt()

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

    val (ans1, ans2) = an.foldLeft((0L, 0L)) {
      case ((dp1, dp2), a) => (dp1 max (dp2 - a), dp2 max (dp1 + a))
    }

    val ans = ans1 max ans2
  }
}


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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val an          = readLine().split(" ").map(_.toInt)
    val bn          = an.zipWithIndex.sorted

    val r = bn.tail.foldLeft((1, bn.head._2)) {
      case ((count, i), (_, j)) if j == i + 1 => (count, j)
      case ((count, _), (_, j))               => (count + 1, j)
    }._1

    if (r <= k) println("YES") else println("NO")
  }
}

import scala.io.StdIn._

object _1557B {

  def main(args: Array[String]): Unit = {
    var t = readInt()
    while (t > 0) {
      t -= 1
      val Array(n, k) = ni();
      val ar = ni()
      val br = ar.zipWithIndex.sorted
//      println(br.mkString(", "));
      var count = 0;
      for(i <- 0 until n - 1)
        if(br(i)._2 + 1 != br(i + 1)._2)count += 1;

      if(count < k)println("Yes");
      else println("No")
    }
  }
  def ni(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }
}

import scala.io.StdIn._

object _1557B {

  def main(args: Array[String]): Unit = {
    var t = readInt()
    while (t > 0) {
      t -= 1
      val Array(n, k) = ni();
      val ar = ni()
      var count = 0;
      for(i <- 0 until n - 1)
        if(ar(i) >= ar(i + 1))count += 1;

      if(count < k)println("Yes");
      else println("No")
    }
  }
  def ni(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }
}

import scala.io.StdIn._

object _1557B {

  def main(args: Array[String]): Unit = {
    var t = readInt()
    while (t > 0) {
      t -= 1
      val Array(n, k) = ni();
      val ar = ni()
      var count = 0;
      for(i <- 0 until n - 1)
        if(ar(i) > ar(i + 1))count += 1;

      if(count < k)println("Yes");
      else println("No")
    }
  }
  def ni(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val an          = readLine().split(" ").map(_.toInt)
    val bn          = an.zipWithIndex.sorted

    val r = bn.tail.foldLeft((0, bn.head._2)) {
      case ((count, i), (_, j)) if j == i + 1 => (count, j)
      case ((count, _), (_, j))               => (count + 1, j)
    }._1

    if (r <= k) println("YES") else println("NO")
  }
}

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

  val t = readInt()

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

    val bm = an.foldLeft(List.empty[List[Int]]) {
      case ((l @ (ap :: _)) :: ls, ac) if ac >= ap => (ac :: l) :: ls
      case (ls, ac)                                => List(ac) :: ls
    }

    val ans = bm.length == k && bm.reverse.flatten.sameElements(an.sorted(Ordering[Int].reverse))

    if (ans) println("YES") else println("NO")
  }
}


object A177 {

  def R = readLine().split(" ").toList map(_.toInt)

  def main(args: Array[String]): Unit = {
        var N = R
        var n = N.head
        var k = N.tail.head

        def helper(acc: Int, sum: Int): Int = {

        if(acc > n)
        {
          sum
        }
        else
        {
            var foo = R
            var a = foo.head
            var b = foo.tail.head
            helper(acc+1, sum+b-a+1)
        }
      }

        var sumX = helper(1,0)
        if(sumX%k == 0)
        {
          println(0)

        }
        else
        {
            println(k-sumX%k)
        }

      }

  }

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

object Segments extends App {

	// scan input
	val scanner = new Scanner( System.in )
	val n = scanner.nextInt
	val k = scanner.nextInt
	val input: ArrayBuffer[(Int,Int)] = ArrayBuffer.empty
	for( i <- 1 to n)
		input += (( scanner.nextInt, scanner.nextInt ))
	val segments = input.sortBy( _._1 ).toIndexedSeq	// sort the segments

	val value = (0 /: segments)( (l,e) => l + e._2 - e._1 + 1 ) 	// check value (total length) of segments

	val moves = ( k - value % k ) % k	// check required moves

	/* not required by test
	// check if there is a place for those moves - check distances between segments and absolute margins
	// minimal and maximal value
	final val MIN_MAX = 10000
	val left = segments.head._1 + MIN_MAX
	val right = MIN_MAX - segments.last._2
	val distance = (left /: segments.sliding( 2 )) ( (d, pair) => d + pair.last._1 - pair.head._2 - 1 ) + right
	// if( distance < moves ) then there is no solution
	*/

	println( moves )
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = (1 to n).map{_ =>
    val r = in.next().split(' ').map(_.toInt)
    r.last - r.head + 1
  }.sum
  val left = data % k
  if (left == 0)
    println(0)
  else
    println(k - left)
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  val N, K = sc.nextInt

  val sum = Stream.fill(N)(- sc.nextInt + sc.nextInt + 1).sum
  val res = (K - sum % K) % K

  out.println(res)
  out.close
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);

  def main(args: Array[String]) {
    var Array(n, k) = READ;
    var s = 0;
      for (i <- 1 to n){
      var Array(a,b) = READ;
      s += b-a+1;
    };
    println(if (s%k == 0) 0 else k-s%k);
  }
}

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

    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val sum = a.map(a0 => a0(1) - a0(0) + 1).sum
    println((k - (sum % k)) % k)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = (1 to n).map{_ =>
    val r = in.next().split(' ').map(_.toInt)
    r.last - r.head + 1
  }.sum
  val left = data % k
  println(k - left)
}