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

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

    case class pair(var s: Int, var a:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (a == that.a && s == that.s)
                return 0
            if (a > that.s && that.a <= s)
                return 1
            if (a <= that.s && that.a > s)
                return -1
            if (a == that.a) {
                if (s < that.s)
                    return -1
                else
                    return 1
            }
            if (a < that.a)
                return -1
            else
                return 1
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        var n = readLong() - 1L
        val k = readLong()
        var p = 1L
        var ans = 0L
        while (n > 0 && p < k) {
            ans += 1L
            n -= p
            p *= 2L
        }
        if (n > 0) {
            if (n % k != 0L) {
                ans += 1L
                n -= n % k
            }
            ans += (n / k).toLong
        }
        writer.println(ans)
    }
    writer.flush()
}

object B extends App {

  def log2(x: Long): Int = {
    @annotation.tailrec
    def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)
    go(0)
  }

  def updateFiles(n: Long, k: Long): Long = {
    val log2k = log2(k)
    val log2n = log2(n)

    if (log2n <= log2k) log2n
    else {
      val num4k = (1L << log2k) - 1L
      val rem   = n - 1L - num4k

      log2k + (rem + k - 1L) / k
    }
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextLong()
    val k = nextLong()
    val h = updateFiles(n, k)

    out.println(h)
  }

  out.flush()

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

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

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

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

    def nextLine() = in.readLine()

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

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

}

object B extends App {

  def log2(x: Long): Int = {
    @annotation.tailrec
    def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)
    go(0)
  }

  def updateFiles(n: Long, k: Long): Long = (log2(k), log2(n)) match {
    case (log2k, log2n) if log2n <= log2k => log2n
    case (log2k, _)                       =>
      val num4k = (1L << log2k) - 1L
      val rem   = (n - 1L) - num4k

      log2k + (rem + k - 1L) / k
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextLong()
    val k = nextLong()
    val h = updateFiles(n, k)

    out.println(h)
  }

  out.flush()

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

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

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

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

    def nextLine() = in.readLine()

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

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

}

object B extends App {

  def log2(x: Long): Int = {
    @annotation.tailrec
    def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)
    go(0)
  }

  def updateFiles(n: Long, k: Long): Long =
    (log2(k), log2(n - 1L)) match {
      case (log2k, log2n) if log2n <= log2k => log2n
      case (log2k, _)                       =>
        val num4k = (1L << log2k) - 1L
        val rem   = (n - 1L) - num4k

        log2k + (rem + k - 1L) / k
    }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextLong()
    val k = nextLong()
    val h = updateFiles(n, k)

    out.println(h)
  }

  out.flush()

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

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

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

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

    def nextLine() = in.readLine()

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

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

}


object Solution {
  type Point = (Long, Long)

  def main(args: Array[String]) {
    val r = new Reader()
    val n = r.read[Int]
    val ps = r.read[List[Point]](n)

    println(if (ps.length < 3 || solve(ps)) "YES" else "NO")
  }

  def solve(ps: List[Point]) = {
    val q1 :: q2 :: q3 :: _ = ps
    lazy val u = ps.partition(collinear(_, q1, q2))._2
    lazy val v = ps.partition(collinear(_, q1, q3))._2
    lazy val w = ps.partition(collinear(_, q2, q3))._2

    u.length < 3 || v.length < 3 || w.length < 3 ||
      collinear(u) || collinear(v) || collinear(w)
  }

  def collinear(ps: List[Point]): Boolean =
    ps match {
      case p1 :: p2 :: qs => qs.dropWhile(collinear(_, p1, p2)).isEmpty
      case _ => true
    }

  def collinear(p: Point, q: Point, r: Point): Boolean =
     p._1*(q._2 - r._2) + q._1*(r._2 - p._2) + r._1*(p._2 - q._2) == 0
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object A {
    def main(args: Array[String]) {
        var n = scala.io.StdIn.readInt();
        var ps = Array.ofDim[Int](n, 2);
        for(i <- 0 until n){
            ps(i) = scala.io.StdIn.readLine().split(" ").map( _.toInt );
        }

        if(n <= 4) println("YES");
        else{
            var a1 = check(ps, 0, 1);
            var a2 = check(ps, 0, 2);
            var a3 = check(ps, 1, 2);
            var ans = a1 || a2 || a3;
            if(ans) println("YES");
            else println("NO");
        }
    }

    def check(ps: Array[Array[Int]], id1: Int, id2: Int): Boolean = {
        var n = ps.size;
        var on = Array.ofDim[Int](n);
        for(i <- 0 until n){
            if(cross(ps(i), ps(id1), ps(id2)) == 0) on(i) = 1;
        }

        var line = true;
        var b0 = -1;
        var b1 = -1;
        for(i <- 0 until n){
            if(on(i) == 0){
                if(b0 == -1) b0 = i;
                else if(b1 == -1) b1 = i;
                else{
                    if(cross(ps(i), ps(b0), ps(b1)) != 0) line = false;
                }
            }
        }

        return line;
    }

    def cross(p0: Array[Int], p1: Array[Int], p2: Array[Int]): Long = {
        var v0x = p1(0).toLong - p0(0).toLong;
        var v0y = p1(1).toLong - p0(1).toLong;
        var v1x = p2(0).toLong - p0(0).toLong;
        var v1y = p2(1).toLong - p0(1).toLong;
        return v0x * v1y - v0y * v1x;
    }
}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toLong).toList
  val sorted = line.sorted
  val (_, ans) = sorted.zipWithIndex.foldLeft(line, List.empty[String]) {
    case ((l, answer), (el, index)) =>
      val lindex = l.indexOf(el)
      (l.take(lindex) ::: l.drop(lindex + 1), (index until lindex + index).map(i => s"${i + 1} ${i + 2}").toList ::: answer)
  }
  println(ans.reverse.mkString("\n"))
}

object Solution {
  def mrg(x:Vector[Boolean]) = {
    rle(x,0,0).sorted.reverse.headOption
  }
  def rle(x:Vector[Boolean],s:Int,l:Int):Vector[(Int,Int)] = {
    if (x.isEmpty) {
      if (l>0) Vector((l,s)) else Vector.empty[(Int,Int)]
    }
    else if (x.head) rle(x.tail,s,l+1)
    else {
      if (l==0) rle(x.tail,s+1,0)
      else (l,s) +: rle(x.tail,s+l+1,0)
    }
  }
  def gmx(x:Vector[Vector[Int]]) = mrg(x.map(v=>v.length == 2 && v(1) < v(0))).getOrElse((0,0))
  def inv(x:Vector[Int]) = {
    val g = gmx(x.grouped(2).toVector)
    val go = gmx(x.drop(1).grouped(2).toVector)
    if (g._1 > go._1) (g._2*2,g._1*2) else (1+go._2*2,2*go._1)
  }
  def re(x:Vector[Int]):Unit = {
    val g = inv(x)
    if (g._2 > 0) {
      println(s"${g._1+1} ${g._1+g._2}")
      re(flp(x,g))
    }
  }
  def flp(x:Vector[Int],i:(Int,Int)):Vector[Int] = {
    if (i._2 == 0) x else {
      val h = x(i._1)
      val l = x(i._1+1)
      flp(x.updated(i._1,l).updated(i._1+1,h),(i._1+2,i._2-2))
    }
  }
  def main(args: Array[String]) {
    val n = readInt
    val ns = readLine.split(" ").map(_.toInt)
    re(ns.toVector)
  }
}

object B686 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val ai = readInts(n)

    for(i <- 0 until n) {
      val slice = ai.slice(i, n)
      val min = slice.min
      if(slice.head != min) {
        var idx = slice.indexOf(min) + i
        while(idx > i) {
          println(s"${idx} ${idx+1}")

          val temp = ai(idx)
          ai(idx) = ai(idx-1)
          ai(idx-1) = temp

          idx -= 1
        }
      }
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @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 Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _686B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val animals = read[Vector[Int]]
    val ans = solve(animals, 0).map(i => s"${i + 1} ${i + 2}")
    if (ans.isEmpty) io else io.writeAll(ans, "\n")
  }

  def solve(animals: Vector[Int], offset: Int): Seq[Int] = if (animals.isEmpty) {
    Nil
  } else {
    val smallest = animals.min
    val pos = animals.indexOf(smallest)
    //debug(animals, offset, smallest, pos)
    (offset until (offset + pos)).reverse ++ solve(animals.patch(pos, Nil, 1), offset + 1)
  }
}
/****************************[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 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 = t.head.ensuring(t.size == 1)
    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 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
  }
  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 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 toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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(n.min(x, y), n.max(x, y), 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]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, 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
  }
  @inline 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)
  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, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

  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 java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val ans = new Array[(Int, Int)](20000)
    var ind = 0
    //
    for(i <- (1 to n-1).reverse){
      for(j <- 1 to i){
        if(a(j) > a(j+1)){
          ans(ind) = (j, j+1)
          ind += 1
          val tmp = a(j)
          a(j) = a(j+1)
          a(j + 1) = tmp
        }
      }
    }

    for(i <- 0 until ind){
      println(ans(i)._1 + " " + ans(i)._2)
    }
  }
}

object Main{
  def main(args: Array[String]) {

    def step (list: List[Int]): (List[Int], (Int, Int)) = {
      val size = list.size
      for(i <- 0 to size - 2){
        if (list(i) > list(i+1)){
          return (list.updated(i,list(i+1)).updated(i+1,list(i)), (i, i+1))
        }
      }
      (list, (-1, -1))
    }

    val n = scala.io.StdIn.readInt()
    var list = scala.io.StdIn.readLine().split(" ").map(x => x.toInt).toList

    def recSolve(list: List[Int]): Unit ={
      val (l, (a,b)) = step(list)
      if (a != -1) {
        println((a+1) + " " + (b+1))
        recSolve(l)
      }
    }

    recSolve(list)

  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toLong).toList
  val sorted = line.sorted
  val (_, ans) = sorted.zipWithIndex.foldLeft(line, List.empty[String]) {
    case ((l, answer), (el, index)) =>
      val lindex = l.indexOf(el)
      (l.take(lindex) ::: l.drop(lindex + 1), (index until lindex + index).map(i => s"${i + 1} ${i + 2}").reverse.toList ::: answer)
  }
  println(ans.reverse.mkString("\n"))
}

object B686 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val ai = readInts(n)

    for(i <- 0 until n) {
      val slice = ai.slice(i, n)
      val min = slice.min
      if(slice.head != min) {
        var idx = slice.indexOf(min) + i
        while(idx > i) {
          println(s"${idx+1} ${idx}")

          val temp = ai(idx)
          ai(idx) = ai(idx-1)
          ai(idx-1) = temp

          idx -= 1
        }
      }
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @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

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val ans = new Array[(Int, Int)](20000)
    var ind = 0
    //
    for(i <- (2 to n-1).reverse){
      for(j <- 1 to i){
        if(a(j) > a(j+1)){
          ans(ind) = (j, j+1)
          ind += 1
          val tmp = a(j)
          a(j) = a(j+1)
          a(j + 1) = tmp
        }
      }
    }

    for(i <- 0 until ind){
      println(ans(i)._1 + " " + ans(i)._2)
    }
  }
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val ans = new Array[(Int, Int)](20000)
    var ind = 0
    //
    for(i <- 1 to n-1){
      for(j <- i to n-1){
        if(a(j) > a(j+1)){
          ans(ind) = (j, j+1)
          ind += 1
          val tmp = a(j)
          a(j) = a(j+1)
          a(j + 1) = tmp
        }
      }
    }

    for(i <- 0 until ind){
      println(ans(i)._1 + " " + ans(i)._2)
    }
  }
}


object Main {
  def main(args: Array[String]) {
    val n = readInt()
    print("abcd" * (n / 4))
    n % 4 match {
      case 0 =>
      case 1 => print("a")
      case 2 => print("ab")
      case 3 => println("abc")
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val res = "abcd"
  println(res * (n / 4) + res.take(n % 4))
}


import java.util
import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)
  val srcSum = inj.sum
  var visited = new util.HashSet[Seq[Int]]()

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx)._1, idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil, 0)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      val next = cur.next()
      next.foreach(it => visited.add(it.archers))
      q.enqueue(next: _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int], bias: Int) extends Ordered[Entry] {

    val dmgDealt = inj.sum - archers.sum

    override def compare(that: Entry): Int = {
      //-this.bias.compareTo(that.bias)
      //-(this.bias.toDouble + move.toDouble * 0.01).compareTo(that.bias.toDouble + that.move.toDouble * 0.01)
      if (this.bias > that.bias) {
        -1
      } else if (this.bias == that.bias) {
        this.move.compareTo(that.move)
      } else {
        1
      }
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx) if !visited.contains(tmp._1)) yield Entry(tmp._1, move + 1, idx :: trace, this.bias + tmp._2)

    def finished(): Boolean = !archers.exists(_ != -1)

  }

  def shot(a: Seq[Int], idx: Int): (Seq[Int], Int) = {
    val r: Array[Int] = Array(a: _*)
    var bias = 0
    def norm(i: Int) = if (r(i) < 0) {
      bias += math.abs(r(i) + 1)
      r(i) = -1
    }
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    (r.toSeq, bias)
  }

}

object P6D {
    def main(args : Array[String]) {
        val Array(n, a, b) = readLine split ' ' map {_.toInt}
        val h = readLine split ' ' map {_.toInt + 1}
        val hm = h.max + 1
        case class Node(v : Int, from : Int)
        val s = Array.fill(n - 2, hm, hm){Node(Int.MaxValue >>> 1, -1)}
        for (i <- 0 until hm) {
            if (i * b >= h(0)) s(0)(0)(i) = Node(i, -1)
        }
        for {
            i <- 1 until n - 2
            k1 <- 0 until hm
            k2 <- 0 until hm
            k3 <- 0 until hm
            if (k1 * b + k2 * a + k3 * b >= h(i))
            x = s(i - 1)(k1)(k2).v + k3
            if (x < s(i)(k2)(k3).v)
        } s(i)(k2)(k3) = Node(x, k1)
        var answer = (Int.MaxValue, -1, -1)
        for {
            k1 <- 0 until hm
            k2 <- 0 until hm
            if (k1 * b + k2 * a >= h(n - 2))
            if (k2 * b >= h(n - 1))
            x = s(n - 3)(k1)(k2).v
            if (x < answer._1)
        } answer = (x, k1, k2)
        println(answer._1)
        def solve(i : Int, k1 : Int, k2 : Int) {
            if (i < 0) return
            val out = ((i + 2) + " ") * k2
            if (i == 0) println(out.trim) else print(out)
            solve(i - 1, s(i)(k1)(k2).from, k1)
        }
        solve(n - 3, answer._2, answer._3)
    }
}

object main extends App with fastIO {

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

  var dp = Array.fill(20, 20, 20, 20)(Int.MaxValue >> 1)

  def dfs(n :Int, A :Int, B :Int, C :Int) :Int = {

    if (n == 0) return 0
    if (dp(n)(A)(B)(C) < Int.MaxValue / 2) return dp(n)(A)(B)(C)

    val hp = array(n - 1) - (A + C) * b - B * a
    if (hp <= 0) return dfs(n - 1, 0, A, B)

    var res = Int.MaxValue / 2
    if (n > 2) res = res min dfs(n, A + 1, B, C)
    if (n > 1) res = res min dfs(n, A, B + 1, C)
    if (n > 0) res = res min dfs(n, A, B, C + 1)

    dp(n)(A)(B)(C) = res + 1
    res + 1
  }

  def printResult(n :Int, A :Int, B :Int, C :Int) {
    if (n == 0) return

    val hp = array(n - 1) - (A + C) * b - B * a
    if (hp <= 0) return printResult(n - 1, 0, A, B)

    val res = dp(n)(A)(B)(C)
    if (n > 2 && dfs(n, A + 1, B, C) < res) { printResult(n, A + 1, B, C); print((n - 1) + " ") } else
    if (n > 1 && dfs(n, A, B + 1, C) < res) { printResult(n, A, B + 1, C); print(n + " ") } else
    { printResult(n, A, B, C + 1); print((n + 1) + " ") }
  }

  val r = (array(n - 1) + b - 1) / b
  val res = dfs(n - 1, 0, r, 0)

  println(res + r)
  printResult(n - 1, 0, r, 0)
  println(((n - 1) + " ") * r)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def nextInt :Int = { in.nextToken; in.nval.toInt }
  def nextLong :Long = { in.nextToken; in.nval.toLong }
  def nextDouble :Double = { in.nextToken; in.nval.toDouble }
  def readLine = bf.readLine

  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)

  def flush = out.flush
}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      -(archers.sum + move * archers.size).compareTo(that.archers.sum + that.archers.size * move)
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)

    def finished(): Boolean = math.abs(archers.sum) == archers.size

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r: Array[Int] = Array(a: _*)
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      -(archers.sum + move).compareTo(that.archers.sum + that.move)
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)

    def finished(): Boolean = !archers.exists(_ != -1)

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r: Array[Int] = Array(a: _*)
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil, inj.sum)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int], prevSum: Int) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      -(archers.sum + move * (archers.sum - prevSum)).compareTo(that.archers.sum + that.move * (that.archers.sum - that.prevSum))
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace, archers.sum)

    def finished(): Boolean = !archers.exists(_ != -1)

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r: Array[Int] = Array(a: _*)
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      archers.sum + move * archers.size
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)

    def finished(): Boolean = math.abs(archers.sum) == archers.size

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r = a.toArray
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      -(archers.sum + move * archers.size).compareTo(that.archers.sum + that.archers.size * move)
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)

    def finished(): Boolean = !archers.exists(_ != -1)

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r: Array[Int] = Array(a: _*)
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}


object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {
    val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max

    if (ml > n) Seq(-1)
    else {
      val suffix = ls.scanRight(0L)(_ + _)

      if (suffix.head < n) Seq(-1)
      else
        (1 to ls.length).zip(suffix).map {
          case (i, si) => ((n + 1L - si) max i).toInt
        }
    }

  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  println(ps.mkString(" "))
}

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Seq[Long] = {
    val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max

    if (ml > n) Seq(-1)
    else {
      val suffix = ls.scanRight(0L)(_ + _)

      if (suffix.head < n) Seq(-1L)
      else
        (1L to ls.length).zip(suffix).map {
          case (i, si) => (i max (n + 1L- si))
        }
    }

  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  println(ps.mkString(" "))
}

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Option[Seq[Int]] = {
    val suffix = ls.scanRight(0)(_ + _)

    if (suffix.head < n) None
    else
      Some((1 to ls.length).zip(suffix).map {
        case (i, si) => (i max (n + 1 - si))
      })
  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  ps match {
    case None => println("-1")
    case Some(ps) => {
      println(ps.length)
      println(ps.mkString(" "))
    }
  }
}

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {
    val suffix = ls.scanRight(0)(_ + _)

    if (suffix.head < n) Seq(-1)
    else
      (1 to ls.length).zip(suffix).map { case (i, si) => (i max (n + 1 - si)) }
  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  println(ps.mkString(" "))
}

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {
    val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max

    if (ml > n) Seq(-1)
    else {
      val suffix = ls.scanRight(0)(_ + _)

      if (suffix.head < n) Seq(-1)
      else
        (1 to ls.length).zip(suffix).map {
          case (i, si) => (i max (n + 1 - si))
        }
    }

  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  println(ps.mkString(" "))
}


object CF118B {
  def main(args: Array[String]): Unit = {
    val s = readDouble()
    val Array(a, b, c) = readLine().split(" ").map(_.toDouble)
    if (a + b + c == 0) {
      println(s + " 0.0 0.0")
    } else {
      val x = s * (a / (a + b + c))
      val y = s * (b / (a + b + c))
      val z = s * (c / (a + b + c))
      println(x + " " + y + " " + z)
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = readInt
    val Array(a, b, c) = readLine.split(" ").map(_.toInt)
    val sum = a + b + c
    if (sum == 0) {
      println(List(s / 3.0, s / 3.0, s / 3.0).mkString(" "))
    }
    else{
    val fs = sum.toDouble
    val (fa, fb, fc) = (s * a / fs, s * b / fs, s * c / fs)
    println(List(fa, fb, fc).mkString(" "))
    }
  }
}

object CF118B {
  def main(args: Array[String]): Unit = {
    val s = readInt().doubleValue
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)
    if (a + b + c == 0) {
      println(s + " 0.0 0.0")
    } else {
      val x = s * (a / (a + b + c))
      val y = s * (b / (a + b + c))
      val z = s * (c / (a + b + c))
      println(x + " " + y + " " + z)
    }
  }
}

object CF118B {
  def main(args: Array[String]): Unit = {
    val s = readInt().doubleValue
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)
    val max = List(a, b, c).max
    if (max == a && max == b && max == c){
      println(s / 3 + " " + s / 3 + " " + s / 3)
    } else if (max == a && max == b) {
      println(s / 2 + " " + s / 2 + " " + 0)
    } else if (max == b && max == c) {
      println(0 + " " + s / 2 + " " + s / 2)
    } else if (max == c && max == a) {
      println(s / 2 + " " + 0 + " " + s / 2)
    } else if (max == a) {
      println(s + " " + 0 + " " + 0)
    } else if (max == b) {
      println(0 + " " + s + " " + 0)
    } else if (max == c) {
      println(0 + " " + 0 + " " + s)
    }
  }
}


import scala.collection._

object C extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  var as = readInts.distinct

  var bit = 1 << 30

  while (bit > 0) {

    val bs = as.filter(a => (a & bit) != 0)

    if (!bs.isEmpty && bs.reduce(_ & _) % bit == 0) {
      println(bs.size)
      println(bs.mkString(" "))
      exit
    }

    bit >>= 1
  }

}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  var as = readInts.distinct

  var threshold = 1 << 30

  while (threshold > 0) {

    val bs = as.filter(a => (a & threshold) != 0)

    if (!bs.isEmpty && bs.reduce((a, b) => a & b) % threshold == 0) {
      println(bs.size)
      println(bs.mkString(" "))
      exit
    }

    threshold /= 2
  }

}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  val MAX = 1000000000
  var as = Array.fill(n)(scala.util.Random.nextInt % MAX)
  //var as = readInts.distinct
  var bs = Seq[Int]()

  var threshold = 1

  while (!as.isEmpty) {

	val remove = mutable.BitSet(as.size)

	var bit = 1
	while (bit < threshold) {
	  if (!as.indices.exists(i => (as(i) & bit) == 0 && !remove(i))) {
	    as.indices.withFilter(i => (as(i) & bit) != 0).foreach(i => remove += i)
	  }
	  bit *= 2
	}

	var bestCount = 0
	var bestBit = 0

	while (bit <= MAX) {
	  val count = as.indices.count(i => (as(i) & bit) != 0 && !remove(i))
	  if (count > bestCount) {
	    bestCount = count
	    bestBit = bit
	  }
	  bit *= 2
	}

	if (bestBit > 0) bs = as.indices.withFilter(i => (as(i) & bestBit) != 0 && !remove(i)).map(i => as(i))

    threshold *= 2
	as = as.filter(_ >= threshold)
  }

  println(bs.size)
  if (n < 100000) println(bs.mkString(" "))
}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  val MAX = 1000000000
  var as = Array.fill(n)(scala.util.Random.nextInt % MAX)
  //var as = readInts.distinct
  var bs = Seq[Int]()

  var threshold = 1

  while (!as.isEmpty) {

	val remove = mutable.BitSet(as.size)

	var bit = 1
	while (bit < threshold) {
	  if (!as.indices.exists(i => (as(i) & bit) == 0 && !remove(i))) {
	    as.indices.withFilter(i => (as(i) & bit) != 0).foreach(i => remove += i)
	  }
	  bit *= 2
	}

	var bestCount = 0
	var bestBit = 0

	while (bit <= MAX) {
	  val count = as.indices.count(i => (as(i) & bit) != 0 && !remove(i))
	  if (count > bestCount) {
	    bestCount = count
	    bestBit = bit
	  }
	  bit *= 2
	}

	if (bestBit > 0) bs = as.indices.withFilter(i => (as(i) & bestBit) != 0 && !remove(i)).map(i => as(i))

    threshold *= 2
	as = as.filter(_ >= threshold)
  }

  println(bs.size)
  //println(bs.mkString(" "))
}


object A extends App {

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

  val m = readInt
  val stepPos = Array.ofDim[Long](m)

  val stepA = Array.ofDim[Boolean](m)
  val stepPar = Array.ofDim[Int](m)

  var pos = 0L
  for (i <- 0 until m) {
    val t = tokenizeLine
    val typ = t.nextToken.toInt
    if (typ == 1) {
      stepA(i) = true
      stepPar(i) = t.nextToken.toInt
      pos += 1
      stepPos(i) = pos
    } else {
      val l = t.nextToken.toInt
      val c = t.nextToken.toInt
      stepA(i) = false
      stepPar(i) = l
      pos += l * c
      stepPos(i) = pos
    }
  }

  @annotation.tailrec
  def get(q: Long): Int = {
    var i = java.util.Arrays.binarySearch(stepPos, q)
    if (i < 0) i = -1 - i
    if (stepA(i)) stepPar(i)
    else {
      val l = stepPar(i)
      var q2 = ((q - stepPos(i - 1)) % l)
      if (q2 == 0) q2 = l
      get(q2)
    }
  }

  val n = readInt
  val qs = readLongs(n)
  val ans = qs.map(get)
  println(ans.mkString(" "))
}

import java.util.Scanner

object P380A {
    class SerejaSequence (scanner: Scanner) {
        val m = scanner.nextInt()
        val seq = new Array[Int](m)
        val periods = new Array[Long](m + 1)
        val types = new Array[Int](m)

        for (i <- 0 until m) {
            types(i) = scanner.nextInt()
            if (types(i) == 1) {
                seq(i) = scanner.nextInt()
                periods(i + 1) = periods(i) + 1
            }
            else {
                val l = scanner.nextInt()
                val c = scanner.nextInt()
                seq(i) = l
                periods(i + 1) = periods(i) + l * c
            }
        }

        def apply(i: Long): Int = {
            val pos = java.util.Arrays.binarySearch(periods, i)
            val index = if (pos >= 0) pos else -(pos + 2)
            if (types(index) == 1) {
                seq(index)
            }
            else {
                apply((i - periods(index)) % seq(index))
            }
        }
    }

    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val seq = new SerejaSequence(scanner)
        val n = scanner.nextInt()
        val ans = for (i <- 1 to n) yield seq(scanner.nextLong() - 1)
        println(ans.mkString(" "))
    }
}

object A extends App {

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

  val m = readInt
  val stepPos = Array.ofDim[Long](m)

  val stepA = Array.ofDim[Boolean](m)
  val stepPar = Array.ofDim[Int](m)

  var pos = 0L

  for (i <- 0 until m) {
    val t = tokenizeLine
    val typ = t.nextToken.toInt
    if (typ == 1) {
      stepA(i) = true
      stepPar(i) = t.nextToken.toInt
      pos += 1
      stepPos(i) = pos
    } else {
      val l = t.nextToken.toInt
      val c = t.nextToken.toInt
      stepA(i) = false
      stepPar(i) = l
      pos += l * c
      stepPos(i) = pos
    }
  }

  @annotation.tailrec
  def get(q: Long): Int = {
    var i = java.util.Arrays.binarySearch(stepPos, q)
    if (i < 0) i = -1 - i
    if (stepA(i)) stepPar(i)
    else {
      val l = stepPar(i)
      var q2 = ((q - stepPos(i - 1)) % l)
      if (q2 == 0) q2 = l
      get(q2)
    }
  }

  val n = readInt
  val qs = readLongs(n)
  val ans = qs.map(get)
  println(ans.mkString(" "))
}

import java.util.Scanner

object P380A {
    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val m = scanner.nextInt()
        val list = scala.collection.mutable.ListBuffer[Int]()
        for (stage <- 1 to m) {
            val t = scanner.nextInt()
            if (t == 1) {
                val num = scanner.nextInt()
                list += num
            }
            else {
                val l = scanner.nextInt()
                val c = scanner.nextInt()
                val addList = list.toList.take(l)
                for (i <- 1 to c) list ++= addList
            }
        }
        val n = scanner.nextInt()
        val ans = list.toList.take(n)
        println(ans.mkString(" "))
    }
}


//package me.jetblack.codeforces

import java.util.Scanner

object A8Train extends App {

  val scanner = new Scanner(System.in)
  val a = scanner.next()
  val b = scanner.next()
  val c = scanner.next()

  val r1 = solve(a)
  val r2 = solve(a.reverse)

  if (r1 && r2) {
    println("both")
  } else if (r1) {
    println("forward")
  } else if (r2) {
    println("backward")
  } else {
    println("fantasy")
  }

  def solve(s: String): Boolean = {
    s.contains(b) && s.contains(c) && s.replaceFirst(b, "").contains(c) && s.indexOf(b) < s.lastIndexOf(c)
  }

}

object P8A {
    import io.StdIn._

    def main(args:Array[String]) {
        val (s, s1, s2) = (readLine, readLine, readLine)
        val b1 = (s1 + ".*" + s2).r.findFirstMatchIn(s).nonEmpty
        val (s1r, s2r) = (s1.reverse, s2.reverse)
        val b2 = (s2r + ".*" + s1r).r.findFirstMatchIn(s).nonEmpty
        println(() match {
            case _ if b1 && b2 => "both"
            case _ if b1 => "forward"
            case _ if b2 => "backward"
            case _ => "fantasy"
        })
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val reverse = str.reverse
//  println(reverse)
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val blast = str.lastIndexOf(b1)
  val bfirst = reverse.indexOf(a1)
  val alast = reverse.lastIndexOf(b1)
//  println(afirst)
//  println(blast)
//  println(bfirst)
//  println(alast)

  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = bfirst != -1 && alast != -1 && alast >= bfirst + a1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object P7E {
    import io.StdIn._

    def main(args:Array[String]) {
        val (s, s1, s2) = (readLine, readLine, readLine)
        val b1 = (s1 + ".*" + s2).r.findFirstMatchIn(s).nonEmpty
        val (s1r, s2r) = (s1.reverse, s2.reverse)
        val b2 = (s2r + ".*" + s1r).r.findFirstMatchIn(s).nonEmpty
        println(() match {
            case _ if b1 && b2 => "both"
            case _ if b1 => "forward"
            case _ if b2 => "backward"
            case _ => "fantasy"
        })
    }
}

object A8 {

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

  def main(args: Array[String]): Unit = {
    val s = read
    val a = read
    val b = read

    val forward = check(s, a, b)
    val backward = check(s.reverse, a, b)

    if(forward && backward) {
      println("both")
    } else if(forward) {
      println("forward")
    } else if(backward) {
      println("backward")
    } else {
      println("fantasy")
    }
  }

  def check(str: String, d: String, e: String): Boolean = {
    val f = str.indexOf(d)
    if(f != -1) {
      if(str.indexOf(e, f+d.length) != -1) {
        true
      } else {
        false
      }
    } else {
      false
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @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 P7E {
    import io.StdIn._

    def main(args:Array[String]) {
        val (s, s1, s2) = (readLine, readLine, readLine)
        val b1 = (s1 + ".*" + s2).r.findFirstMatchIn(s).nonEmpty
        val b2 = (s2 + ".*" + s1).r.findFirstMatchIn(s).nonEmpty
        println(() match {
            case _ if b1 && b2 => "both"
            case _ if b1 => "forward"
            case _ if b2 => "backward"
            case _ => "fantasy"
        })
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val bfirst = str.indexOf(b1)
  val alast = str.lastIndexOf(a1)
  val blast = str.lastIndexOf(b1)
  val here = afirst != -1 && blast != -1 && blast > afirst + a1.length
  val there = alast != -1 && bfirst != -1 && alast > bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val bfirst = str.indexOf(b1)
  val alast = str.lastIndexOf(a1)
  val blast = str.lastIndexOf(b1)
  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = alast != -1 && bfirst != -1 && alast > bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val reverse = str.reverse
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val blast = str.lastIndexOf(b1)
  val bfirst = reverse.length - reverse.indexOf(b1.reverse)
  val alast = reverse.length - reverse.lastIndexOf(a1.reverse)
//  println(bfirst)
//  println(alast)
//  println(bfirst)
//  println(alast)

  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = alast != -1 && bfirst != -1 && alast >= bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val reverse = str.reverse
//  println(reverse)
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val blast = str.lastIndexOf(b1)
  val bfirst = reverse.indexOf(a1)
  val alast = reverse.lastIndexOf(b1)
//  println(afirst)
//  println(blast)
//  println(bfirst)
//  println(alast)

  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = bfirst != -1 && alast != -1 && alast >= bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val reverse = str.reverse
  println(reverse)
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val blast = str.lastIndexOf(b1)
  val bfirst = reverse.indexOf(b1)
  val alast = reverse.lastIndexOf(a1)
//  println(afirst)
//  println(blast)
//  println(bfirst)
//  println(alast)

  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = bfirst != -1 && alast != -1 && alast >= bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val bfirst = str.indexOf(b1)
  val alast = str.lastIndexOf(a1)
  val blast = str.lastIndexOf(b1)
  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = alast != -1 && bfirst != -1 && alast >= bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object A8 {

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

  def main(args: Array[String]): Unit = {
    val s = read
    val a = read
    val b = read

    def check(str: String, d: String, e: String): Boolean = {
      val f = str.indexOf(d)
      if(f != -1) {
        if(s.indexOf(e, f+a.length) != -1) {
          true
        } else {
          false
        }
      } else {
        false
      }
    }

    val forward = check(s, a, b)
    val backward = check(s.reverse, a, b)

    if(forward && backward) {
      println("both")
    } else if(forward) {
      println("forward")
    } else if(backward) {
      println("backward")
    } else {
      println("fantasy")
    }

  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @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 P8A {
    import io.StdIn._

    def main(args:Array[String]) {
        val (s, s1, s2) = (readLine, readLine, readLine)
        val b1 = (s1 + ".*" + s2).r.findFirstMatchIn(s).nonEmpty
        val b2 = (s2 + ".*" + s1).r.findFirstMatchIn(s).nonEmpty
        println(() match {
            case _ if b1 && b2 => "both"
            case _ if b1 => "forward"
            case _ if b2 => "backward"
            case _ => "fantasy"
        })
    }
}


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

  val t = readInt()

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

    val ans =
      if (n % 2 == 0) {
        val b = an.zipWithIndex.exists { case (a, i) => (i + 1) % 2 == 0 && a % 2 == 0 }
        if (b) 2 else 1
      } else {
        val r = an.zipWithIndex.exists { case (a, i) => (i + 1) % 2 == 1 && a % 2 == 1 }
        if (r) 1 else 2
      }

    println(ans)
  }
}

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

import scala.annotation.tailrec

object A {
  def solve(in: Input, out: PrintWriter): Unit = {
    for (_ <- 0 until in.nextInt()) {
      in.nextInt()
      val str = in.nextToken()
      if (str.length % 2 == 0) {
        out.println(if ((0 until str.length).exists(i => i % 2 == 1 && (str(i) - '0') % 2 == 0)) 2 else 1)
      } else {
        out.println(if ((0 until str.length).exists(i => i % 2 == 0 && (str(i) - '0') % 2 == 1)) 1 else 2)
      }
    }
  }

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("4\n1\n2\n1\n3\n3\n102\n4\n2069", "2\n1\n1\n2", "Sample"),
    ("1\n5\n22222", "2", "T1"),
    ("1\n5\n22122", "1", "T2"),
    ("1\n6\n111111", "1", "T3"),
    ("1\n6\n111112", "2", "T4"),
  )

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

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

import scala.collection.mutable.ArrayBuffer

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val n       = in.nextInt()
      val digits  = in.nextLine().toString.split("").map(_.toInt)
      val hasOdd  = digits.indices.exists(i => i % 2 == 0 && digits(i) % 2 == 1)
      val hasEven = digits.indices.exists(i => i % 2 == 1 && digits(i) % 2 == 0)

      if ((n % 2 == 0 && !hasEven) || (n % 2 == 1 && hasOdd)) println("1") else println("2")

    }
    /*
    inputLines.times {
      val n      = in.nextInt()
      val digits = in.nextInt()
      if (n % 2 == 0) {
        val nums        = digits.toString.split("").map(_.toInt)
        val hasOddCount = nums.indices.count(i => i % 2 == 1 && nums(i) % 2 == 1)
        if (hasOddCount == (n / 2)) println("1") else println("2")
      } else if (n == 1) {
        if (digits % 2 == 0) {
          println("2")
        } else {
          println("1")
        }
      } else {
        val nums   = digits.toString.split("").map(_.toInt)
        val hasOdd = nums.indices.exists(i => i % 2 == 0 && nums(i) % 2 == 1)
        if (hasOdd) println("1") else println("2")
      }
    }*/
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(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))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).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 next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

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


import java.util.Scanner

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

  def main(args: Array[String]): Unit = {
    val n = sc.nextInt()
    val res = new StringBuilder()

    for (i <- 1 to n) {
      if (res.size < 2) {
        res.append("a")
      } else {
        val newChar = if (res.charAt(i - 3) == 'a') 'b' else 'a'
        res.append(newChar)
      }
    }

    print(res.toString())
  }
}

object B 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)
  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(("aabb" * (n / 4 + 4)).take(n))

  Console.flush
}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n = read[Int]
    val phrase = Seq("aab", "baa", "bba", "abb").mkString
    val q = n/phrase.length
    val r = n%phrase.length
    val ans = phrase*q + phrase.take(r)
    //require(ans.sliding(3).forall(s => s != s.reverse))
    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
    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])
    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 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")

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