object 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 sc = new InputReader(System.in)
    val T = sc.nextInt()
    rep(T) {_ =>
      val N = sc.nextInt()
      val s = sc.next()
      val l = s.take(N / 2)
      val r = s.drop(N / 2).reverse
      val ok = 0 until l.length forall { i =>
        val d = abs(l(i) - r(i))
        d == 0 || d == 2
      }
      out.println(if (ok) "YES" else "NO")
    }
  }

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

object EDU49A extends App {
  import scala.io.StdIn
  val t = StdIn.readInt
  val inputs = (0 until t).map(_ => {
    StdIn.readLine
    StdIn.readLine
  }).toList

  def getNewLetters(char: Char): List[Char] = {
    return List(char+1, char-1).filter(c => c >= 'a' && c <= 'z').map(_.toChar)
  }

  for (input <- inputs) {
    val answer = input.take(input.length/2).zipWithIndex.forall {
      case (c: Char, i: Int) => {
        getNewLetters(c).toSet.intersect(getNewLetters(input(input.length - 1 - i)).toSet).nonEmpty
      }
    }

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

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

object A extends App {

  def solve(in: InputReader): Unit = {
    val t = in.nextInt
    (1 to t) foreach { _ =>
      in.nextInt
      handle(in.next)
    }
  }

  def handle(s: String): Unit = {
    val lhs = s.take(s.length / 2)
    val rhs = s.drop(s.length / 2).reverse

    val result = lhs.zip(rhs).forall { case (l, r) =>
        val nl = neighbors(l)
        val rl = neighbors(r)
        nl.exists(rl.contains)
    }

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

  //97-122

  def neighbors(c: Char): Set[Char] = {
    Seq(c - 1, c + 1).filter(_ >= 97).filter(_ <= 122).map(_.toChar).toSet
  }

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

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

  val Array(n) = readInts(1)

  for (_ <- 1 to n) {
    val Array(l) = readInts(1)
    val s = readLine
    var ok = true
    for (i <- 0 until l / 2) {
      val d = Math.abs(s(i) - s(l - i - 1))
      if (d != 0 && d != 2) ok = false
    }
    println(if (ok) "YES" else "NO")
  }
}


object PhoneNumbers extends App {

  var Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  var s = scala.io.StdIn.readLine()

  val letters = s.toCharArray.sorted.distinct.zipWithIndex.toMap
  val weights = s.toCharArray.sorted.distinct.zipWithIndex.map { case (letter, idx) => (idx, letter)}.toMap

  var smaller = s.take(k).toArray

  var i = k - 1

  if (smaller.length < k) {
    val diff = k - smaller.length
    println(smaller.mkString("") + (weights(0).toString * diff))
  } else {
    while (i >= 0) {
      var current = smaller(i)
      var weight = letters(current)
      var nextWeight = weights.get(weight + 1)
      if (nextWeight.isDefined) {
        smaller(i) = nextWeight.get
        i = 0
      } else {
        smaller(i) = weights(0)
      }

      i -= 1
    }

    println(smaller.mkString(""))
  }
}

import java.util.StringTokenizer

object C extends App {
  val INF = 1 << 30

  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong

  read()
  val n = int()
  val k = int()
  val s = readLine()

  val chars = s.distinct.sorted.toIndexedSeq
  val last = chars.last

  if (k > n) {
    println(s + Array.fill(k-n)(chars(0)).mkString)
  } else {
    val t = s.take(k).toCharArray
    var i = k-1
    while (t(i) == last) {
      t(i) = chars.head
      i -= 1
    }
    t(i) = chars.iterator.find(_ > t(i)).get
    println(t.mkString)
  }

}

import scala.io.StdIn.readLine

/**
  * Solution of the problem: http://codeforces.com/contest/940/problem/C
  */
object cPhoneNumbers {

  def numbers(n: Int, k: Int, t: String):String = {

    val alpha = t.toCharArray.toSet.toList.sorted
    def getNext(c: Char, s: List[Char]): Option[Char] =
      s match {
        case Nil => None
        case x::y::_ if x == c => Some(y)
        case x::_ if x > c => None
        case _ => getNext(c, s.tail)
      }

    def replace(s: List[Char]):String =
      getNext(s.head, alpha) match {
        case None => replace(s.tail)
        case Some(x) => (x::s.tail).mkString
      }

    if (k > t.length) t ++ (for { _ <- 1 to k - t.length} yield alpha.head)
    else {
      val part = replace(t.substring(0, k).reverse.toCharArray.toList).reverse
      part ++ (for { _ <- 1 to k - part.length} yield alpha.head)
    }
  }

  def main(args: Array[String]):Unit = {
    val n::k::Nil = readLine().split(" ").map(_.toInt).toList
    val t = readLine()
    println(numbers(n, k, t))
  }
}

import scala.io.StdIn.readLine

/**
  * Solution of the problem: http://codeforces.com/contest/940/problem/C
  */
object cPhoneNumbers {

  def numbers(n: Int, k: Int, t: String):String = {

    val alpha = t.toCharArray.toSet.toList.sorted
    def getNext(c: Char, s: List[Char]): Option[Char] =
      s match {
        case Nil => None
        case x::y::_ if x == c => Some(y)
        case x::_ if x > c => None
        case _ => getNext(c, s.tail)
      }

    def replace(s: List[Char]):String =
      getNext(s.head, alpha) match {
        case None => replace(s.tail)
        case Some(x) => (x::s.tail).mkString
      }

    if (k > t.length) t ++ (for { _ <- 1 to k - t.length} yield alpha.head)
    else {
      val part = replace(t.reverse.toCharArray.toList).reverse
      part ++ (for { _ <- 1 to k - part.length} yield alpha.head)
    }
  }

  def main(args: Array[String]):Unit = {
    val n::k::Nil = readLine().split(" ").map(_.toInt).toList
    val t = readLine()
    println(numbers(n, k, t))
  }
}

object PhoneNumbers extends App {

  var Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  var s = scala.io.StdIn.readLine()

  val letters = s.toCharArray.sorted.distinct.zipWithIndex.toMap
  val weights = s.toCharArray.sorted.distinct.zipWithIndex.map { case (letter, idx) => (idx, letter)}.toMap

  var smaller = s.take(k).toArray

  var i = k - 1

  if (smaller.length < k) {
    val diff = k - smaller.length
    println(smaller.mkString("") + (weights(0).toString * diff))
  } else {
    while (i >= 0) {
      var current = smaller(i)
      var weight = letters(current)
      var nextWeight = weights.get(weight + 1)
      if (nextWeight.isDefined) {
        smaller(i) = nextWeight.get
      } else {
        smaller(i) = weights(0)
      }

      i -= 1
    }

    println(smaller.mkString(""))
  }
}


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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C446A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 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
  }
}

class C446A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val a = na(n)

    var trip = 0
    a.foreach { f =>
      trip = gcd(f, trip)
    }

//    out.println(trip)

    if(trip > 1) {
      out.println(-1)
    } else {
      val cnt = a.count(f => f == 1)
      if(cnt > 0) {
        out.println(n - cnt)
      } else {
        var mn = 100000
        REP(n) { i =>
          trip = 0
          var j = i
          while (j < n && trip != 1) {
            trip = gcd(a(j), trip)
            j += 1
          }
          if (trip == 1) {
            mn = Math.min(mn, (j - i - 1) + (n - 1))
          }
        }
        out.println(mn)
      }
    }

  }

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

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

import collection.Searching._
import scala.collection.mutable

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

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val nums = readIntLine()

    if (nums.map(BigInt(_)).reduce(_.gcd(_)) != 1) {
      println(-1)
    } else if (nums.contains(1)) {
      var reduced : List[Int] = List()
      reduced ::= nums.head
      for (n <- nums.tail) {
        if (reduced.head != 1 || n != 1) {
          reduced ::= n
        }
      }

      val idxs = reduced.zipWithIndex.filter(_._1 == 1).map(_._2)
      val points = (-1 :: idxs) :+ reduced.length

      println(points.sliding(2).map {case List(l, r) => r - l - 1}.sum)
    } else {
      println(subproblem(nums))
    }
  }

  def subproblem(nums : Array[Int]) : Int = {
    val precalc = Array.ofDim[Int](nums.length, nums.length)
    for (i <- nums.indices) {
      precalc(i)(i) = nums(i).intValue()
      for (j <- i + 1 until nums.length) {
        precalc(i)(j) = BigInt(precalc(i)(j - 1)).gcd(nums(j)).intValue()
      }
    }

    val pair = nums.indices.flatMap {
      i =>
        (i until nums.length).flatMap {
          j =>
            if (precalc(i)(j) == 1) {
              Some((j - i, (i, j)))
            } else {
              None
            }
        }
    }.minBy(_._1)
    pair._1 + nums.length - 1
  }

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

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

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

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

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C446A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 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
  }
}

class C446A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val a = na(n)

    var trip = 0
    a.foreach { f =>
      trip = gcd(f, trip)
    }

//    out.println(trip)

    if(trip > 1) {
      out.println(-1)
    } else {
      val cnt = a.count(f => f == 1)
      if(cnt > 0) {
        out.println(n - cnt)
      } else {
        var mn = 2005
        REP(n) { i =>
          trip = 0
          var j = i
          while (j < n && trip != 1) {
            trip = gcd(a(j), trip)
            j += 1
          }
          if (trip == 1) {
            mn = Math.min(mn, (j - i - 1) + (n - 1))
          }
        }
        out.println(mn)
      }
    }

  }

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

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

import collection.Searching._
import scala.collection.mutable

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

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val nums = readBigIntLine()

    if (nums.reduce(_.gcd(_)) != 1) {
      println(-1)
    } else {

      val precalc = Array.ofDim[Int](nums.length, nums.length)
      for (i <- nums.indices) {
        precalc(i)(i) = nums(i).intValue()
        for (j <- i + 1 until nums.length) {
          precalc(i)(j) = BigInt(precalc(i)(j - 1)).gcd(nums(j)).intValue()
        }
      }

      val pair = nums.indices.flatMap {
        i =>
          (i until nums.length).flatMap {
            j =>
              if (precalc(i)(j) == 1) {
                Some((j - i, (i, j)))
              } else {
                None
              }
          }
      }.minBy(_._1)
      println(pair._1 + nums.length - 1)
    }
  }

  def bfs(s1 : List[Array[BigInt]], s2 : List[Array[BigInt]], seen : mutable.HashSet[Array[BigInt]], count : Int) : Int = {
    s1 match {
      case Nil => bfs(s2, s1, seen, count + 1)
      case item :: rest =>
        if (seen contains item) {
          bfs(rest, s2, seen, count)
        }
        else if (item.toSet.size == 1) {
          count
        } else {
          seen.add(item)
          val neighbors = item.zipWithIndex.sliding(2).flatMap {
            case Array((l, li), (r, ri)) =>
              val gcd = l.gcd(r)
              var n : List[Array[BigInt]] = List()
              if (gcd != l) {
                val newA = Array.ofDim[BigInt](item.length)
                item.copyToArray(newA)
                newA(li) = gcd
                n ::= newA
              }
              if (gcd != r) {
                val newA = Array.ofDim[BigInt](item.length)
                item.copyToArray(newA)
                newA(ri) = gcd
                n ::= newA
              }
              n
          }.toList
          bfs(rest, neighbors ::: s2, seen, count)
        }
    }
  }

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

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

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

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


object Program extends App{
  val input = Array(scala.io.StdIn.readLine(), scala.io.StdIn.readLine())
  val n = input.head.toInt
  val citizens = input.tail.head.split(" ").map(x => x.toInt)
  val max = citizens.max
  val res = citizens.foldLeft(0)((x, y) => x + max - y)
  println(res)
}

import scala.io.StdIn._

object Main extends App {
  readInt()
  val a = readLine().split(" ").map(_.toInt)
  val max = a.max
  val ans = a.foldLeft(0)((sum, x) => sum + (max - x))
  println(ans)
}

object MyApp extends App {
  val n = readLine().toInt
  val citizensWellfare = readLine().split(" ").map(_.toInt)

  var max = 0
  var sum = 0
  for (i <- 0 until citizensWellfare.length) {
    val diff = max - citizensWellfare(i)
    if (diff < 0) {
      val increase = -diff
      sum += increase * i
      max = citizensWellfare(i)
    } else {
      sum += diff
    }
  }
  println(sum)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val answer = in.next().split(' ').map(_.toInt)
  println(answer.max * n - answer.sum)
}

import scala.io.StdIn

object CF {
  def main(args: Array[String]):Unit = {
    val n = readInt()
    val lis = readLine().split("\\s+").map(_.toInt)
    val v_max = lis.max
    val res = lis.map(x => v_max-x).sum
    println(res)
  }
}

object A758 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n).sorted
    val sum = in.sum
    val max = in.max
    println(max*n - sum)
  }

  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._, collection.Searching._

object _758A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val wealth = read[Vector[Int]]
    val m = wealth.max

    write(wealth.map(i => m - i).sum)
  }
}
/****************************[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 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")

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

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

import scala.io.StdIn.readLine

object App {
  def main(args: Array[String]): Unit = {
    readLine()
    val a = readLine().split(" ").map(_.toInt)
    val m = a.max
    var answer = 0
    for (a_n <- a) {
      answer += (m - a_n)
    }

    print(answer)
  }
}

import scala.io.StdIn

/**
  * Created by user on 23.01.2017.
  */
object Solution extends App {
    val stdIn0 = StdIn.readLine();
    val stdIn = StdIn.readLine();

    val arr = stdIn.split(" ").map(_.toInt)
    print(arr.map(arr.max - _).sum)
}

import scala.io.StdIn._

object Main extends App{
  readLine()
  val A = readLine().split(" ").map(_.toInt)
  val max = A.max
  println(A.map(max - _).sum)
}

import java.util.Scanner

import scala.language.postfixOps

object TaskA extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  val as = 0 until n map (_ => sc.nextInt)
  println(as.max * n - as.sum)
}


/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF5A extends App {
  import scala.collection.mutable
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {

    val names = new mutable.HashSet[String]()

    var count = 0
    while (in.hasNext) {
      val s = nextLine
      if (s.startsWith("+")) {
        names += s.substring(1)
      } else if (s.startsWith("-")) {
        names -= s.substring(1)
      } else {
        val arr = s.split(":")
        if (arr.length > 1)
          count += s.split(":")(1).length * names.size
      }
    }

    out.println(count)
  }

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.foldLeft((0, 0)) {
    case((count, set), el) if el.head == '+' => (count, set + 1)
    case((count, set), el) if el.head == '-' => (count, set - 1)
    case((count, set), el) => (count + set * (el.length - el.indexOf(':') - 1), set)
  }
  println(res._1)
}

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

object AChatTraffic extends App {

  val scanner = new Scanner(System.in)

  val input = ArrayBuffer.empty[String]

  while (scanner.hasNext) {
//  (0 until 4) foreach { i =>
    input += scanner.nextLine()
  }

  var visitors = 0
  var result = 0

  input foreach {
    case s if s.contains('+') =>
      visitors += 1
    case s if s.contains('-') =>
      visitors -= 1
    case s if s.contains(':') =>
      val sp = s.split("""\:""", -1)(1)
      result += sp.length * visitors
  }

  println(result)

}

object A5 {

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

  def main(args: Array[String]): Unit = {
    var curr = 0
    var res = 0L
    var in = read
    while(in != null) {
      if(in.startsWith("+"))
        curr += 1
      else if (in.startsWith("-"))
        curr -= 1
      else
        util.Try{in.split(':')(1)}.map(_.length).foreach(a => res += curr * a)
      in = read
    }
    println(res)
  }

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

    @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 Main {
  def main(args: Array[String]) {
    var users = 0
    var sum = 0
    for(line <- scala.io.Source.stdin.getLines()) {
      if (line.startsWith("+")) users += 1
      else if (line.startsWith("-")) users -= 1
      else sum += line.split(":").tail.headOption.map(_.size).getOrElse(0) * users
    }
    println(sum)
  }
}

object P5A {
    def main(args: Array[String]) {
        val (add, remove, send) = ("\\+.*".r, "-.*".r, ".*:(.*)".r)
        var p = 0
        var answer = 0
        while (true) readLine match {
            case add() => p = p + 1
            case remove() => p = p - 1
            case send(s) => answer = answer + p * s.size
            case _ => {println(answer); return}
        }
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.foldLeft((0, Set.empty[String])) {
    case((count, set), el) if el.head == '+' => (count, set + el.tail)
    case((count, set), el) if el.head == '-' => (count, set - el.tail)
    case((count, set), el) => (count + set.size * el.split(':').last.trim.length, set)
  }
  println(res._1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.foldLeft((0, Set.empty[String])) {
    case((count, set), el) if el.head == '+' => (count, set + el.tail)
    case((count, set), el) if el.head == '-' => (count, set - el.tail)
    case((count, set), el) => (count + set.size * el.split(':').last.length, set)
  }
  println(res._1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  println(in.hasNext)
  while (in.hasNext)
    println(in.next())
  println("stop")
  println(in.size)
  val res = in.foldLeft((0, Set.empty[String])) {
    case((count, set), el) if el.head == '+' => (count, set + el.tail)
    case((count, set), el) if el.head == '-' => (count, set - el.tail)
    case((count, set), el) => (count + set.size, set)
  }
  println(res._1)
}


import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

    def printList[A](ls: List[A]) = {
        print(ls.size);
        for (x <- ls) print( " " + x )
        println
    }

    def main(args: Array[String]): Unit = {
        var (nums, zeros) = nextSeq(nextInt).toList partition (_ != 0)
        var (neg, pos) = nums partition (_ < 0)

        if (pos.isEmpty) {
            pos = neg.take(2)
            neg = neg.drop(2)
        }
        if (neg.size % 2 == 0) {
            zeros = neg.head :: zeros
            neg = neg.tail
        }
        printList(neg)
        printList(pos)
        printList(zeros)
    }

    class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
    {
        private var tokenizer = new StringTokenizer("")
        def readLine() = in.readLine()
        def nextToken(): String = {
            while (!tokenizer.hasMoreTokens) {
                val line = readLine
                if (line == null) return null
                tokenizer = new StringTokenizer(line, splitOn)
            }
            tokenizer.nextToken
        }
        def next[A](f: String => A) = f(nextToken)
        def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())
    }

    implicit val tokenizer = new Tokenizer(Console.in)

    def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
    def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
    def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
    def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
    def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =
        (for (i <- 0 until count) yield f())
}

import java.util.Scanner

object A {

  def pr(a:List[Int]) = {
    print(a.length)
    a.foreach(x => print(" "+x))
    println
  }
  def main(args: Array[String]): Unit = {
     var scan = new Scanner(System.in)
     val n = scan.nextInt
     val L = List.fill(n)(scan.nextInt)
     var a:List[Int] = Nil
     var b:List[Int] = Nil
     var c:List[Int] = Nil
     var pos = L.count(_>0)
     for(x <-L ) {
       if (x<0 && a.isEmpty) a = x::a
       else if (x>0 || (x<0 && pos==0 && b.length<2))b=x::b
       else c = x::c

     }
     pr(a);pr(b);pr(c)

  }

}

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

  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ

    var s1 = a filter(_ > 0)
    var s2 = a filter(_< 0)
    var s3 = a filter(_ == 0)
    if (s1.size == 0) {
      s1 = s2.slice(0, 2);
      s2 = s2.slice(2, s2.size);
    }
    if (s2.size%2 == 0) {
      s3 = s3 :+ s2(0);
      s2 = s2.slice(1, s2.size);
    }
    println(s2.size + " " + s2.mkString(" "));
    println(s1.size + " " + s1.mkString(" "));
    println(s3.size + " " + s3.mkString(" "));
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val a = readLine().split(" ").map(_.toInt)
    val neg = a.filter(_ < 0)
    val pos = a.filter(_ > 0)
    val zero = a.filter(_ == 0)

    if (pos.size == 0) {
      if (neg.size % 2 == 0) {
        println( neg.size - 3 + " " + neg.drop(3).mkString(" "))
        println( "2 " + neg.take(2).mkString(" "))
        println( (1 + zero.size) + " " + (neg.drop(2).take(1) ++ zero).mkString(" "))
      } else {
        println( neg.size - 2 + " " + neg.drop(2).mkString(" "))
        println( "2 " + neg.take(2).mkString(" "))
        println( zero.size + " " + zero.mkString(" "))
      }
    } else {
      if (neg.size % 2 == 0) {
        println( neg.size - 1 + " " + neg.drop(1).mkString(" "))
        println( pos.size + " " + pos.mkString(" "))
        println( (1 + zero.size) + " " + (neg.take(1) ++ zero).mkString(" "))
      } else {
        println( neg.size + " " + neg.mkString(" "))
        println( pos.size + " " + pos.mkString(" "))
        println( zero.size + " " + zero.mkString(" "))
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer
object A extends App {
  val n = readLine.toInt
  val a = for(s <- readLine.split(" ")) yield s.toInt
  val t0 = (for(i <- a if i < 0) yield i).toBuffer
  val t1 = (for(i <- a if i > 0) yield i).toBuffer
  val t2 = (for(i <- a if i == 0) yield i).toBuffer
  if(t1.size == 0) {
    for(i <- 1 to 2) {
      t1 += t0(0)
      t0 -= t0(0)
    }
  }
  if(t0.size % 2 == 0) {
    t2 += t0(0)
    t0 -= t0(0)
  }
  print(t0.size)
  for(i <- t0) print(" "+i)
  println
  print(t1.size)
  for(i <- t1) print(" "+i)
  println
  print(t2.size)
  for(i <- t2) print(" "+i)
  println
}

import java.util.StringTokenizer

object _300A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  var pos = a.filter(i => i > 0)
  var neg = a.filter(i => i < 0)
  var zero = a.filter(i => i == 0)

  if (pos.size == 0) {
    pos = neg.take(2)
    neg = neg.drop(2)
  }
  if (neg.size > 1) {
    zero = zero ++ neg.drop(1)
    neg = neg.take(1)
  }

  println(neg.size + " " + neg.mkString(" "))
  println(pos.size + " " + pos.mkString(" "))
  println(zero.size + " " + zero.mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val posCount = data.count(_ > 0)
  val ans = data.foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {
    case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)
    case((f, s, t), el) if (s.isEmpty && el > 0) || (el != 0 && s.size < 2 && posCount == 0) => (f, el :: s, t)
    case((f, s, t), el) => (f, s, el :: t)
  }
  println(ans._1.size + " " + ans._1.mkString(" "))
  println(ans._2.size + " " + ans._2.mkString(" "))
  println(ans._3.size + " " + ans._3.mkString(" "))
}

import scala.collection.JavaConversions._
import scala.collection.mutable._

object Codeforces300A {
    def main(args: Array[String]) {
        var ps = Set[Int]()
        var ns = Set[Int]()
        var zs = Set[Int]()
        val n = scala.io.StdIn.readLine().toInt
        val ar = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        for (i <- 0 until n) {
            if (ar(i) == 0)
                zs.add(ar(i))
            if (ar(i) > 0)
                ps.add(ar(i))
            if (ar(i) < 0)
                ns.add(ar(i))
        }

        if (ns.size % 2 == 0) {
            val t = ns.take(1)
            zs = zs.union(t)
            ns = ns.diff(t)
        }

        if (ps.size == 0) {
            val t = ns.take(2)
            ps = ps.union(t)
            ns = ns.diff(t)
        }

        val s1 = ns.mkString(" ")
        val s2 = ps.mkString(" ")
        val s3 = zs.mkString(" ")
        println(s"${ns.size} ${s1}")
        println(s"${ps.size} ${s2}")
        println(s"${zs.size} ${s3}")
    }
}

object A300 {

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

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

    val neg = a.filter(_ < 0)
    val pos = a.filter(_ > 0)
    val zero = a.filter(_ == 0)

    if(neg.nonEmpty && zero.nonEmpty) {
      if(pos.nonEmpty) {
        solve(neg.take(1), pos, zero ++ neg.takeRight(neg.length-1))
      } else {
        solve(neg.take(1), neg.slice(1,3), zero ++ neg.takeRight(neg.length-3))
      }
    }
  }

  def solve(neg: Array[Int], pos: Array[Int], zero: Array[Int]): Unit = {
    println(s"${neg.length} ${neg.mkString(" ")}")
    println(s"${pos.length} ${pos.mkString(" ")}")
    println(s"${zero.length} ${zero.mkString(" ")}")
  }
  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

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

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

  val N = sc.nextInt
  val A = List.fill(N)(sc.nextInt).sortWith(_ < _)

  def solve(): Unit = {
    val (neg, zeroPos) = A span (_ < 0)
    val pos = zeroPos.tail

    neg match {
      case x :: Nil => {
        out.println(s"1 $x")
        out.println(s"1 ${pos.head}")
        val rest = 0 :: pos.tail
        out.println((rest.size :: rest).mkString(" "))
      }
      case x :: y :: z :: rest => {
        out.println(s"1 $x")
        out.println(s"2 $y $z")
        val other = rest ::: zeroPos
        out.println((other.size :: other).mkString(" "))
      }
      case x :: y :: rest => {
        out.println(s"1 $x")
        out.println(s"1 ${pos.head}")
        val rest = y :: 0 :: pos.tail
        out.println((rest.size :: rest).mkString(" "))
      }
    }
  }

  solve
  out.close
}

import scala.collection.mutable.ArrayBuffer
object A extends App {
  val n = readLine.toInt
  val a = for(s <- readLine.split(" ")) yield s.toInt
  val t0 = (for(i <- a if i < 0) yield i).toBuffer
  val t1 = (for(i <- a if i > 0) yield i).toBuffer
  val t2 = (for(i <- a if i == 0) yield i).toBuffer
  if(t1.size == 0) {
    for(i <- 1 to 2) {
      t1 += t0(0)
      t0 -= t0(0)
      println(t1)
    }
  }
  print(t0.size)
  for(i <- t0) print(" "+i)
  println
  print(t1.size)
  for(i <- t1) print(" "+i)
  println
  print(t2.size)
  for(i <- t2) print(" "+i)
  println
}

import scala.collection.mutable.ArrayBuffer
object A extends App {
  val n = readLine.toInt
  val a = for(s <- readLine.split(" ")) yield s.toInt
  val t0 = (for(i <- a if i < 0) yield i).toBuffer
  val t1 = (for(i <- a if i > 0) yield i).toBuffer
  val t2 = (for(i <- a if i == 0) yield i).toBuffer
  if(t1.size == 0) {
    for(i <- 1 to 2) {
      t1 += t0(0)
      t0 -= t0(0)
    }
  }
  print(t0.size)
  for(i <- t0) print(" "+i)
  println
  print(t1.size)
  for(i <- t1) print(" "+i)
  println
  print(t2.size)
  for(i <- t2) print(" "+i)
  println
}

import java.util.StringTokenizer

object _300A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  var pos = a.filter(i => i > 0)
  var neg = a.filter(i => i < 0)
  var zero = a.filter(i => i == 0)

  if (pos.size == 0) {
    pos = neg.take(2)
    neg = neg.drop(2)
  }
  if (neg.size > 1) {
    zero = neg.drop(1)
    neg = neg.take(1)
  }

  println(neg.size + " " + neg.mkString(" "))
  println(pos.size + " " + pos.mkString(" "))
  println(zero.size + " " + zero.mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {
    case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)
    case((f, s, t), el) if el == 0 => (f, s, el :: t)
    case((f, s, t), el) => (f, el :: s, t)
  }
  println(data._1.size + " " + data._1.mkString(" "))
  println(data._2.size + " " + data._2.mkString(" "))
  println(data._3.size + " " + data._3.mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val posCount = data.count(_ > 0)
  val ans = data.foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {
    case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)
    case((f, s, t), el) if (s.isEmpty && el > 0) || (s.size < 2 && posCount == 0) => (f, el :: s, t)
    case((f, s, t), el) => (f, s, el :: t)
  }
  println(ans._1.size + " " + ans._1.mkString(" "))
  println(ans._2.size + " " + ans._2.mkString(" "))
  println(ans._3.size + " " + ans._3.mkString(" "))
}

import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

    def printList[A](ls: List[A]) = {
        print(ls.size);
        for (x <- ls) print( " " + x )
        println
    }

    def main(args: Array[String]): Unit = {
        var (nums, zeros) = nextSeq(nextInt).toList partition (_ != 0)
        var (neg, pos) = nums partition (_ < 0)
        if (neg.size % 2 == 0) {
            zeros = neg.head :: zeros
            neg = neg.tail
        }
        printList(neg)
        printList(pos)
        printList(zeros)
    }

    class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
    {
        private var tokenizer = new StringTokenizer("")
        def readLine() = in.readLine()
        def nextToken(): String = {
            while (!tokenizer.hasMoreTokens) {
                val line = readLine
                if (line == null) return null
                tokenizer = new StringTokenizer(line, splitOn)
            }
            tokenizer.nextToken
        }
        def next[A](f: String => A) = f(nextToken)
        def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())
    }

    implicit val tokenizer = new Tokenizer(Console.in)

    def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
    def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
    def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
    def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
    def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =
        (for (i <- 0 until count) yield f())
}

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

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

  val N = sc.nextInt
  val A = List.fill(N)(sc.nextInt).sortWith(_ < _)

  def solve(): Unit = {
    val (neg, zeroPos) = A span (_ < 0)
    val pos = zeroPos.tail

    neg match {
      case x :: Nil => {
        out.println(s"1 $x")
        out.println(s"1 ${pos.head}")
        val rest = 0 :: pos.tail
        out.println((rest.size :: rest).mkString(" "))
      }
      case x :: y :: z :: rest => {
        out.println(s"1 $x")
        out.println(s"1 $y $z")
        val other = rest ::: zeroPos
        out.println((other.size :: other).mkString(" "))
      }
      case x :: y :: rest => {
        out.println(s"1 $x")
        out.println(s"1 ${pos.head}")
        val rest = y :: 0 :: pos.tail
        out.println((rest.size :: rest).mkString(" "))
      }
    }
  }

  solve
  out.close
}

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

  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ

    var s1 = a filter(_ > 0)
    var s2 = a filter(_< 0)
    var s3 = a filter(_ == 0)
    if (s1.size == 0) {
      s1 = s2.slice(0, 2);
      s2 = s2.slice(2, s2.size);
    }
    if (s2.size%2 == 0) {
      s3 = s3 :+ s2(0);
      s2 = s2.slice(1, s2.size);
    }
    println(s1.size + " " + s1.mkString(" "));
    println(s2.size + " " + s2.mkString(" "));
    println(s3.size + " " + s3.mkString(" "));

  }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).foldLeft((0, 0)) {
    case((h, timeSoFar), i) =>
      val h1 = in.next().toInt
      (h1, timeSoFar + Math.abs(h - h1))
  }._2 + n - 1 + n)
}

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

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

  def solve(): Long = {
    val N = sc.nextInt
    val H = List.fill(N)(sc.nextLong)

    @tailrec
    def loop(acc: Long, pos: Long, ts: List[Long]): Long = ts match {
        case Nil => acc + 2 * N - 1
        case x :: xs => loop(acc + (pos - x).abs, x, xs)
    }

    loop(0L, 0L, H)
  }

  out.println(solve)
  out.close
}

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

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

  val n = readInt
  val trees = for(_ <- 1 to n) yield readInt
  val ans = trees.sliding(2).map(x => (x.last - x.head).abs).sum + n - 1 + n + trees.head

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

object Main {
  def main(args: Array[String]) = {
    val n = readInt
    val a = (1 to n).map(_ => readInt())

    var h0 = a(0)
    var step = a(0) + 1

    a.drop(1).foreach{ h =>
      if (h0 > h) step += h0 - h + 2
      else step += h - h0 + 2
      h0 = h
    }

    println(step)
  }
}

object CF265B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

  def nextInt = in.nextInt
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve = {
    var n = nextInt
    var h = (for (i <- 0 until n) yield nextInt).toArray

    var c = 0
    var t = -1
    for (i <- 0 until n) {
      t += math.abs(h(i) - c) + 2;
      c = h(i)
    }

    out.println(t)
  }

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).foldLeft((1, 0)) {
    case((h, timeSoFar), i) =>
      val h1 = in.next().toInt
      (h1, timeSoFar + Math.abs(h - h1))
  }._2 + n - 1)
}


object D 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, k, p) = readInts(3)

  val as = readInts(n).sorted
  val bs = readInts(k).sorted

  var min = Int.MaxValue

  for (offset <- 0 to k - n) {

    var max = 0
    var i = 0
    while (i < as.length) {

      val a = as(i)
      val b = bs(offset + i)

      val len = if (a <= p) {
        if (a > b) {
          (p - b) + (a - b) //bap
        } else {
          if (b > p) {
            b - a + b - p // apb
          } else {
            p - a // abp
          }
        }
      } else {
        if (a < b) {
          (b - a) + (b - p)//pab
        } else {
          if (b < p) {
            a - b + p - b //bpa
          } else {
            a - p //pba
          }
        }
      }
      if (len > max) max = len
      //println(offset, i, as(i), bs(j), len, max)
      i += 1
    }

    if (max < min) min = max
  }

  println(min)
}

import scala.io.StdIn

object A830 {
    def main(args: Array[String]) = {
        val Array(n, k, p) = StdIn.readLine().split(" ").map(_.toLong)
        val a = StdIn.readLine().split(" ").map(_.toLong).sorted
        val b = StdIn.readLine().split(" ").map(_.toLong).sorted

        def intervalByT(start: Long, t: Long): Option[Tuple2[Long, Long]] = start match {
            case _ if ((start - p).abs > t) => None
            case start if (start < p) => {
                val dist = (t - (p - start)) / 2
                Some((start - dist, p + dist))
            }
            case start if (start >= p) => {
                val dist = (t - (start - p)) / 2
                Some((p - dist, start + dist))
            }
        }

        def greedy(segments: Array[Tuple2[Long, Long]]): Boolean = {
            var j = 0
            for (i <- 0 until segments.length) {
                while (j < b.length && segments(i)._1 > b(j))
                    j += 1
                if (j == b.length || segments(i)._2 < b(j))
                    return false
                j += 1
            }
            return true
        }

        def binarySearch(left: Long, right: Long): Option[Long] = {
            if (right < left)
                return None
            val med = (left + right) / 2
            val res = a.map(intervalByT(_, med))
            if (res.forall(_.isDefined))
                med match {
                    case med if (greedy(res.flatten.sorted)) =>
                        binarySearch(left, med - 1) match {
                            case None => Some(med)
                            case some => Some(some.get)
                        }
                    case med => binarySearch(med + 1, right)
                }
            else
                binarySearch(med + 1, right)
        }

        println(binarySearch(0, 2 * 1000 * 1000 * 1000).get)
    }
}

object D 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, k, p) = readInts(3)

  val as = readInts(n).sorted
  val bs = readInts(k).sorted

  var min = Int.MaxValue

  for (offset <- 0 until k - n) {

    var max = 0
    var i = 0
    while (i < as.length) {

      val a = as(i)
      val b = bs(offset + i)

      val len = if (a <= p) {
        if (a > b) {
          (p - b) + (a - b) //bap
        } else {
          if (b > p) {
            b - a + b - p // apb
          } else {
            p - a // abp
          }
        }
      } else {
        if (a < b) {
          (b - a) + (b - p)//pab
        } else {
          if (b < p) {
            a - b + p - b //bpa
          } else {
            a - p //pba
          }
        }
      }
      if (len > max) max = len
      //println(offset, i, as(i), bs(j), len, max)
      i += 1
    }

    if (max < min) min = max
  }

  println(min)
}


object B1004 extends App {
  case class LR(l: Int, r: Int) {
    def length = r - l
  }

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

  val (n, m) = {
    val arr = read
    (arr(0), arr(1))
  }

  val result = {
    val arr = new Array[Int](n)
    (0 to n - 1).foreach { i => arr(i) = i % 2 }
    arr
  }

  result foreach print
}

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

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var m = array1(1)
  var answer = Array.ofDim[Int](n)

  var tree = mutable.SortedMap.empty[Int, mutable.HashSet[Tuple2[Int, Int]]]

  for (i <- 0 until m) {
    val d = StdIn.readLine().split(" ").map(_.toInt)
    val k = d(1) - d(0)
    val set = tree.getOrElse(k, mutable.HashSet.empty[Tuple2[Int, Int]])
    set.add(d(0) - 1 -> (d(1) - 1))
    tree.put(k, set)
  }

  var l = 0
  answer.map({el =>
    l = l + 1
    if (l % 2 == 0) 0 else 1
  }).foreach(print)
  /*if (n != 1) {

    var last = 0
    tree.foreach({ case (d, t1) =>
      t1.foreach({ t =>
        var i = t._1
        while (i <= t._2) {
          if (answer(i) == 0) {
            if (last % 2 == 0) answer(i) = 1; else answer(i) = 2
            last = last + 1
          }
          i = i + 1
        }
      })
    })
    answer.map(_ % 2).foreach(print)
  } else {
    println(0)
  }*/
}

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

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var m = array1(1)
  var answer = Array.ofDim[Int](n)

  var tree = mutable.SortedMap.empty[Int, mutable.HashSet[Tuple2[Int, Int]]]

  for (i <- 0 until m) {
    val d = StdIn.readLine().split(" ").map(_.toInt)
    val k = d(1) - d(0)
    val set = tree.getOrElse(k, mutable.HashSet.empty[Tuple2[Int, Int]])
    set.add(d(0) - 1 -> (d(1) - 1))
    tree.put(k, set)
  }

  if (n != 1) {

    var last = 0
    tree.foreach({ case (d, t1) =>
      t1.foreach({ t =>
        var i = t._1
        while (i <= t._2) {
          if (answer(i) == 0) {
            if (last % 2 == 0) answer(i) = 1; else answer(i) = 2
            last = last + 1
          }
          i = i + 1
        }
      })
    })
    answer.map(_ % 2).foreach(print)
  } else {
    println(0)
  }
}

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

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var m = array1(1)
  var answer = Array.ofDim[Int](n)

  var tree = mutable.SortedMap.empty[Int,Tuple2[Int,Int]]

  for (i <- 0 until m) {
    val d = StdIn.readLine().split(" ").map(_.toInt)
    tree.put(d(1) - d(0), d(0) - 1 -> (d(1) - 1))
  }

  if (n != 1) {

    var last = 0
    tree.foreach({ case (d, t) =>
      var i = t._1
      while (i <= t._2) {
        if (answer(i) == 0) {
          if (last % 2 == 0) answer(i) = 1; else answer(i) = 2
          last = last + 1
        }
        i = i + 1
      }
    })
    answer.map(_ % 2).foreach(print)
  } else
    {
      println(0)
    }
}

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

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var m = array1(1)
  var answer = Array.ofDim[Int](n)

  var tree = mutable.SortedMap.empty[Int,Tuple2[Int,Int]]

  for (i <- 0 until m) {
    val d = StdIn.readLine().split(" ").map(_.toInt)
    tree.put(d(1) - d(0), d(0) - 1 -> (d(1) - 1))
  }

  if (n != 1) {

    var last = 0
    tree.foreach({ case (d, t) =>
      var i = t._1
      while (i <= t._2) {
        if (answer(i) == 0) {
          if (last % 2 == 0) answer(i) = 1; else answer(i) = 2
          last = last + 1
        }
        i = i + 1
      }
    })
    answer.map(_ % 2).foreach(println)
  } else
    {
      println(0)
    }
}

object B1004 extends App {
  case class LR(l: Int, r: Int) {
    def length = r - l
  }

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

  val (n, m) = {
    val arr = read
    (arr(0), arr(1))
  }

  val memo = {
    val arr = new Array[Boolean](n)
    (0 to n - 1).foreach { i => arr(i) = false }
    arr
  }

  val result = {
    val arr = new Array[Int](n)
    (0 to n - 1).foreach { i => arr(i) = 0 }
    arr
  }

  val flowers =
    (0 to m - 1)
      .map { _ =>
        val arr = read
        LR(arr(0), arr(1))
      }
      .sortWith(_.length > _.length)
      .foreach { interval =>
        val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))
        pendingDecision.zipWithIndex.foreach { case (v, i) =>
          result(v - 1) = i % 2
          memo(v - 1) = true
        }
      }

  result foreach print
}

object B1004 extends App {
  case class LR(l: Int, r: Int) {
    def length = r - l
  }

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

  val (n, m) = {
    val arr = read
    (arr(0), arr(1))
  }

  val memo = {
    val arr = new Array[Boolean](n)
    (0 to n - 1).foreach { i => arr(i) = false }
    arr
  }

  val result = {
    val arr = new Array[Int](n)
    (0 to n - 1).foreach { i => arr(i) = 0 }
    arr
  }

  val flowers =
    (0 to m - 1)
      .map { _ =>
        val arr = read
        LR(arr(0), arr(1))
      }
      .sortWith((x, y) => x.length > y.length || (x.length == y.length && x.l < y.l))
      .foreach { interval =>
        val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))
        pendingDecision.zipWithIndex.foreach { case (v, i) =>
          result(v - 1) = i % 2
          memo(v - 1) = true
        }
      }

  result foreach print
}

object B1004 extends App {
  case class LR(l: Int, r: Int) {
    def length = r - l
  }

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

  val (n, m) = {
    val arr = read
    (arr(0), arr(1))
  }

  val memo = {
    val arr = new Array[Boolean](n)
    (0 to n - 1).foreach { i => arr(i) = false }
    arr
  }

  val result = {
    val arr = new Array[Int](n)
    (0 to n - 1).foreach { i => arr(i) = 0 }
    arr
  }

  val flowers =
    (0 to m - 1)
      .map { _ =>
        val arr = read
        LR(arr(0), arr(1))
      }
      .sortWith(_.length > _.length)
      .foreach { interval =>
        val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))
        pendingDecision.zipWithIndex.foreach { case (v, i) =>
          result(v - 1) = i % 2
          memo(v - 1) = true
        }
      }

  println(result.toList.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 = {
    REP(ni()) { _ =>
      val k, x = nl()
      val ans = (k - 1) * 9 + x
      out.println(ans)
    }
  }

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

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

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

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

  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 Main {

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val n = std.readLine().toInt
    for (_ <- 0 until n) {
      val values = std.readLine().split(" ")
      val k = values(0).toLong
      val x = values(1).toLong
      println(x + (k-1) * 9 )

    }
  }
}

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 = {
    REP(ni()) { _ =>
      val k, x = nl()
      out.println(x)
    }
  }

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

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

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

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

  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 B670 {

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

  def main(args: Array[String]): Unit = {
    var Array(n, k) = readInts(2)
    val id = readInts(n)
    var i = 1
    while(k > 0) {
      if(k <= i) {
        println(id(k-1))
      }
      k -= i
      i += 1
    }
  }

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

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

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

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

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

}

import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 16 Jun 2016
 */
object B670 extends App {

  def solve() = {
    val reader = new BufferedReader(new InputStreamReader(System.in))
    val Array(n, k): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    val ids: Array[Int] = reader.readLine().split(" ").map(_.toInt)
    var solution: Long = 0L
    var minorIndex: Int = 0
    if (hasExactSquareRoot(8 * k + 1)) {
      val determinant: Long = Math.round(Math.sqrt(8 * k + 1))
      solution = (determinant - 1) / 2
    } else {
      val determinant: Double = Math.sqrt(1L + 8 * k)
      solution = Math.floor((determinant - 1) / 2).toInt
    }
    val sum = (solution * (solution + 1)) / 2
    if (sum == k) {
      minorIndex = (solution - 1).toInt
    } else {
      minorIndex = (k - sum - 1).toInt
    }
    println(ids(minorIndex))
  }

  def hasExactSquareRoot(x: Long): Boolean = {
    val sqrt: Double = Math.sqrt(x)
    val floor: Double = Math.floor(sqrt)
    Math.abs(floor * floor - x) < 1E-9
  }

  solve()

}

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

object _670B extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, k = io[Int]
    val ids = io[Vector, Int](n)
    //debug(ans(2 * 1e9.toInt))
    io += ids(ans(k-1))
  }

  def ans(i: Int) = {
    val m = ((Math.sqrt(8*i.toDouble + 1) - 1)/2).toLong
    //debug(i, m, m*(m + 1)/2)
    (i - m*(m + 1)/2).toInt
  }
}
/****************************[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
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  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 PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).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 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 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 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 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)
  }
  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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  @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]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.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[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toLong - 1)
  val line = in.next().split(' ').map(_.toLong)
  val full = (1l to k + 1).find(i => i * (i + 1) / 2 > k).get - 1
  val index = k - full * (full + 1) / 2
  println(line(index.toInt))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt - 1)
  val line = in.next().split(' ').map(_.toInt)
  val full = (1 to n).find(i => i * (i + 1) / 2 > k).getOrElse(1) - 1
  val index = k - full * (full + 1) / 2
  println(line(index))
}


import scala.io.StdIn
object A {
  def main(args: Array[String]): Unit = {
    var ans:StringBuilder=new StringBuilder()
    var t=StdIn.readInt();
    while(t>0)
      {
        var arr:Array[String]=StdIn.readLine().split(" ");
        var a=Integer.parseInt(arr(0))
        var b=Integer.parseInt(arr(1))
        var i=30;
        var value:Long =0L;
        while(i>=0) {
          if ((a & (1 << i)) != 0 && (b & (1 << i)) != 0) {
            value += (1 << i);
          }
          i -= 1;
        }

        var res=(a^value)+(b^value)

        ans.append(res).append("\n");

        t-=1;
      }
    println(ans.toString());

  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (i <- 1 to t) {
      val s = StdIn.readLine()
      val a = s
        .split(" ")
        .map(_.toInt)
      println(a(0) ^ a(1))
    }
  }
}


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 S = ns(N)
    val INF = 1e6.toInt
    val dp = Array.fill[Int](N + 1,3)(INF)
    val pre = Array.ofDim[Int](N + 1, 3)
    REP(3) { i => dp(0)(i) = 0 }
    val COLOR = "RGB"
    REP(N) { i =>
      // dp(i)(j) -> dp(i + 1)(k)
      REP(3) { j =>
        REP(3) { k =>
          if (i == 0 || j != k) {
            val add = if (COLOR(k) == S(i)) 0 else 1
            val next = dp(i)(j) + add
            if (next < dp(i + 1)(k)) {
              dp(i + 1)(k) = next
              pre(i + 1)(k) = j
            }
          }
        }
      }
    }

    def restore(last: Int): String = {
      val c = Array.ofDim[Char](N)
      var p = last
      REP_r(N) { i =>
        c(i) = COLOR(p)
        p = pre(i + 1)(p)
      }
      c.mkString
    }

    val (ans, last) = dp(N).zipWithIndex.minBy(_._1)
    out.println(ans)
    val restored = restore(last)
//    val changed = 0 until N count { i => restored(i) != S(i) }
//    debug(changed.toString)
    out.println(restored)
  }

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

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

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

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

  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 CF_535_3_D {
// date: 25/01/2019

  type In  = (Int, String)
  type Out = String

  def solve(in: In): Out = {
    val (n, s) = in
    val m = Map('R' -> Seq('G','B'), 'G' -> Seq('B','R'), 'B' -> Seq('G','R'))
    val cols = m.keys.toSet

    def loop(cs: Seq[Char], out: Seq[Char]): Seq[Char] = cs match {
      // end
      case Seq(a) =>              out :+ a
      case Seq(a, b) if a == b => out :+ a :+ m(a)(0)
      case Seq(a, b)           => out :+ a :+ b
      case a +: b +: c +: rest =>
        if (a == b && c == m(a)(0))  loop(m(a)(1) +: c +: rest, out :+ a)
        else if (a == b)             loop(m(b)(0) +: c +: rest, out :+ a)
        else                         loop(cs.tail, out :+ a)
    }

    val res = loop(s.toList, Vector.empty).mkString
    def differences(xs: Seq[Char], ys: Seq[Char]) = (xs, ys).zipped.count(i => i._1 != i._2)
    val diffs = differences(s, res)
    s"$diffs\n$res"
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.nextLine})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}