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 = {
    // l <= r
    var l = 0
    var r = 0
    REP(ni()) { _ =>
      val tpe = nc()
      if (tpe == '+') {
        val x, y = ni()
        l = max(l, min(x, y))
        r = max(r, max(x, y))
      } else {
        val h, w = ni()
        if (min(h, w) >= l && max(h, w) >= r) out.println("YES")
        else out.println("NO")
      }
    }
  }

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

  type In = (Seq[String])
  type Out = Seq[String]
  type Data = (String, Int, Int)

  def solve(in: In): Out = {
    val (xs) = in

    val as: Seq[Data] =
      xs.map(_.split(" ") match {case Array(op, x, y) => (op, x.toInt, y.toInt)})

    def loop(lines: Seq[Data], longmax: Int, shortmax: Int, out: Seq[String]): Seq[String] = lines match {
      case Seq() => out
      case line +: rest => line match {
        case ("+", x, y) => loop(rest, longmax max (x max y), shortmax max (x min y), out)
        case ("?", h, w) =>
          val s = if (longmax <= (h max w) && shortmax <= (h min w)) "YES" else "NO"
          loop(rest, longmax, shortmax, out :+ s)
      }
    }

    loop(as, 0, 0, Vector.empty)
  }

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

  def formatIn(i: Input): In       = i.getLines(i.int)
  def formatOut(out: Out): String  = out.mkString("\n")

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  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(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
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  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)
  }
}


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

  override def apply(io: IO): io.type = {
    val inputs = io.read[Seq[Seq[Int]]]
    val ans = inputs.map(solve)
    io.writeLines(ans)
  }

  def solve(input: Seq[Int]) = {
    val table = input
      .groupBy(_%3)
      .mapValues(_.length)
      .withDefaultValue(0)
    val rest = if (table(2) > table(1)) {
      table(1) + (table(2) - table(1))/3
    } else {
      table(2) + (table(1) - table(2))/3
    }
    table(0) + rest
  }
}
/****************************[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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

import java.util
import java.util.Scanner

import scala.io.StdIn

object Btask565 extends App {

  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()

  val q = new util.ArrayList[Int]()

  for (i <- 0 until n) {
    line = new Scanner(StdIn.readLine())
    val q = line.nextInt()
    var x = StdIn.readLine().split(' ').map(_.toInt)

    var count0 = 0
    var count1 = 0
    var count2 = 0

    for (i <- 0 until q) {
      val temp = x(i) % 3
      if (temp == 0) {
        count0 += 1
      }
      if (temp == 1) {
        count1 += 1
      }
      if (temp == 2) {
        count2 += 1
      }
    }
    var result = 0
    if (count1 == count2) {
      result = count0 + ((count1 + count2) / 2)
      println(result)
    } else {
      if (count1 > count2) {
        result = count0 + count2 + ((count1 - count2) / 3)
        println(result)
      } else {
        result = count0 + count1 + ((count2 - count1) / 3)
        println(result)
      }
    }
  }
  }

object CF565B extends App {

  import scala.io.StdIn

  val t = StdIn.readInt
  for (_ <- 0 until t) {
    val n = StdIn.readInt
    val as = StdIn.readLine.split(" ").map(_.toInt)

    val mod3_0 = as.count(_ % 3 == 0)
    val mod3_1 = as.count(_ % 3 == 1)
    val mod3_2 = as.count(_ % 3 == 2)

    val combine1_2 = Math.min(mod3_1, mod3_2)

    val remaining1 = (mod3_1 - combine1_2) / 3
    val remaining2 = (mod3_2 - combine1_2) / 3

    println(mod3_0 + combine1_2 + remaining1 + remaining2)
  }
}

object Main {
  def main(args: Array[String]) {
    val q = readInt
    (1 to q).map(_ => {
      val n = readInt
      val s = readLine.split(" ").map(_.toInt).map(x => x % 3)
      val cnt3 = s.count(_ == 0)
      val cnt1 = s.count(_ == 1)
      val cnt2 = s.count(_ == 2)
      if (cnt1 > cnt2) {
        println(cnt3 + cnt2 + (cnt1 - cnt2) / 3)
      } else {
        println(cnt3 + cnt1 + (cnt2 - cnt1) / 3)
      }
    })
  }
}


object B {

  /** TODO: Check! */
  private val multipleTests: Boolean = true

  def run(testNum: Int): Unit = {
    val n = int()
    val r = (1 to n).map(_ => Seq.fill(5)(int()))

    def winner(i: Int, j: Int): Int =
      if (r(i).zip(r(j)).count { case (a, b) => a < b } >= 3) i else j

    val potential = (1 until n).foldLeft(0) { case (ac, i) => winner(ac, i) }
    val won = (0 until n).count(i => winner(potential, i) == i) == 1
    println(if (won) potential + 1 else -1)
  }

  /** Template. */

  private val onlineJudge = System.getProperty("ONLINE_JUDGE") != null

  def main(args: Array[String]): Unit = {
    val t = if (multipleTests) reader.int() else 1
    (1 to t).foreach(run)
  }

  /** I/O. */

  import java.io._
  import java.nio.file._

  private val inputFileName = "input.txt"
  private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)

  private def string(): String = reader.string()
  private def int(): Int = reader.int()
  private def long(): Long = reader.long()
  private def double(): Double = reader.double()

  final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {
    import java.util.StringTokenizer

    def string(): String = next()
    def line(): String = tokenizer().get.nextToken("\n\r")
    def boolean(): Boolean = next().toBoolean
    def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
    def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
    def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
    def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
    def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
    def float(): Float = next().toFloat
    def double(): Double = next().toDouble
    def bigDecimal(): BigDecimal = BigDecimal(next())
    def lineNumber(): Int = linedDelegate.getLineNumber

    @inline def nextLine(): String = {
      current = None // reset the rest of current line
      delegate.readLine()
    }

    override def hasNext: Boolean = tokenizer().nonEmpty
    override def next(): String = tokenizer().getOrElse(throw new RuntimeException("End of input")).nextToken()
    override def close(): Unit = delegate.close()

    private lazy val linedDelegate = new LineNumberReader(delegate)
    private val tokenizers = Iterator.continually(delegate.readLine())
      .takeWhile(_ != null)
      .map(new StringTokenizer(_))
      .filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

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

  object FastReader {
    import scala.io.Codec

    def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)
    def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {
      Files.newBufferedReader(Paths.get(fileName), codec.charSet)
    }
    def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))
    def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {
      new BufferedReader(new InputStreamReader(inputStream, codec.charSet))
    }
  }
}

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

  val t = readInt()

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

    def compare(i: Int, j: Int): Boolean = (ranks(i) zip ranks(j)).count { case (a, b) => a <= b } >= 3

    val athlete = {
      val i = (1 until n).foldLeft(0) { (i, j) => if (compare(j, i)) j else i }
      (0 until n).forall(j => compare(i, j)) match {
        case true => Some(i)
        case _    => None
      }
    }

    athlete match {
      case Some(i) => println(i + 1)
      case _       => println(-1)
    }
  }
}

import scala.collection.mutable

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

    val t = nextInt
    val res = Array.fill(t)(1)

    case class A(r: Array[Int], idx: Int) extends Comparable[A] {
      override def compareTo(o: A): Int = {
          var i, l, g = 0
          while (i < 5) {
            if (r(i) < o.r(i)) l += 1
            else if (r(i) > o.r(i)) g += 1
            i += 1
          }
          if (l >= 3) -1
          else if (g >= 3) 1
          else 0
      }
    }

    for (test <- 0 until t) {
      val n = nextInt
      val rs = Array.tabulate(n) { i => A(nextInts(5), i) }

      if (n > 1) {
        val pq = new java.util.PriorityQueue[A]
        for (r <- rs) pq.add(r)
        val top = pq.peek()
        var ok = true
        for (i <- rs.indices) {
          if (top.idx != rs(i).idx && top.compareTo(rs(i)) >= 0) {
            ok = false
          }
        }
        if (ok) res(test) = top.idx + 1
        else res(test) = -1
      }

    }

    out.println(res.mkString("\n"))
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n         = readInt()
    val ranks     = Array.fill(n)(readLine().split(" ").map(_.toInt))
    val marathons = ranks.transpose.map(_.zipWithIndex.sorted)

    val counts = Array.fill(n)(0L)
    marathons.foreach { marathon =>
      marathon.indices.foreach { i =>
        val (_, athlete) = marathon(i)
        counts(athlete) += n - i - 1L
      }
    }

    val athlete = {
      val (_, i) = counts.zipWithIndex.maxBy(_._1)

      (0 until n).forall { j =>
        (0 until 5).count(k => ranks(i)(k) <= ranks(j)(k)) >= 3
      } match {
        case true => Some(i + 1)
        case _    => None
      }
    }

    athlete match {
      case Some(i) => println(i)
      case _       => println(-1)
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n         = readInt()
    val ranks     = Array.fill(n)(readLine().split(" ").map(_.toInt))
    val marathons = ranks.transpose.map(_.zipWithIndex.sorted)

    val counts = Array.fill(n)(0)
    marathons.foreach { marathon =>
      marathon.indices.foreach { i =>
        val (_, athlete) = marathon(i)
        counts(athlete) += n - i - 1
      }
    }

    val athlete = {
      val (_, i) = counts.zipWithIndex.maxBy(_._1)

      (0 until n).forall { j =>
        (0 until 5).count(k => ranks(i)(k) <= ranks(j)(k)) >= 3
      } match {
        case true => Some(i + 1)
        case _    => None
      }
    }

    athlete match {
      case Some(i) => println(i)
      case _       => println(-1)
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val ms =
      Array
        .fill(n)(readLine().split(" ").map(_.toInt))
        .transpose
        .map(_.zipWithIndex.sorted)

    val counts = {
      val cs = Array.fill(n)(0)

      ms.foreach { m =>
        m.indices.foreach { i =>
          val (_, athlete) = m(i)
          cs(athlete) += n - i - 1
        }
      }

      cs.zipWithIndex.sortBy(_._1)(Ordering[Int].reverse)
    }

    val (count, athlete) = counts.head

    if (count >= 3 * (n - 1) && counts.tail.forall { case (c, _) => count - c > 2 })
      println(athlete + 1)
    else
      println(-1)
  }
}


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

  val t = readInt()

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

    val status = (an zip an.tail).exists { case (a, b) => a <= b }

    val ans = status match {
      case true => "YES"
      case _    => "NO"
    }

    println(ans)
  }
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach { k =>
       val n = readInt
       val a = readLine.split(" ").map(_.toInt)
       val d = a.sortBy(x => -x)
       if ((d.distinct.size == n) && (d.sameElements(a))) println("NO") else println("YES")
    }
  }
}

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

  val t = readInt()

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

    val count = (an zip bn).count { case (a, b) => a != b }
    val ans   = if ((count + 1) / 2 <= n * (n - 1) / 2 - 1) "YES" else "NO"

    println(ans)
  }
}

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

  val t = readInt()

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

    val count = (an zip bn).count { case (a, b) => a != b }
    val ans   = if (count <= n * (n - 1) / 2 - 1) "YES" else "NO"

    println(ans)
  }
}


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

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

    val A=readLine.split(" ").map(_.toInt)
    val dp=Array.ofDim[Int](2,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))
          }
          dp(i&1)(j)(k)%=mod
        }
      }
    }
    var ans:Int=0
    for(i<-0 to b){
      ans+=dp(n&1)(m)(i)
      ans%=mod
    }
    println(ans)
  }
}

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

    var Array(n,m,b,mod)=readLine.split(" ").map(_.toInt)

    var A=readLine.split(" ").map(_.toInt)
    var dp=Array.ofDim[Int](2,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))
          }
          dp(i&1)(j)(k)%=mod
        }
      }
    }
    var ans:Int=0
    for(i<-0 to b){
      ans+=dp(n&1)(m)(i)
      ans%=mod
    }
    println(ans)
  }
}

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

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

    val A=readLine.split(" ").map(_.toInt)
    var dp=Array.ofDim[Int](2,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))
          }
          dp(i&1)(j)(k)%=mod
        }
      }
    }
    var ans:Int=0
    for(i<-0 to b){
      ans+=dp(n&1)(m)(i)
      ans%=mod
    }
    println(ans)
  }
}

object C544 {
    def main(args: Array[String]) {
      val Array(n, m, b, mod) = readLine.split(" ").map(_.toInt)
      val A = readLine.split(" ").map(_.toInt)
      val dp = Array.ofDim[Int](2, m + 10, b + 10)
      dp(0)(0)(0) = 1
      for (i <- 1 to n) {
        for (j <- 0 to m) {
          for (k <- 0 to b) {
            dp(i & 1)(j)(k) = dp(1 - (i & 1))(j)(k)
            if (j > 0 && k >= A(i - 1)) {
              dp(i & 1)(j)(k) += (dp(i & 1)(j - 1)(k - A(i - 1)))
            }
            dp(i & 1)(j)(k) %= mod
          }
        }
      }
      var ans: Int = 0
      for (i <- 0 to b) {
        ans += dp(n & 1)(m)(i)
        ans %= mod
      }
      println(ans)
    }
  }

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

    var Array(n,m,b,mod)=readLine.split(" ").map(_.toInt)

    var A=readLine.split(" ").map(_.toInt)
    val dp=Array.ofDim[Int](2,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i&1)(j)(k)=dp(1-(i&1))(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i&1)(j)(k)+=(dp(i&1)(j-1)(k-A(i-1)))
          }
          dp(i&1)(j)(k)%=mod
        }
      }
    }
    var ans:Int=0
    for(i<-0 to b){
      ans+=dp(n&1)(m)(i)
      ans%=mod
    }
    println(ans)
  }
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.mutable.ArrayBuffer

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    Integer.parseInt(next)
  }

  def nextLong: Long = {
    java.lang.Long.parseLong(next)
  }

  def lowerBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (!(array(mid) < value)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val (n, m, b, mod) = (nextInt, nextInt, nextInt, nextInt)
    val dp = Array.ofDim[Int](m + 1, b + 1)
    val a: Array[Int] = new Array(n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    dp(0)(0) = 1
    for (k <- 0 until n) {
      for (i <- 0 until m) {
        for (j <- 0 to b) {
          if (j + a(k) <= b) {
            dp(i + 1)(j + a(k)) += dp(i)(j)
            dp(i + 1)(j + a(k)) %= mod
          }
        }
      }
    }
    var res = 0
    for (i <- 0 to b) {
      res += dp(m)(i)
      res %= mod
    }
    out.println(res)
  }

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

/**
 * Created by canoe on 5/17/15.
 */

object CF544A {
  def main(args: Array[String]) {
    val Array(n, m, b, mod) = readLine().split(" ").map(_.toInt)
    val A = readLine().split(" ").map(_.toInt)
    val dp = Array.ofDim[Int](2, m + 8, b + 8)

    dp(0)(0)(0) = 1
    for (i <- 1 to n) {
      for (j <- 0 to m) {
        for (k <- 0 to b) {
          dp(i & 1)(j)(k) = dp(1 - (i & 1))(j)(k)
          if (k >= A(i - 1) && j >= 1) {
            dp(i & 1)(j)(k) += dp(i & 1)(j - 1)(k - A(i - 1))
          }
          dp(i & 1)(j)(k) %= mod
        }
      }
    }

    var answer: Int = 0
    for (i <- 0 to b) {
      answer += dp(n & 1)(m)(i)
      answer %= mod;
    }
    println(answer)
  }
}

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

    var Array(n,m,b,mod)=readLine.split(" ").map(_.toInt)

    var A=readLine.split(" ").map(_.toInt)
    var dp=Array.ofDim[Int](n+10,m+10,b+10)
    //println("hic")
    dp(0)(0)(0)=1
    for (i <- 1 to n){
      for(j <- 0 to m){
        for(k <- 0 to b){
          dp(i)(j)(k)=dp(i-1)(j)(k)
          if(j>0&&k>=A(i-1)){
            dp(i)(j)(k)+=(dp(i)(j-1)(k-A(i-1)))
          }
          dp(i)(j)(k)%=mod
        }
      }
    }
    println(dp(n)(m)(b))
  }
}


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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n = ni()
      var a, b, c = ni()
      val s = ns(n)
      var ans = 0
      val hands = Array.fill[Char](n)('a')
      REP(n) { i =>
        s(i) match {
          case 'R' =>
            if (b > 0) {
              ans += 1
              b -= 1
              hands(i) = 'P'
            }

          case 'P' =>
            if (c > 0) {
              ans += 1
              c -= 1
              hands(i) = 'S'
            }

          case _ =>
            if (a > 0) {
              ans += 1
              a -= 1
              hands(i) = 'R'
            }
        }
      }
      val line = (n + 1) / 2
      val ok = ans >= line
      if (!ok) out.println("NO")
      else {
        out.println("YES")
        REP(n) { i =>
          if (hands(i) == 'a') {
            hands(i) = if (a > 0) {
              a -= 1
              'R'
            } else if (b > 0) {
              b -= 1
              'P'
            } else {
              c -= 1
              'S'
            }
          }
        }
        out.println(hands.mkString)
      }
    }
  }
}

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

  override def apply(implicit io: IO): io.type = repeat {
    val n = io.read[Int]
    var r, p, s = io.read[Int]
    val bob = io.read[String]

    def rock() = when(r > 0) {r -= 1; 'R'}
    def paper() = when(p > 0) {p -= 1; 'P'}
    def scissor() = when(s > 0) {s -= 1; 'S'}

    val ans = Array.fill(n)('X')
    var wins = 0

    for {
      i <- bob.indices
      a <- bob(i) match {
        case 'R' => paper()
        case 'P' => scissor()
        case 'S' => rock()
      }
    } {
      wins += 1
      ans(i) = a
    }

    for {
      i <- ans.indices if ans(i) == 'X'
      a <- rock() orElse paper() orElse scissor()
    } {
      wins -= 1
      ans(i) = a
    }

    if (wins >= 0) {
      io.writeLine("YES").writeLine(ans.mkString)
    } else {
      io.writeLine("NO")
    }
  }
}
/****************************[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(implicit io: IO): io.type
  def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

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

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

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

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

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

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

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

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

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

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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


/**
 * @author tdx
 */
object Main {
  import scala.math._
  import scala.collection.mutable._
  import java.io.{File, FileInputStream, InputStreamReader}
  import java.util.Scanner

  // !!!! CHANGE to LOCAL = true before submit !!!!
    val LOCAL = false
//  val LOCAL = true

  def D(x: => Unit): Unit = {
    if (LOCAL) {
      try {
        x
      } catch {
        case e: Throwable => println("Error: " + e.getLocalizedMessage)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val MOD = (pow(10, 9) + 7).toInt
    val sc = new Scanner(new InputStreamReader(if (LOCAL) new FileInputStream(new File("input")) else System.in))
    val n = sc.nextInt()
    val arr = ArrayBuffer[Int]()
    for (_ <- 1 to n) {
      arr.append(sc.nextInt())
    }

    val sorted = arr.sorted
    var res = 0L

    D(println(sorted))

    for (i <- 0 until n - 1) {
      res = (res + (powMod(2, i + 1, MOD) - 1) * (powMod(2, n - i - 1, MOD) - 1) % MOD * (sorted(i + 1) - sorted(i))) % MOD
      D(println(i, res))
    }

    println(res)
  }

  def powMod(a: Int, p: Int, MOD: Int): Long = {
    if (p == 0)
      1
    else {
      val half = powMod(a, p / 2, MOD)
      val res = half * half % MOD
      if (p % 2 == 1) {
        res * a % MOD
      } else
        res
    }
  }
}

object C extends App {

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

  val Array(n) = readInts(1)
  val xs = readLongs(n).sorted

  val MOD = 1000000007L
  var res = 0L

  var m = 1L
  for (x <- xs) {
    val y = x * (MOD + m - 1) % MOD
    res = (res + y) % MOD
    m = (m * 2) % MOD
  }

  m = 1L
  for (x <- xs.reverse) {
    val y = x * (MOD + m - 1) % MOD
    res = (MOD + res - y) % MOD
    m = (m * 2) % MOD
  }

  println(res)
}

/**
 * @author tdx
 */
object Main {
  import scala.math._
  import scala.collection.mutable._
  import java.io.{File, FileInputStream, InputStreamReader}
  import java.util.Scanner

  // !!!! CHANGE to LOCAL = true before submit !!!!
    val LOCAL = false
//  val LOCAL = true

  def D(x: => Unit): Unit = {
    if (LOCAL) {
      try {
        x
      } catch {
        case e: Throwable => println("Error: " + e.getLocalizedMessage)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val MOD = (pow(10, 9) + 7).toInt
    val sc = new Scanner(new InputStreamReader(if (LOCAL) new FileInputStream(new File("input")) else System.in))
    val n = sc.nextInt()
    val arr = ArrayBuffer[Int]()
    for (_ <- 1 to n) {
      arr.append(sc.nextInt())
    }

    val sorted = arr.sorted
    var res = 0L

    D(println(sorted))

    for (i <- 0 until n - 1) {
      res = (res + (powMod(2, i + 1, MOD) - 1) * (powMod(2, n - i - 1, MOD) - 1) * (sorted(i + 1) - sorted(i))) % MOD
      D(println(i, res))
    }

    println(res)
  }

  def powMod(a: Int, p: Int, MOD: Int): Long = {
    if (p == 0)
      1
    else {
      val half = powMod(a, p / 2, MOD)
      val res = half.asInstanceOf[Long] * half % MOD
      if (p % 2 == 1) {
        res.asInstanceOf[Long] * a % MOD
      } else
        res
    }
  }
}


import scala.io.StdIn._
object A extends App{
  val Array(n,m) = readLine().split(" ").map(_.toInt)
  val cand = for (i <- 0 until m) yield {
    readLine().split(" ").map(_.toLong).zipWithIndex.maxBy(_._1)._2
  }
  val static = cand.groupBy(+_).mapValues(_.length).toSeq
  val mv = static.maxBy(_._2)._2
  println(static.filter(_._2 == mv).minBy(_._1)._1 + 1)
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val votes = Array.fill(m)(readLongs(n))

    val winner1 = votes.map(_.zipWithIndex.map{case(k, v) => (k, n-v-1)}.sortBy(identity).last._2)
    val winner2 = winner1.groupBy(identity).mapValues(_.length).toArray.map{case (x, y) => (y,x)}.sortBy(identity)

    println(n - winner2.last._2)
  }
}

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

import scala.collection.mutable

object A {

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

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

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

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val votes = new Array[Array[Int]](m)
    for (i <- 0 until m) {
      votes(i) = new Array[Int](n)
      for (j <- 0 until n) {
        votes(i)(j) = nextInt
      }
    }
    val res = new Array[(Int, Int)](m)
    for (i <- 0 until m) {
      var max = Int.MinValue
      var ind = -1
      for (j <- 0 until n) {
        if (max < votes(i)(j)) {
          ind = j
          max = votes(i)(j)
        }
      }
      res(i) = (max, ind)
    }
    val fnl = new Array[Int](n)
    for (i <- 0 until m) {
      fnl(res(i)._2) += 1
    }
    val max = fnl.reduceLeft(_ max _)
    for (i <- 0 until n) {
      if (fnl(i) == max) {
        out.println(i + 1)
        return 0
      }
    }
    return 0
  }
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val f = Array.ofDim[Int](m, n)
    for (i <- 0 to m-1) {
      f(i) = readLine().split(" ").map(_.toInt)
    }

    val result = f.map { c => c.zipWithIndex.find(_._1 == c.max).get._2 }
                  .groupBy[Int](c=>c).map { case(c, arr) => (c, arr.length) }
                  .maxBy { case(c, v) => (v, -c) }

    println(result._1+1)
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _570A extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  val data = IndexedSeq.fill(m, n)(nextInt)

  val round1 = data map {votes => votes.indexOf(votes.max)}

  val round2 = round1.groupBy(identity).mapValues(_.size)

  val ranked = round2.toList map {case (candidate, cities) => -cities -> candidate}

  //debug(ranked)

  ranked.min._2 + 1
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object A extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val winners = for {
    i <- 0 until m
  } yield {
    val votes = readLine().split(" ").map(_.toLong)
    votes.zipWithIndex.maxBy(_._1)._2
  }

  val x = winners.groupBy(identity).mapValues(_.length).toSeq
  val max = x.maxBy(_._2)._2
  println(x.filter(_._2 == max).map(_._1).min + 1)
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object Elections {

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

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }

   def main(args: Array[String]) {
     val (can,cities) = readTuple()
     val winners = for {
       i <- 1 to cities
       v = readInts
       m = v.max
       winner = v.indexOf(m)
     } yield winner
     val tmp = winners.groupBy { x => x }.mapValues { _.size }.toList
       .sortBy{ case (cand,votes) => (-votes,cand)}
     //println(tmp)
     println(tmp.head._1 + 1)

   }

}

import java.util.Scanner

object PA extends App {
    var in = new Scanner(System.in)
    val n = in.nextInt()
    val m = in.nextInt()
    val d = Array.ofDim[Int](m, n)
    for{
        i <- 0 until m
        j <- 0 until n
    } d(i)(j) = in.nextInt()
    def maxv(ar:Array[Int]):Int = {
        var v = 0
        var idx = 0
        for(i <- 0 until ar.length if ar(i) > v){
            idx = i
            v = ar(i)
        }
        idx+1
    }
    val sum = Array.fill[Int](111)(0)
    for(i <- d.map(maxv))
        sum(i) += 1
    var ans = 0
    var mv = 0
    for(i <- 0 until sum.length if sum(i) > mv){
        ans = i
        mv = sum(i)
    }
    println(ans)
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val f = Array.ofDim[Int](m, n)
    for (i <- 0 to m-1) {
      f(i) = readLine().split(" ").map(_.toInt)
    }

    val result = f.map { c => c.zipWithIndex.find(_._1 == c.max).get._2 }
                  .groupBy[Int](c=>c).map { case(c, arr) => (c, arr.length) }
                  .maxBy {
                    case(c, v) =>
                      var all = 0
                      for (i <- 0 to m-1) {
                        all += f(i)(c)
                      }
                      (v, all, -c)
                  }

    println(result._1+1)
  }
}

import scala.io.StdIn._

object A extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val total = Array.ofDim[Long](n)

  var globalMax = Long.MinValue
  var globalMaxIdx = 0

  for (i <- 0 until m) {
    val votes = readLine().split(" ").map(_.toInt)
    var maxIdx = 0
    var maxVotes = Long.MinValue

    for (j <- votes.indices) {
      if (votes(j) > maxVotes) {
        maxVotes = votes(j)
        maxIdx = j
      }
    }

    total(maxIdx) += 1
    if (total(maxIdx) > globalMax) {
      globalMax = total(maxIdx)
      globalMaxIdx = maxIdx
    }
  }

  println(globalMaxIdx + 1)
}


object A {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val newLogin = sc.next.toLowerCase
    val len = newLogin.length
    val n = sc.nextInt()
    for (_ <- 1 to n) {
      val s = sc.next
      if (s.length == len && isSimilar(s)) {
        print("No")
        return
      }
    }
    print("Yes")

    def isSimilar(str: String): Boolean = {
      def similarChars(c1: Char, c2: Char): Boolean = {
        if (c1 == c2) true else
          c1 match {
            case 'o' => c2 == '0'
            case '0' => c2 == 'o'
            case '1' => c2 == 'i' || c2 == 'l'
            case 'i' => c2 == '1' || c2 == 'l'
            case 'l' => c2 == 'i' || c2 == '1'
            case _ => false
          }
      }

      newLogin.zip(str.toLowerCase).forall(t => similarChars(t._1, t._2))
    }
  }

}


object CF_531_3_D {

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

  def solve0(in: In): Out = {
    val (n, s) = in
???
  }

  def solve(in: In): Out = {
  val (n, s) = in

  val target = n / 3
  val counts = List('0','1','2').map(i => (i, s.count(_ == i)))

  val replacees = for {
    (char, count) <- counts
    if count > target
    c <- Seq.fill(count - target)(char)
  } yield c

  val replacements = for {
    (char, count) <- counts
    if count < target
    c <- Seq.fill(target - count)(char)
  } yield c

  val (startPairs, endPairs) = replacees.zip(replacements).partition(p => p._1 > p._2)
  val startMap = startPairs.groupBy(_._1).mapValues(_.map(_._2)).withDefaultValue(Seq.empty)
  val endMap = endPairs.groupBy(_._1).mapValues(_.map(_._2).reverse).withDefaultValue(Seq.empty)

  def loop(ps: Map[Char, Seq[Char]], input: List[Char], output: List[Char]): List[Char] = input match {
    case Nil       => output
    case c +: tail => ps(c) match {
      case Seq()               => loop(ps, tail, c :: output)
      case replacement +: rest => loop(ps + (c -> rest), tail, replacement :: output)
    }
  }

    val fromStart = loop(startMap, s.toList, Nil)
    val fromEnd = loop(endMap, fromStart, Nil)
    val result = fromEnd
    result.mkString
  }

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

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).map(_-'0')
    val n = N / 3
    val d = Array.fill[Int](3)(-n)
    REP(N) { i =>
      d(S(i)) += 1
    }

    REP(N) { i =>
      if (d(0) < 0 && S(i) != 0 && d(S(i)) > 0) {
        d(0) += 1
        d(S(i)) -= 1
        S(i) = 0
      }
    }

    REP_r(N) { i =>
      if (d(2) < 0 && S(i) != 2 && d(S(i)) > 0) {
        d(2) += 1
        d(S(i)) -= 1
        S(i) = 2
      }
    }

    // この時点で1以外は+になっている
    // <-の方向で0を1にする
    REP_r(N) { i =>
      if (d(1) < 0 && S(i) == 0 && d(0) > 0) {
        d(1) += 1
        d(0) -= 1
        S(i) = 1
      }
    }

    // ->の方向で2を1にする
    REP(N) { i =>
      if (d(1) < 0 && S(i) == 2 && d(2) > 0) {
        d(1) += 1
        d(2) -= 1
        S(i) = 1
      }
    }

    out.println(S.mkString)
  }

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

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

  def solve(in: In): Out = {
    val (n, s) = in

    val target = n/3
//    val counts = s.groupBy(identity).mapValues(_.length).toSeq.sorted

    val counts = Seq('0','1','2').map(i => (i, s.count(_ == i)))

    val replacees = for {
      (char, count) <- counts
      if count > target
      c <- Seq.fill(count - target)(char)
    } yield c

    val replacements = for {
      (char, count) <- counts
      if count < target
      c <- Seq.fill(target - count)(char)
    } yield c

    val (startPairs, endPairs) = replacees.zip(replacements).partition(p => p._1 > p._2)

    def loop(ps: Seq[(Char, Char)], input: String, output: String): String = ps match {
      case Seq() => output + input
      case Seq((replacee, replacement), _*) =>
        if(input.head == replacee)
          loop(ps.tail, input.tail, output + replacement)
        else
          loop(ps, input.tail, output + input.head)
    }

    val fromStart = loop(startPairs, s, "")
    val fromEnd = loop(endPairs.reverse, fromStart.reverse, "")
    fromEnd.reverse

  }

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


/**
  * Created by octavian on 18/02/2016.
  */
object Selection {

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("src/selection.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/selection.out")))
    var n = readInt()
    val res: BigInt = comb(5, n) + comb(6, n) + comb(7, n)
    println(res)
  }

  def comb(k: Int, n: Int): BigInt = {
    //println("k is: " + k)
    //println("n is: " + n)
    var res: BigInt = 1
    for(i <- (n - k + 1) to n) {
      //println("i is: " + i)
      res *= i
      //println("res became " + res)
    }
    for(i <- 2 to k) {
      //println("i is: " + i)
      res /= i
      //println("res became " + res)
    }
    return res
  }

}

import java.util.Scanner

object problem extends App {
  val in = new Scanner(System.in)
  val n = in.nextLong()
  var res: Long = 0
  res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5
  res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * (n - 5) / 6
  res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * (n - 5) / 6 * (n - 6) / 7
  println(res)
}

import scala.io.StdIn

object SelectionOfPersonnel {

  def main(args: Array[String]) {
    def f(s : BigInt, n : BigInt) : BigInt = {
      if (s == n) n
      else s * f(s + 1, n)
    }
    val n = StdIn.readInt()
    val a = f(n - 4, n) / f(1, 5)
    val b = f(n - 5, n) / f(1, 6)
    val c = f(n - 6, n) / f(1, 7)
    print(a + b + c)
  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer
//import java.math.BigDecimal

object Bitz_F {

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

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int

    val res = comb(n, 5) + comb(n, 6) + comb(n, 7)
    println(res.toLong)

    //---------------------------- parameters reading end ----------------------

  }

  def comb(n: Int, k: Int) = {
//    fact(n) / (fact(k) * fact(n - k))
    factLast(n, k)  / fact(k)
  }
  def fact(v: Int) = {
    var res = 1l;
    for (i <- 2 to v) {
      res *= i
//      db(res)
    }
    res
  }

  def factLast(v:Int, k:Int):BigDecimal = {
    var res = BigDecimal(1);
//    var res = (v-k+1).toDouble / fact(k);
    for (i <- (v-k+1) to v) {
      res *= i
//      db(res)
    }
    res
  }

//
//  def comb2(n: Int, k: Int):Long = {
//    var res = 1L;
//    for(i <- n to n-k by -1 ) {
//      res *= i
//    }
//    res
//  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
321
"""//66715035255088

val t6 = """
624
"""//7147161340917624

}

}

import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

  def C(n: Long, k: Long) = {
    var res = BigInt(1)
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)

    val n = in.nextInt()

    val result = C(n, 5) + C(n, 6) + C(n, 7)

    println(result)
  }
}

/**
  * Created by octavian on 18/02/2016.
  */
object Selection {

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("src/selection.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/selection.out")))
    var n = readInt()
    val res: Long = comb(5, n) + comb(6, n) + comb(7, n)
    println(res)
  }

  def comb(k: Int, n: Int): Long = {
    var res: Long = 1
    for(i <- (n - k + 1) to n) {
      res *= i
    }
    for(i <- 2 to k) {
      res /= i
    }
    return res
  }

}

import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

  def C(n: Long, k: Long) = {
    var res = 1L
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)

    val n = in.nextInt()

    val result = C(n, 5) + C(n, 6) + C(n, 7)

    println(result)
  }
}

import scala.io.StdIn

object SelectionOfPersonnel {

  def main(args: Array[String]) {
    def fact(n : Long) : Long = {
      if (n <= 1) 1
      else n * fact(n - 1)
    }
    def f(s : Long, n : Long) : Long = {
      if (s == n) n
      else s * f(s + 1, n)
    }
    val n = StdIn.readInt()
    val a = f(n - 4, n) / fact(5)
    val b = f(n - 5, n) / fact(6)
    val c = f(n - 6, n) / fact(7)
    print(a + b + c)
  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer
//import java.math.BigDecimal

object Bitz_F {

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

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int

    val res = comb(n, 5) + comb(n, 6) + comb(n, 7)
    println(res)

    //---------------------------- parameters reading end ----------------------

  }

  def comb(n: Int, k: Int) = {
//    fact(n) / (fact(k) * fact(n - k))
    factLast(n, k) / fact(k)
  }
  def fact(v: Int) = {
    var res = 1l;
    for (i <- 2 to v) {
      res *= i
//      println(res)
    }
    res
  }

  def factLast(v:Int, k:Int):Long = {
    var res = 1l;
    for (i <- (v-k+1) to v) {
      res *= i
//      println(res)
    }
    res
  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
321
"""

}

}


import scala.collection._

object A extends App {

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

  val Array(n, l, r, ql, qr) = readInts(5)
  val ws = readInts(n)
  val sums = ws.scan(0)(_ + _)
  val sum = sums.last

  var i = 0
  var minCost = Int.MaxValue
  val half = (n + 1) / 2

  while (i <= n) {
    val j = n - i
    val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < j) (j - i - 1) * qr else if (i > j) (i - j - 1) * ql else 0)
    if (cost < minCost) minCost = cost
    i += 1
  }

  println(minCost)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, l, r, ql, qr) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val leftSum = data.scanLeft(0l){case(acc, el) => acc + el}
  val maxSum = leftSum.last
  println((0 to n).foldLeft(Long.MaxValue) {
    case(acc, i) =>
      val sum = leftSum(i) * l + (maxSum - leftSum(i)) * r
      val res = if ( i > n - i ) (2 * i - n - 1) * ql
        else if ( i < n - i ) (n - 2 * i - 1) * qr
        else 0

      Math.min(acc, sum + res)
  })
}

import scala.collection._

object A extends App {

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

  val Array(n, l, r, ql, qr) = readInts(5)
  val ws = readInts(n)
  val sums = ws.scan(0)(_ + _)
  val sum = sums.last

  var i = 0
  var minCost = Int.MaxValue
  val half = (n + 1) / 2

  while (i <= n) {
    val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i - 1) * qr else (i - half) * ql)
    if (cost < minCost) minCost = cost
    i += 1
  }

  println(minCost)
}

import scala.collection._

object A extends App {

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

  val Array(n, l, r, ql, qr) = readInts(5)
  val ws = readInts(n)
  val sums = ws.scan(0)(_ + _)
  val sum = sums.last

  var i = 0
  var minCost = Int.MaxValue
  val half = n / 2

  while (i <= n) {

    val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i) * qr else (i - half) * ql)

    if (cost < minCost) minCost = cost

    i += 1
  }

  println(minCost)
}

import scala.collection._

object A extends App {

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

  val Array(n, l, r, ql, qr) = readInts(5)
  val ws = readInts(n)
  val sums = ws.scan(0)(_ + _)
  val sum = sums.last

  var i = 0
  var minCost = Int.MaxValue
  val half = (n + 1) / 2

  while (i <= n) {
    val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i) * qr else (i - half) * ql)
    if (cost < minCost) minCost = cost
    i += 1
  }

  println(minCost)
}


//package codeforces.contests._1353

object MostUnstableArray {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)
      println {
        n match {
          case 1 => 0
          case 2 => m
          case _ => 2L * m
        }
      }
    }
  }

}

import scala.io.StdIn.readLine

object A {

  def solution(n: Int, m: Int): Int = n match {
    case 1 => 0
    case 2 => m
    case _ => 2 * m
  }

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

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

import scala.math.max
import scala.math.min
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("problem.in"))),
						new PrintWriter(new File("problem.out"))
					)
				}
			new CF644(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 CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {

	import Main._
	import fScanner._

	// def solve(): Unit = {
	// 	val T = ni()
	// 	for(i <- 0 until T){
	// 	var ans : Int = 1000
	// 		val n = ni()
	// 		var list: List[Int] = List()
	// 		for(j <- 0 until n){
	// 			val cu:Int = ni()
	// 			for( x <- list)
	// 				ans = ans.min( ( cu - x ).max(x - cu) )
	// 			list = cu::	list
	// 		}
	// 		out.println(ans)
	// 	}
	// }

	def solve(): Unit ={
		val T = ni()
		for(i <- 0 until T){
			val n = ni()
			val m = ni()
			n match {
				case 1 =>
					out.println(0)
				case 2 =>
					out.println(m)
				case _ =>
					out.println(2*m)
			}
		}
	}
}

object A extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val r =
      if (n == 1) 0
      else if (n == 2) m
      else 2 * m

    println(r)
  }
}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()

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

    if (n == 1) {
      println(0)
    } else if (n == 2) {
      println(m)
    } else {
      println(m * 2)
    }

  }

}

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

import scala.math.max
import scala.math.min
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("problem.in"))),
						new PrintWriter(new File("problem.out"))
					)
				}
			new CF644(in, out).solve()
			out.flush()
			out.close()
		} catch {
			case e: IOException => e.printStackTrace()
		}
	}

	private[this] val isOnlineJudge = false

	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 CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {

	import Main._
	import fScanner._

	// def solve(): Unit = {
	// 	val T = ni()
	// 	for(i <- 0 until T){
	// 	var ans : Int = 1000
	// 		val n = ni()
	// 		var list: List[Int] = List()
	// 		for(j <- 0 until n){
	// 			val cu:Int = ni()
	// 			for( x <- list)
	// 				ans = ans.min( ( cu - x ).max(x - cu) )
	// 			list = cu::	list
	// 		}
	// 		out.println(ans)
	// 	}
	// }

	def solve(): Unit ={
		val T = ni()
		for(i <- 0 until T){
			val n = ni()
			val m = ni()
			n match {
				case 1 =>
					out.println(0)
				case 2 =>
					out.println(m)
				case _ =>
					out.println(2*m)
			}
		}
	}
}

object A extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val c = n / 2

    val r =
      if (c == 0) 0
      else if (c == 1) m
      else 2 * m

    println(r)
  }
}

object A extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val c = n / 2

    val r =
      if (c == 0) 0
      else if (c == 1) m
      else {
        val ai = m / c
        val a1 = m - ai * (c - 1)

        if (n % 2 == 0) (a1 + ai) * 2 + ai * 2 * (c - 2)
        else a1 * 2 + ai * 2 * (c - 1)
      }

    println(r)
  }
}


object C extends App {

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

  val Array(n) = readInts(1)
  val bs = readLongs(n / 2)
  val as = Array.ofDim[Long](n)

  var l = 0L
  var r = Long.MaxValue

  for (i <- 0 until n / 2) {
    var l2 = l
    var r2 = bs(i) - l2
    if (r2 >= r) {
      r2 = r
      l2 = bs(i) - r2
    }
    as(i) = l2
    as(n - i - 1) = r2
    l = l2
    r = r2
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(as.mkString(" "))
  Console.flush
}

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 B = nal(N / 2)
    val A = Array.ofDim[Long](N)
    var l = 0L
    var r = 1e18.toLong + 9
    REP(N / 2) { i =>
      val b = B(i)

      val l0 = l
      val r0 = b - l0
      if (r0 <= r) {
        l = l0
        r = r0
      } else {
        l = b - r
      }

      A(i) = l
      A(N - 1 - i) = r
    }

    out.println(A.mkString(" "))
  }

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

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

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

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

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

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

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn

object MishkaAndTheLastExam extends App {

  val n = StdIn.readLine().toInt

  println(createA(StdIn.readLine().split(" ").map(_.toLong)))

  def createA(half: Array[Long]): String = {
    val left = mutable.ArrayStack[Long]()
    val right = mutable.ArrayStack[Long]()

    half.foreach(solutionForIth(_, left, right))

    left.reverse.mkString(" ") + " " + right.mkString(" ")
  }

  def solutionForIth(ith: Long, left: mutable.ArrayStack[Long], right: mutable.ArrayStack[Long]) = {

    @tailrec
    def sol(li: Long, ri: Long): Unit = {
      if (left.isEmpty) {
        left.push(li)
        right.push(ri)
        return
      }

      val rtop = right.top
      val ltop = left.top

      if (rtop >= ri && ltop <= li) {
        left.push(li)
        right.push(ri)
        return
      }

      val diff = if (ri > rtop) {
        ri - rtop
      } else {
        ltop - li
      }

      sol(li + diff, ri - diff)
    }

    sol(0, ith)
  }
}

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

object MishkaAndTheLastExam extends App {

  val n = StdIn.readLine().toInt

  println(createA(StdIn.readLine().split(" ").map(_.toLong)))

  def createA(half: Array[Long]): String = {
    val left = mutable.ArrayStack[Long]()
    val right = mutable.ArrayStack[Long]()

    half.foreach(solutionForIth(_, left, right))

    left.reverse.mkString(" ") + " " + right.mkString(" ")
  }

  def solutionForIth(ith: Long, left: mutable.ArrayStack[Long], right: mutable.ArrayStack[Long]) = {

    def sol(li: Long, ri: Long): Unit = {
      if (left.isEmpty) {
        left.push(li)
        right.push(ri)
        return
      }

      val rtop = right.top
      val ltop = left.top

      if (left.nonEmpty && rtop >= ri && ltop <= li) {
        left.push(li)
        right.push(ri)
        return
      }

      if (ri > rtop) {
        sol(li + 1, ri - 1)
      }

    }

    sol(0, ith)
  }
}