import scala.io.StdIn._

object _519_B extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)
  val B = readLine().split(" ").map(_.toInt)
  val C = readLine().split(" ").map(_.toInt)

  val answer1 = A.diff(B)(0)
  val diff = A.diff(C)
  val answer2 = if (diff(0) !=  answer1) diff(0) else diff(1)

  println(answer1)
  println(answer2)
}

import scala.collection.mutable.HashMap

object CompilationErrors{
    def main(args : Array[String]){
        var n : String = readLine
        var one : Array[Int] = readLine.split(" ").map(_.toInt)
        var two : Array[Int] = readLine.split(" ").map(_.toInt)
        var three : Array[Int] = readLine.split(" ").map(_.toInt)
        (one diff two).foreach(println)
        (two diff three).foreach(print)
    }
}

object Main extends App {

   def diff(a: List[Long], b: List[Long]): Long = (a zip b :+ 0L).dropWhile({ case (a1, b1) => a1 == b1 }).head._1

   readLong
   val a = readLine.split(" ").filterNot(_ == "").map(_.toLong).toList.sorted
   val b = readLine.split(" ").filterNot(_ == "").map(_.toLong).toList.sorted
   val c = readLine.split(" ").filterNot(_ == "").map(_.toLong).toList.sorted

   println(diff(a,b))
   println(diff(b,c))

}

import scala.io.Source

/**
 * Created by kgribov on 05/03/15.
 */
object Problem519B {
  def main(args: Array[String]) {
    val lines = Source.stdin.getLines();
    lines.next()
    val linesNumber = 3
    val arr = new Array[Int](linesNumber)

    for (a <- 0 until linesNumber) {
      for (st <- lines.next().split(" ")) {
        arr(a) += Integer.parseInt(st)
      }
    }
    println(arr(0) - arr(1))
    println(arr(1) - arr(2))
  }
}

import java.io._

object Main {

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

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val a = in.readLine().split(" +").map(_.toInt)
    val b = in.readLine().split(" +").map(_.toInt)
    val c = in.readLine().split(" +").map(_.toInt)

    out.println((a diff b)(0))
    out.println((b diff c)(0))

    out.close()
  }

}

import scala.io.StdIn

object Main extends App {
	StdIn.readLine()

	lazy val errors: Array[Int] = StdIn.readLine().split(" ").map(_.toInt)
	lazy val fix1 = StdIn.readLine().split(" ").map(_.toInt)
	lazy val fix2 = StdIn.readLine().split(" ").map(_.toInt)

	(errors.diff(fix1).head, fix1.diff(fix2).head) match {
		case (bug1, bug2) => println(s"$bug1\n$bug2")
	}
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val input1 = readInts(n-1)
    val input2 = readInts(n-2)
    println(input.diff(input1)(0))
    println(input1.diff(input2)(0))
  }
}

import scala.io.StdIn

object A extends App {

  val n = StdIn.readInt()
  val f = StdIn.readLine().split(" ").map(_.toInt)
  val s = StdIn.readLine().split(" ").map(_.toInt)
  val t = StdIn.readLine().split(" ").map(_.toInt)
  val e1 = f diff s
  val e2 = s diff t
  println(e1.head)
  println(e2.head)

}

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

import scala.collection.mutable

object B {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val a = new mutable.HashMap[Int, Int]()
    for (i <- 0 until n) {
      val int = nextInt
      val x = a.getOrElse(int, 0)
      a.put(int, x + 1)
    }
    val b = new mutable.HashMap[Int, Int]()
    for (i <- 0 until n - 1) {
      val int = nextInt
      val x = b.getOrElse(int, 0)
      b.put(int, x + 1)
    }
    val c = new mutable.HashMap[Int, Int]()
    for (i <- 0 until n - 2) {
      val int = nextInt
      val x = c.getOrElse(int, 0)
      c.put(int, x + 1)
    }
    val list1 = b.toIterator
    while(list1.hasNext) {
      val l1 = list1.next()
      val x = l1._1
      for (j <- 0 until l1._2) {
        val v = a.getOrElse(x, 0)
        a.remove(x)
        if (v - 1 > 0) {
          a.put(x, v - 1)
        }
      }
    }
    val list2 = c.toIterator
    while(list2.hasNext) {
      val l1 = list2.next()
      val x = l1._1
      for (j <- 0 until l1._2) {
        val v = b.getOrElse(x, 0)
        b.remove(x)
        if (v - 1 > 0) {
          b.put(x, v - 1)
        }
      }
    }
    out.println(a.toList.head._1)
    out.println(b.toList.head._1)
    return 1
  }

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

import scala.io.StdIn._

object _519_B extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)
  val B = readLine().split(" ").map(_.toInt)
  val C = readLine().split(" ").map(_.toInt)

  val answer1 = A.diff(B) mkString " "
  val answer2 = A.diff(C) filterNot (_ == answer1.toInt) mkString " "
  println(answer1)
  println(answer2)
}


import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) / 2
		build(v * 2, tl, tm)
		build(v * 2 + 1, tm + 1, tr)
		t(v) = t(v * 2) + t(v * 2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) / 2
    	  query(l, Math.min(r, tm), v * 2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) / 2
		  if (pos <= tm) update(pos, newVal, v * 2, tl, tm)
		  else update(pos, newVal, v * 2 + 1, tm + 1, tr)
		  t(v) = t(v * 2) + t(v * 2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree(as)
  val rightST = SegTree(as.map(a => 1 - a))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i - 1, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) >> 1
		build(v << 1, tl, tm)
		build((v << 1) + 1, tm + 1, tr)
		t(v) = t(v << 1) + t((v << 1) + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) >> 1
    	  query(l, Math.min(r, tm), v << 1, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, (v << 1) + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) >> 1
		  if (pos <= tm) update(pos, newVal, v << 1, tl, tm)
		  else update(pos, newVal, (v << 1) + 1, tm + 1, tr)
		  t(v) = t(v << 1) + t((v << 1) + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree(as)
  val rightST = SegTree(as.map(a => 1 - a))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i - 1, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) / 2
		build(v * 2, tl, tm)
		build(v * 2 + 1, tm + 1, tr)
		t(v) = t(v * 2) + t(v * 2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) / 2
    	  query(l, Math.min(r, tm), v * 2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) / 2
		  if (pos <= tm) update(pos, newVal, v * 2, tl, tm)
		  else update(pos, newVal, v * 2 + 1, tm + 1, tr)
		  t(v) = t(v * 2) + t(v * 2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree((0 +: as).take(n))
  val rightST = SegTree(((as.map(a => (1 - a)) :+ 0)).take(n))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) >> 1
		val v2 = v << 1
		build(v2, tl, tm)
		build(v2 + 1, tm + 1, tr)
		t(v) = t(v2) + t(v2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) >> 1
    	  val v2 = v << 1
    	  query(l, Math.min(r, tm), v2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) >> 1
		  val v2 = v << 1
		  if (pos <= tm) update(pos, newVal, v2, tl, tm)
		  else update(pos, newVal, v2 + 1, tm + 1, tr)
		  t(v) = t(v2) + t(v2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree(as)
  val rightST = SegTree(as.map(a => 1 - a))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i - 1, -1)
  }

  println(sum)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Please hack me if you can!
 */
import scala.collection._

object A extends App {

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

  object BIT {

    def query(t: Array[Int], r: Int, acc: Int = 0): Int =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def update(t: Array[Int], i: Int, delta: Int): Unit =
      if (i < t.length && i >= 0) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Int]): Array[Int] = {
      val t = Array.fill(src.length) { 0 }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftBIT = BIT((0 +: as).take(n))
  val rightBIT = BIT((0 +: (as.map(a => (1 - a)).reverse)).take(n))

  var sum = 0L
  for (i <- order) {
    sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)
    if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)
    else BIT.update(leftBIT, i, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) >> 1
		val v2 = v << 1
		build(v2, tl, tm)
		build(v2 + 1, tm + 1, tr)
		t(v) = t(v2) + t(v2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) >> 1
    	  val v2 = v << 1
    	  query(l, Math.min(r, tm), v2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) >> 1
		  val v2 = v << 1
		  if (pos <= tm) update(pos, newVal, v2, tl, tm)
		  else update(pos, newVal, v2 + 1, tm + 1, tr)
		  t(v) = t(v2) + t(v2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree(as)
  val rightST = SegTree(as.map(a => 1 - a))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i - 1, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) / 2
		build(v * 2, tl, tm)
		build(v * 2 + 1, tm + 1, tr)
		t(v) = t(v * 2) + t(v * 2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) / 2
    	  query(l, Math.min(r, tm), v * 2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) / 2
		  if (pos <= tm) update(pos, newVal, v * 2, tl, tm)
		  else update(pos, newVal, v * 2 + 1, tm + 1, tr)
		  t(v) = t(v * 2) + t(v * 2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree((0 +: as).take(n))
  val rightST = SegTree((0 +: (as.map(a => (1 - a)).reverse)).take(n))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i) + rightST.query(0, n - i - 1)
    if (as(i) == 0) rightST.update(n - i - 1, -1)
    else leftST.update(i, -1)
  }

  println(sum)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Please hack me if you can!
 */
import scala.collection._

object A extends App {

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

  object BIT {

    def query(t: Array[Int], r: Int, acc: Int = 0): Int =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def update(t: Array[Int], i: Int, delta: Int): Unit =
      if (i < t.length && i >= 0) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Byte]): Array[Int] = {
      val t = Array.fill(src.length) { 0 }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftBIT = BIT((0.toByte +: as).take(n))
  val rightBIT = BIT((0.toByte +: (as.map(a => (1 - a).toByte).reverse)).take(n))

  var sum = 0
  for (i <- order) {
    sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)
    if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)
    else BIT.update(leftBIT, i, -1)
  }

  println(sum)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Please hack me if you can!
 */
import scala.collection._

object A extends App {

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

  object BIT {

    def query(t: Array[Int], r: Int, acc: Int = 0): Int =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def update(t: Array[Int], i: Int, delta: Int): Unit =
      if (i < t.length && i >= 0) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Int]): Array[Int] = {
      val t = Array.fill(src.length) { 0 }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftBIT = BIT((0 +: as).take(n))
  val rightBIT = BIT((0 +: (as.map(a => (1 - a)).reverse)).take(n))

  var sum = 0
  for (i <- order) {
    sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)
    if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)
    else BIT.update(leftBIT, i, -1)
  }

  println(sum)
}


object B701 {

  import IO._

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

    val row = Array.fill(n)(false)
    val col = Array.fill(n)(false)
    val res = Array.fill(m)(0L)
    var R = 0L
    var C = 0L
    for(q <- 0 until m ) {
      val Array(r, c)= readInts(2)
      if(!row(r-1)) {
        row(r-1) = true
        R += 1
      }
      if(!col(c-1)) {
        col(c-1) = true
        C += 1
      }
      res(q) = (n-R)*(n-C)
    }

    println(res.mkString(" "))
  }

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

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

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

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

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

}

import scala.collection.mutable.BitSet

//package b

object B extends App {

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

  val Array(n, m) = readInts(2)

  var freeCols, freeRows = n
  var remain = n.toLong * n
  val res = Array.ofDim[Long](m)

  val row, col = new BitSet(n)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    if (!row(y) && !col(x)) {
      remain -= (freeCols + freeRows - 1)
      freeCols -= 1
      freeRows -= 1
    } else if (!row(y)) {
      remain -= freeCols
      freeRows -= 1
    } else if (!col(x)) {
      remain -= freeRows
      freeCols -= 1
    }

    res(i) = remain
    row += y
    col += x
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}

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

object _701B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val (n, m) = read[(Long, Int)]
    val rows, cols = mutable.Set.empty[Int]
    repeat(m) {
      val r, c = read[Int]
      rows += r
      cols += c
      val ans: Long = (n - rows.size)*(n - cols.size)
      write(ans, "")
    }
    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def until(until: Int): Range = 0 until until
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt(); val m = sc.nextInt()

    val dpx = new Array[Boolean](n+1)
    val dpy = new Array[Boolean](n+1)

    var xw = n
    var yw = n

    for(k <- 1 to m){
      val y = sc.nextInt(); val x = sc.nextInt()

      if(!dpx(x)){
        dpx(x) = true
        xw -= 1
      }

      if(!dpy(y)){
        dpy(y) = true
        yw -= 1
      }

      if(k == m)
        println(xw * yw.toLong)
      else
        print(xw * yw.toLong + " ")
    }
  }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val Array(n, m) = lines.next().split(' ').map(_.toInt)
  val xaxis = Array.ofDim[Boolean](n)
  val yaxis = Array.ofDim[Boolean](n)
  var xLeft: Long = n
  var yLeft: Long = n

  println(lines.take(m).map { _.split(' ').map(_.toInt - 1)}.map {
    case Array(x, y) =>
      if (!xaxis(x)) xLeft -= 1
      if (!yaxis(y)) yLeft -= 1
      xaxis(x) = true
      yaxis(y) = true
      xLeft * yLeft
  }.mkString(" "))

}

import scala.collection.mutable.BitSet

//package b

object B extends App {

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

  val Array(n, m) = readInts(2)

  var freeCols, freeRows = n
  var remain = n.toLong * n
  val res = Array.ofDim[Long](m)

  val row, col = new BitSet(n)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    if (!row(y) && !col(y)) {
      remain -= (freeCols + freeRows - 1)
      freeCols -= 1
      freeRows -= 1
    } else if (!row(y)) {
      remain -= freeCols
      freeRows -= 1
    } else if (!col(x)) {
      remain -= freeRows
      freeCols -= 1
    }

    res(i) = remain
    row += y
    col += x
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}

import scala.collection.mutable.BitSet

//package b

object B extends App {

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

  val Array(n, m) = readInts(2)

  var freeCols, freeRows = n
  var remain = n.toLong * n
  val res = Array.ofDim[Long](m)

  val row, col = new BitSet(n)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    if (!row(y) && !col(y)) {
      remain -= (freeCols + freeRows - 1)
      freeCols -= 1
      freeRows -= 1
    } else if (!row(y)) {
      remain -= freeCols
      freeRows -= 1
    } else if (!col(x)) {
      remain -= freeRows
      freeCols -= 1
    }

    res(i) = remain
    row += y
    col += y
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}


//package codeforces.contest1244

object PensAndPencils {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val Array(lectures, practicals, lRate, pRate, limit) =
        io.StdIn.readLine.split(" ").map(_.toInt)

      val pensRequired = (lectures + (if (lectures % lRate == 0) 0 else lRate)) / lRate
      val pencilsRequired = (practicals + (if (practicals % pRate == 0) 0 else pRate)) / pRate

      if (pensRequired + pencilsRequired <= limit)
        println(s"$pensRequired $pencilsRequired")
      else
        println(-1)

    }
  }

}

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

  val t = nextInt

  for (_ <- 1 to t) {
    val a, b, c, d, k = nextInt
    val aa = (a + c - 1) / c
    val bb = (b + d - 1) / d
    if (aa + bb <= k) out.println(s"$aa $bb")
    else out.println(-1)
    out.flush()
  }

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


import scala.io.StdIn

object Zeros extends App {

  private val operate: String => Int =
    str => {
      val from = str.indexOf('1')
      val to = str.lastIndexOf('1')
      getCount(str.substring(from, to))
    }

  private val getCount: String => Int =
    str => str count (_ == '0')

  var n: Int = StdIn.readLine().toInt

  while (n != 0) {
    val line: String = StdIn.readLine()
    if (line.contains('1')) println(operate(line)) else println(0)
    n -= 1
  }

}

import java.io.PrintWriter
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString(): String = reader.readLine()

    def multiTest(f: () => Unit): Unit = {
        var t = readInt()
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        val s = readString()
        var l = 0
        while (l < s.length && s(l) == '0') l += 1

        var r = s.length - 1
        while (r > 0 && s(r) == '0') r -= 1

        var rs = 0
        while (l <= r) {
            if (s(l) == '0') rs += 1
            l += 1
        }
        println(rs)
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
    }
}

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

  override def solve(io: IO) = io.repeat {
    val t = io.read[String]
    val ans = for {
      i <- Option(t.indexOf('1')) if i >= 0
      j <- Option(t.lastIndexOf('1')) if j > i
      o = t.substring(i, j)
    } yield o.count(_ == '0')
    io.write(ans.getOrElse(0))
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.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(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

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

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  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.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

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

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var value: Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return value.compareTo(that.value)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n)
        for (i <- 0 until n)
            arr(i) = readInt()
        val s = readString()
        var r = Vector[Int]()
        var b = Vector[Int]()
        for (i <- 0 until n) {
           if (s(i) == 'B')
               b :+= arr(i)
           else
               r :+= arr(i)
        }
        b = b.sorted
        r = r.sorted.reverse
        var ans = "YES"
        for (i <- r.indices) {
            if (r(i) > n-i)
                ans = "NO"
        }
        for (i <- b.indices) {
            if (b(i) < i+1)
                ans = "NO"
        }
        writer.println(ans)
    }
    writer.flush()
}

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

  override def solve(io: IO) = io.repeat {
    val values = io.read[Vector[Int]]
    val colors = io.read[String]

    val arr = colors.zip(values).toMultiMap.mapValues(_.sorted).withDefaultValue(Vector.empty)

    val blues = arr('B')
    var bi = -1

    val reds = arr('R')
    var ri = -1

    def findRed(x: Int) =
      ((ri + 1) until reds.length)
        .find(i => reds(i) <= x)
        .map({i => ri = i; i})

    def findBlue(x: Int) =
      ((bi + 1) until blues.length)
        .find(i => x <= blues(i))
        .map({i => bi = i; i})

    def find(x: Int) = findBlue(x).orElse(findRed(x)).nonEmpty

    val ans = (1 to values.length).forall(find)

    io.write(ans.toEnglish.toUpperCase)
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.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)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  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(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

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

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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


object A {

  def main(args: Array[String]): Unit = {}
  import IO._

  val t = nextInt

  for (_ <- 1 to t) {
    val a, b, n = nextLong
    val xs = Array(a, b, a ^ b)
    println(xs(n.toInt % 3))
  }

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val a, b, n = ni()
      val ans = n % 3 match {
        case 0 => a
        case 1 => b
        case 2 => a ^ b
      }
      out.println(ans)
    }
  }
}

object A {

  import IO._
  def main(args: Array[String]): Unit = {
    val t = nextInt

    var i = 0
    while (i < t) {
      val a, b, n = nextLong
      val xs = Array(a, b, a ^ b)
      out.println(xs(n.toInt % 3))
      i += 1
    }
    out.flush()
  }

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

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

  @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(t) = readInts(1)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 1 to t) {
    val Array(a, b, n) = readLongs(3)
    val xs = Array(a, b, a ^ b)
    println(xs(n.toInt % 3))
  }

  Console.flush
}

object A {

  def main(args: Array[String]): Unit = {}
  import IO._

  val t = nextInt

  for (_ <- Range(0, t)) {
    val a, b, n = nextLong
    val xs = Array(a, b, a ^ b)
    out.println(xs(n.toInt % 3))
  }
  out.flush()

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

  def main(args: Array[String]): Unit = {}
  import IO._

  val t = nextInt

  var i = 0
  while (i < t) {
    val a, b, n = nextLong
    val xs = Array(a, b, a ^ b)
    out.println(xs(n.toInt % 3))
    i += 1
  }
  out.flush()

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A 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(t) = readInts(1)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 1 to t) {
    val Array(a, b, n) = readLongs(3)
    val xs = Array(a, b, a ^ b)
    println(xs(n.toInt % 3))
  }

  Console.flush
}

object A {

  def main(args: Array[String]): Unit = {}
  import IO._

  val t = nextInt

  for (_ <- 1 to t) {
    val a, b, n = nextLong
    val xs = Array(a, b, a ^ b)
    out.println(xs(n.toInt % 3))
  }
  out.flush()

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

  import IO._
  def main(args: Array[String]): Unit = {
    val t = nextInt

    for (_ <- Range(0, t)) {
      val a, b, n = nextLong
      val xs = Array(a, b, a ^ b)
      out.println(xs(n.toInt % 3))
    }
    out.flush()
  }

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object A {

  import IO._
  def main(args: Array[String]): Unit = {
    val t = nextInt

    for (_ <- 1 to t) {
      val a, b, n = nextLong
      val xs = Array(a, b, a ^ b)
      out.println(xs(n.toInt % 3))
    }
    out.flush()
  }

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}


object P7D {
    import io.StdIn._

    val s = readLine

    def main(args : Array[String]) {
        var p = s(0).toLong
        var q = s(0).toLong
        var r = 1L
        val a = Array.ofDim[Int](s.size)
        a(0) = 1
        for (i <- 1 until s.size) {
            p = p * 0x3333333333333333L + s(i)
            r = r * 0x3333333333333333L
            q = q + r * s(i)
            a(i) = if (p == q) a(i - 1 >> 1) + 1 else 0
        }
        println(a.sum)
    }
}


import scala.annotation.tailrec

object Devu {
  def main(args: Array[String]) {
	  val n = readLine().toInt
	  val d = readLine().split(" ").map(_.toLong)
	  val goal = d.reduceLeft(_ + _) / n
	  @tailrec
	  def cnt(x: Int, g: Long, acc: Long): Long = {
	    if (x >= n) acc
	    else (g - d(x)) match {
	      case 0 => cnt(x + 1, goal, acc)
	      case z if z > 0 => cnt(x + 1, goal + z, acc + z)
	      case z if z < 0 => cnt(x + 1, goal + z, acc - z)
	    }
	  }
	  println(cnt(0, goal, 0))
  }
}

//package template

object Template {
	def main(args: Array[String]) {
		var n = readLine.toInt
		var input = readLine.split(' ').map(_.toLong)
		if(n == 1){
			print(0)
		}
		else{
			var avarage = 0L
			for(i <- input){
				avarage += i
			}
			avarage /= n
			var answer = 0L
			var current = avarage
			var next = input(0)
			var dif = 0L
			for(i <- 0 until n){
				dif = avarage - current
				current = next - dif
				if(i != n-1)next = input(i+1)
				answer += Math.abs(dif)
			}
			print(answer)
		}
	}
}

//package template

object Template {
	def main(args: Array[String]) {
		var n = readLine.toInt
		var input = readLine.split(' ').map(_.toInt)
		if(n == 1){
			print(0)
		}
		else{
			var avarage = 0
			for(i <- input){
				avarage += i
			}
			avarage /= n
			var answer = 0
			var current = avarage
			var next = input(0)
			var dif = 0
			for(i <- 0 until n){
				dif = avarage - current
				current = next - dif
				if(i != n-1)next = input(i+1)
				answer += Math.abs(dif)
			}
			print(answer)
		}
	}
}


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

object Main{
  def main(args: Array[String]) {
    val bf = new BufferedReader(new InputStreamReader(System.in))
    val N = bf.readLine.toInt
    val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(" ")
    val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)
    val G = E groupBy(_._1) mapValues (_ map(_._2))
    def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList;
    val black = coloring.filter{case (id, color) => color == 0}.size
    val white = N - black

    println(black.toLong * white - (N - 1));
  }
}

import scala.annotation.tailrec
import scala.collection.mutable

/**
  * @see http://codeforces.com/contest/862/problem/B
  *      TIME LIMIT EXCEEDED :(
  */

object TAILREC_BMahmoudAndEhabAndTheBipartiteness extends App {
  /**
    * Bicoloring based of dfs
    */
  def bicoloring(g: mutable.HashMap[Int, List[Int]]): (Long, Long) = {
    @tailrec
    def dfs(h: List[(Int, Int, List[Int], Int)], cts: (Long, Long)): (Long, Long) = {
      if (h.isEmpty) cts
      else {
        val (p, u, adj, c) = h.head
        if (adj.isEmpty) dfs(h.tail, (cts._1 + (c ^ 1), cts._2 + (c ^ 0)))
        else {
          val v = adj.head
          if (v == p) dfs((p, u, adj.tail, c) :: h.tail, cts)
          else dfs((u, v, g(v), if (c == 0) 1 else 0) :: (p, u, adj.tail, c) :: h.tail, cts)
        }
      }
    }

    dfs(List((0, 1, g(1), 0)), (0L, 0L))
  }

  /**
    * 1 <= n <= math.pow(10, 5)
    */
  val n = scala.io.StdIn.readLine().toInt

  /**
    * The adjacency-list representation of a graph
    * g is a connected acyclic graph
    */
  val g = (0 until n - 1).foldLeft(new mutable.HashMap[Int, List[Int]]) { (g, _) =>
    val Array(u, v) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    g(v) = u :: g.getOrElse(v, Nil)
    g(u) = v :: g.getOrElse(u, Nil)
    g
//    g + (v -> (u :: g.getOrElse(v, Nil)), u -> (v :: g.getOrElse(u, Nil)))
  }

  val (a, b) = bicoloring(g)
  println(a * b - n + 1)
}

import scala.collection.mutable.ArrayBuffer

/**
  * @see http://codeforces.com/contest/862/problem/B
  */

object BMahmoudAndEhabAndTheBipartiteness extends App {
  /**
    * Bicoloring based of dfs
    */
  def bicoloring(g: ArrayBuffer[List[Int]]): (Long, Long) = {
    var cts = (0L, 0L)

    def dfs(u: Int, v: Int, c: Int): Unit = {
      cts = (cts._1 + (c ^ 1), cts._2 + (c ^ 0))
      g(v).foreach(p => if (p != u) dfs(v, p, if (c == 0) 1 else 0))
    }

    dfs(0, 1, 0)
    cts
  }

  /**
    * 1 <= n <= math.pow(10, 5)
    */
  val n = scala.io.StdIn.readLine().toInt

  /**
    * The adjacency-list representation of a graph
    * g is a connected acyclic graph
    */
  val g = (0 until n - 1).foldLeft(ArrayBuffer.fill[List[Int]](100005)(Nil)) { (g: ArrayBuffer[List[Int]], _) =>
    val Array(u, v) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    g(u) = v :: g(u)
    g(v) = u :: g(v)
    g
  }

  val (a, b) = bicoloring(g)
  println(a * b - n + 1)
}

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

object Main{
  def main(args: Array[String]) {
    val bf = new BufferedReader(new InputStreamReader(System.in))
    val N = bf.readLine.toInt
    val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(" ")
    val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)
    val G = E groupBy(_._1) mapValues (_ map(_._2))
    def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList.toMap;
    val black = coloring.filter{case (id, color) => color == 0}.size
    val white = N - black

    println(black.toLong * white - (N - 1));
  }
}

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

object Main{
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val N = sc.nextInt
    val edgesLines = for (i <- 0 until (N - 1)) yield (sc.nextInt, sc.nextInt)
    val E = edgesLines.flatMap(e => List(e, e.swap))
    val G = E.groupBy{case (from, to) => from}.mapValues(_.map{case (from, to) => to})
    def Color(id: Int, p: Int, color: Int): Iterator[Tuple2[Int, Int]] = Iterator((id, color)) ++ G(id).filter(_ != p).map(Color(_, id, 1 - color)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList
    val black = coloring.count{case (id, color) => color == 0}
    val white = N - black

    println(black.toLong * white - (N - 1));
  }
}

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

object Main{
  def main(args: Array[String]) {
    val bf = new BufferedReader(new InputStreamReader(System.in))
    val N = bf.readLine.toInt
    val edgesLines = for (i <- 0 until (N - 1)) yield bf.readLine.split(" ")
    val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(e => List(e, e.swap))
    val G = E.groupBy{case (from, to) => from}.mapValues(_.map{case (from, to) => to})
    def Color(id: Int, p: Int, color: Int): Iterator[Tuple2[Int, Int]] = Iterator((id, color)) ++ G(id).filter(_ != p).map(Color(_, id, 1 - color)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList
    val black = coloring.count{case (id, color) => color == 0}
    val white = N - black

    println(black.toLong * white - (N - 1));
  }
}

import scala.annotation.tailrec
import scala.collection.immutable.HashMap

/**
  * @see http://codeforces.com/contest/862/problem/B
  */

object BMahmoudAndEhabAndTheBipartiteness extends App {
  /**
    * Bicoloring based of dfs
    *
    * @param g is a connected acyclic graph
    * @return
    */
  def bicoloring(g: HashMap[Int, List[Int]]): (Long, Long) = {
    @tailrec
    def dfs(h: List[(Int, List[Int], Int)], cts: (Long, Long)): (Long, Long) = {
      if (h.isEmpty) cts
      else {
        val (u, adj, c) = h.head
        if (adj.isEmpty) dfs(h.tail, (cts._1 + c ^ 1, cts._2 + c ^ 0))
        else {
          val v = adj.head
          dfs((v, g(v).filter(p => p != u), if (c == 0) 1 else 0) :: (u, adj.tail, c) :: h.tail, cts)
        }
      }
    }

    dfs(List((1, g(1), 0)), (0L, 0L))
  }

  /**
    * 1 <= n <= math.pow(10, 5)
    */
  val n = scala.io.StdIn.readLine().toInt

  /**
    * The adjacency-list representation of a graph
    * g is a connected acyclic graph
    */
  val g = (0 until n - 1).foldLeft(new HashMap[Int, List[Int]]) { (g, _) =>
    val Array(u, v) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    g + (v -> (u :: g.getOrElse(v, Nil)), u -> (v :: g.getOrElse(u, Nil)))
  }

  val (a, b) = bicoloring(g)
  println(a * b - n + 1)
}

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

object Main{
  def main(args: Array[String]) {
    val bf = new BufferedReader(new InputStreamReader(System.in))
    val N = bf.readLine.toInt
    val edgesLines = for (id <- 0 until (N - 1)) yield bf.readLine.split(" ")
    val E = edgesLines.map(s => (s(0).toInt, s(1).toInt)).flatMap(p => (p._1, p._2) :: (p._2, p._1) :: Nil)
    val G = E groupBy(_._1) mapValues (_ map(_._2))
    def Color(x: Int, p: Int, c: Int): Iterator[Tuple2[Int, Int]] = Iterator((x, c)) ++ G(x).filter(_ != p).map(Color(_, x, 1 - c)).fold(Iterator.empty)(_ ++ _)
    val coloring = Color(1, -1, 0).toList.toMap;
    val black = coloring.filter{case (id, color) => color == 0}.size
    val white = N - black

    println(black * white - (N - 1));
  }
}

import java.util.Scanner

object Main{
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val E = for (id <- 0 until (N - 1); p <- (sc.nextInt(), sc.nextInt) :: Nil; ps <- (p._1, p._2) :: (p._2, p._1) :: Nil) yield ps
    val G = E groupBy(_._1) mapValues (_ map(_._2))
    println(G)
    def Color(x: Int, p: Int, c: Int): Map[Int, Int] = G(x).filter(_ != p).map(Color(_, x, 1 - c)).flatten.toMap.updated(x, c)
    val coloring = Color(1, -1, 0);
    val black = coloring.filter{case (id, color) => color == 0}.size
    val white = N - black

    println(black * white - (N - 1));
  }
}


object A {
  import InOut._
  def main(args: Array[String]): Unit = {
    val t = nextInt
    for (i <- 1 to t) {
      val n = nextInt
      val arr = nextInts(n)
      val odd=arr.count(_%2==1)
      println(odd min (n-odd))
    }

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

import scala.io.StdIn

object Sol {
  def main(args: Array[String]): Unit = {
    val tests = StdIn.readLine().toInt
    (0 until tests).foreach { _ =>
      val _ = StdIn.readLine().toInt
      val numbers = StdIn.readLine().split(" ").map(_.toLong)

      val (even, odd) = numbers.foldLeft((0L, 0L)) { case ((even, odd), newNumber) => (even + (1L - newNumber % 2L), odd + (newNumber % 2L)) }

      println(Math.min(even, odd))
    }
  }
}


import scala.collection.mutable

object D extends App {
  val INF = 1000000000000000000L
  def readInts: Array[Int] = readLine().split(" ").map(_.toInt - 1)
  def readLongs: Array[Long] = readLine().split(" ").map(_.toLong)

  val n = readInt
  val weights = readLongs

  val links = Array.fill(n)(List.empty[Int])
  (1 until n).foreach { _ =>
    val Array(a, b) = readInts
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  val branchWeights = new Array[Long](n)
  val bests = new Array[Long](n)
  val bestPairs = new Array[Long](n)

    def main(cur: Int, incoming: Int): Unit = {
      val children = for {
        i <- links(cur)
        if i != incoming
      } yield i
      children.foreach(main(_, cur))

      branchWeights(cur) = children.map(branchWeights).sum + weights(cur)
      val bestsint = children.map(bests)
      val best2 = if (children.size < 3) bestsint else bestsint.sorted.reverse.take(2)
      bests(cur) = best2.foldLeft(branchWeights(cur))(Math.max)
      val bestPairCur = if (best2.size < 2) -INF else best2.sum
      bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)
    }

    main(0, 0)
    val ans = bestPairs(0)
    if (ans == -INF) println("Impossible") else println(ans.toString)
}

import java.util.StringTokenizer

object D extends App {
  val INF = 1000000000000000000L

  var st: StringTokenizer = _

  val n = readInt
  var weights = new Array[Long](n)
  var links = new Array[List[Int]](n)
  st = new StringTokenizer(readLine())
  (0 until n).foreach { id =>
    weights(id) = st.nextToken().toLong
    links(id) = Nil
  }

  var a: Int = _
  var b: Int = _
  (1 until n).foreach { _ =>
    st = new StringTokenizer(readLine())
    a = st.nextToken().toInt - 1
    b = st.nextToken().toInt - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  var branchWeights = new Array[Long](n)
  var bests = new Array[Long](n)
  var bestPairs = new Array[Long](n)

  var best1 = -INF
  var best2 = -INF
  var bestc = -INF

  def main(cur: Int, incoming: Int): Unit = {
    val children = for {
      i <- links(cur)
      if i != incoming
    } yield i

    if (children.isEmpty) {
      bestc = weights(cur)
      branchWeights(cur) = bestc
      bests(cur) = bestc
      bestPairs(cur) = -INF
      return
    }

    children.foreach(main(_, cur))

    bestc = weights(cur)
    children.foreach(bestc += branchWeights(_))
    branchWeights(cur) = bestc

    best1 = -INF
    best2 = -INF
    children.foreach { id =>
      bestc = bests(id)
      if (bestc > best1) { best2 = best1; best1 = bestc }
      else if (bestc > best2) { best2 = bestc }
    }
    bests(cur) = Math.max(branchWeights(cur), best1)

    bestc = if (best2 == -INF) -INF else best1 + best2
    children.foreach { id => bestc = Math.max(bestc, bestPairs(id)) }
    bestPairs(cur) = bestc
  }

  main(0, 0)
  bestc = bestPairs(0)
  if (bestc == -INF) println("Impossible") else println(bestc.toString)
}

import java.util.StringTokenizer

object D extends App {
  val INF = 1000000000000000000L

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

  val n = readInt
  val weights = readLongs

  val links = Array.fill(n)(List.empty[Int])
  var st: StringTokenizer = _
  var a: Int = _
  var b: Int = _
  (1 until n).foreach { _ =>
    st = new StringTokenizer(readLine())
    a = st.nextToken().toInt - 1
    b = st.nextToken().toInt - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  val branchWeights = new Array[Long](n)
  val bests = new Array[Long](n)
  val bestPairs = new Array[Long](n)

  def main(cur: Int, incoming: Int): Unit = {
    val children = for {
      i <- links(cur)
      if i != incoming
    } yield i
    children.foreach(main(_, cur))

    branchWeights(cur) = children.map(branchWeights).sum + weights(cur)
    val bestsint = children.map(bests)
    val best2 = if (children.size < 3) bestsint else bestsint.sorted.reverse.take(2)
    bests(cur) = best2.foldLeft(branchWeights(cur))(Math.max)
    val bestPairCur = if (best2.size < 2) -INF else best2.sum
    bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)
  }

  main(0, 0)
  val ans = bestPairs(0)
  if (ans == -INF) println("Impossible") else println(ans.toString)
}

import scala.collection.mutable

object D extends App {
  val INF = 1000000000000000000L
  def readInts: Array[Int] = readLine().split(" ").map(_.toInt - 1)
  def readLongs: Array[Long] = readLine().split(" ").map(_.toLong)

  val n = readInt
  val weights = readLongs

  val links = Array.fill(n)(List.empty[Int])
  (1 until n).foreach { _ =>
    val Array(a, b) = readInts
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  val branchWeights = new Array[Long](n)
  val bests = new Array[Long](n)
  val bestPairs = new Array[Long](n)

    def main(cur: Int, incoming: Int): Unit = {
      val children = for {
        i <- links(cur)
        if i != incoming
      } yield i
      children.foreach(main(_, cur))

      branchWeights(cur) = children.map(branchWeights).sum + weights(cur)
      val best2 = children.map(bests).sorted.reverse.take(2)
      bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)
      val bestPairCur = if (best2.size < 2) -INF else best2.sum
      bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)
    }

    main(0, 0)
    val ans = bestPairs(0)
    if (ans == -INF) println("Impossible") else println(ans.toString)
}

import java.util.StringTokenizer

import scala.collection.mutable

object D extends App {
  val INF = 1000000000000000000L

  var st: StringTokenizer = _

  val n = readInt
  var weights = new Array[Long](n)
  var links = new Array[List[Int]](n)
  st = new StringTokenizer(readLine())
  (0 until n).foreach { id =>
    weights(id) = st.nextToken().toLong
    links(id) = Nil
  }

  var a: Int = _
  var b: Int = _
  (1 until n).foreach { _ =>
    st = new StringTokenizer(readLine())
    a = st.nextToken().toInt - 1
    b = st.nextToken().toInt - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  var branchWeights = new Array[Long](n)
  var bests = new Array[Long](n)
  var bestPairs = new Array[Long](n)

  var best1 = -INF
  var best2 = -INF
  var bestc = -INF

  def dfs(cur: Int, incoming: Int): Unit = {
    var pair = (0, 0)
    val stack1 = new mutable.Stack[(Int, Int)]
    val stack2 = new mutable.Stack[Int]
    stack1.push((cur, incoming))
    stack2.push(cur)
    while (stack1.nonEmpty) {
      pair = stack1.pop()
      a = pair._1
      links(a) = links(a).filterNot(_ == pair._2)
      links(a).foreach { id =>
        stack1.push((id, a))
        stack2.push(id)
      }
    }
    while (stack2.nonEmpty) process(stack2.pop)
  }

  def process(cur: Int): Unit = {
    val children = links(cur)

    bestc = weights(cur)
    children.foreach(bestc += branchWeights(_))
    branchWeights(cur) = bestc

    best1 = -INF
    best2 = -INF
    children.foreach { id =>
      bestc = bests(id)
      if (bestc > best1) { best2 = best1; best1 = bestc }
      else if (bestc > best2) { best2 = bestc }
    }
    bests(cur) = Math.max(branchWeights(cur), best1)

    bestc = if (best2 == -INF) -INF else best1 + best2
    children.foreach { id => bestc = Math.max(bestc, bestPairs(id)) }
    bestPairs(cur) = bestc
  }

  dfs(0, 0)
  bestc = bestPairs(0)
  if (bestc == -INF) println("Impossible") else println(bestc.toString)
}

import java.util.StringTokenizer

object D extends App {
  val INF = 1000000000000000000L

  var st: StringTokenizer = _

  val n = readInt
  var weights = new Array[Long](n)
  var links = new Array[List[Int]](n)
  st = new StringTokenizer(readLine())
  (0 until n).foreach { id =>
    weights(id) = st.nextToken().toLong
    links(id) = Nil
  }

  var a: Int = _
  var b: Int = _
  (1 until n).foreach { _ =>
    st = new StringTokenizer(readLine())
    a = st.nextToken().toInt - 1
    b = st.nextToken().toInt - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  var branchWeights = new Array[Long](n)
  var bests = new Array[Long](n)
  var bestPairs = new Array[Long](n)

  var best1 = -INF
  var best2 = -INF
  var bestc = -INF

  def main(cur: Int, incoming: Int): Unit = {
    links(a)
    val children = for {
      i <- links(cur)
      if i != incoming
    } yield i

    if (children.isEmpty) {
      bestc = weights(cur)
      branchWeights(cur) = bestc
      bests(cur) = bestc
      bestPairs(cur) = -INF
      return
    }

    children.foreach(main(_, cur))

    bestc = weights(cur)
    children.foreach(bestc += branchWeights(_))
    branchWeights(cur) = bestc

    best1 = -INF
    best2 = -INF
    children.foreach { id =>
      bestc = bests(id)
      if (bestc > best1) { best2 = best1; best1 = bestc }
      else if (bestc > best2) { best2 = bestc }
    }
    bests(cur) = Math.max(branchWeights(cur), best1)

    bestc = if (best2 == -INF) -INF else best1 + best2
    children.foreach { id => bestc = Math.max(bestc, bestPairs(id)) }
    bestPairs(cur) = bestc
  }

  if (n < 100000) {
    main(0, 0)
    bestc = bestPairs(0)
    if (bestc == -INF) println("Impossible") else println(bestc.toString)
  }
}

import scala.collection.mutable

object D extends App {
  val INF = 1000000000000000000L
  def readInts: Array[Int] = readLine().split(" ").map(_.toInt - 1)
  def readLongs: Array[Long] = readLine().split(" ").map(_.toLong)

  val n = readInt
  val weights = readLongs

  val links = Array.fill(n)(mutable.ListBuffer.empty[Int])
  (1 until n).foreach { _ =>
    val Array(a, b) = readInts
    links(a) += b
    links(b) += a
  }

  val branchWeights = new Array[Long](n)
  val bests = new Array[Long](n)
  val bestPairs = new Array[Long](n)

  if (n < 100000) {
    def main(cur: Int, incoming: Int): Unit = {
      val children = for {
        i <- links(cur)
        if i != incoming
      } yield i
      children.foreach(main(_, cur))

      branchWeights(cur) = children.map(branchWeights).sum + weights(cur)
      val best2 = children.map(bests).sorted.reverse.take(2)
      bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)
      val bestPairCur = if (best2.size < 2) -INF else best2.sum
      bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)
    }

    main(0, 0)
    val ans = bestPairs(0)
    if (ans == -INF) println("Impossible") else println(ans.toString)
  }
}

import scala.collection.mutable

object D extends App {
  def readInts = readLine().split(" ").map(_.toInt)
  def readLongs = readLine().split(" ").map(_.toLong)

  val n = readInt
  val nodes = readLongs.zipWithIndex.map { case (w, id) => new Node(id, w) }

  (1 until n).foreach { _ =>
    val Array(a, b) = readInts.map(_ - 1)
    nodes(a).links += b
    nodes(b).links += a
  }

  class Node(val id: Int, val w: Long) {
    val links = mutable.ListBuffer.empty[Int]

    var done: Boolean = false
    var best: Long = 0
    var bestPair: Option[Long] = None
    var weight: Long = 0

    def main(incoming: Int): Unit = {
      if (!done) {
        val children = for {
          i <- links
          if i != incoming
        } yield nodes(i)
        children.foreach(_.main(id))

        weight = children.map(_.weight).sum + w
        val best2 = children.map(_.best).foldLeft(List[Long]()){(l, n) => (n :: l).sorted.take(2)}
        best = (weight +: best2).max
        val bestPairCur: Option[Long] = if (best2.size < 2) None else Some(best2.sum)
        val bestPairs = children.flatMap(_.bestPair) ++ bestPairCur
        bestPair = if (bestPairs.nonEmpty) Some(bestPairs.max) else None
        done = true
      }
    }
  }

  nodes(0).main(0)
  println(nodes(0).bestPair.fold("Impossible")(_.toString))
}

import scala.collection.mutable

object D extends App {
  val INF = 1000000000000000000L
  def readInts: Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs: Array[Long] = readLine().split(" ").map(_.toLong)

  val n = readInt
  val weights = readLongs

  if (n < 100000) {
    val links = Array.fill(n)(mutable.ListBuffer.empty[Int])
    (1 until n).foreach { _ =>
      val Array(a, b) = readInts.map(_ - 1)
      links(a) += b
      links(b) += a
    }

    val branchWeights = new Array[Long](n)
    val bests = new Array[Long](n)
    val bestPairs = new Array[Long](n)

    def main(cur: Int, incoming: Int): Unit = {
      val children = for {
        i <- links(cur)
        if i != incoming
      } yield i
      children.foreach(main(_, cur))

      branchWeights(cur) = children.map(branchWeights).sum + weights(cur)
      val best2 = children.map(bests).sorted.reverse.take(2)
      bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)
      val bestPairCur = if (best2.size < 2) -INF else best2.sum
      bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)
    }

    main(0, 0)
    val ans = bestPairs(0)
    if (ans == -INF) println("Impossible") else println(ans.toString)
  }
}

import scala.collection.mutable

object D extends App {
  val INF = 1000000000000000000L
  def readInts: Array[Int] = readLine().split(" ").map(_.toInt - 1)
  def readLongs: Array[Long] = readLine().split(" ").map(_.toLong)

  val n = readInt
  val weights = readLongs

  val links = Array.fill(n)(mutable.ListBuffer.empty[Int])
  (1 until n).foreach { _ =>
    val Array(a, b) = readInts
    links(a) += b
    links(b) += a
  }
  if (n < 100000) {

    val branchWeights = new Array[Long](n)
    val bests = new Array[Long](n)
    val bestPairs = new Array[Long](n)

    def main(cur: Int, incoming: Int): Unit = {
      val children = for {
        i <- links(cur)
        if i != incoming
      } yield i
      children.foreach(main(_, cur))

      branchWeights(cur) = children.map(branchWeights).sum + weights(cur)
      val best2 = children.map(bests).sorted.reverse.take(2)
      bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)
      val bestPairCur = if (best2.size < 2) -INF else best2.sum
      bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)
    }

    main(0, 0)
    val ans = bestPairs(0)
    if (ans == -INF) println("Impossible") else println(ans.toString)
  }
}

import scala.collection.mutable

object D extends App {
  val INF = 1000000000000000000L
  def readInts: Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs: Array[Long] = readLine().split(" ").map(_.toLong)

  val n = readInt
  val weights = readLongs
  val links = Array.fill(n)(mutable.ListBuffer.empty[Int])
  (1 until n).foreach { _ =>
    val Array(a, b) = readInts.map(_ - 1)
    links(a) += b
    links(b) += a
  }

  val branchWeights = new Array[Long](n)
  val bests = new Array[Long](n)
  val bestPairs = new Array[Long](n)

  def main(cur: Int, incoming: Int): Unit = {
    val children = for {
      i <- links(cur)
      if i != incoming
    } yield i
    children.foreach(main(_, cur))

    branchWeights(cur) = children.map(branchWeights).sum + weights(cur)
    val best2 = children.map(bests).sorted.reverse.take(2)
    bests(cur) = best2.headOption.foldLeft(branchWeights(cur))(Math.max)
    val bestPairCur = if (best2.size < 2) -INF else best2.sum
    bestPairs(cur) = children.map(bestPairs).foldLeft(bestPairCur)(Math.max)
  }

  if (n < 100000) main(0, 0)
  val ans = bestPairs(0)
  if (ans == -INF) println("Impossible") else println(ans.toString)
}


import scala.annotation.tailrec
import scala.io.StdIn._
import scala.math.max
object Task4 extends App {
  @tailrec def solve(ps: List[Int], acc: Int = 0): (List[Int], Int) = ps match {
    case x :: xs => solve(xs.filter(_ != x), acc + max(xs.indexOf(x), 0))
    case Nil => (Nil, acc)
  }
  val n = readInt
  val ps = readLine.split(' ').map(_.toInt).toList
  println(solve(ps)._2)
}

import scala.collection.mutable._

object Main{
  def main(args: Array[String]) {
    var n = readInt()
    val ll = LinkedList[Int]() ++ readLine.split(" ").map(_.toInt)
    var swaps = 0
    var prev = ll
    while(n != 0){
      var current = prev.next
      var pc = prev
      while(prev.elem != current.elem){
        pc = current
        current = current.next
        swaps += 1
      }
      pc.next = current.next
      prev = prev.next
      n -= 1
    }
    println(swaps)
  }
}

import scala.io.StdIn

object D {

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

    val indices = 0 until pairs

    def isOk(): Boolean = {
      indices.forall(i => arr(2 * i) == arr(2 * i + 1))
    }

    var count = 0
    def swap(i: Int, j: Int): Unit = {
      val temp = arr(i)
      arr(i) = arr(j)
      arr(j) = temp
      count += 1
    }

    while (!isOk()) {
      indices
        .find(i => arr(2 * i) != arr(2 * i + 1))
        .foreach {index =>
          val guest = arr(2 * index)
          var last = arr.lastIndexOf(guest)

          while (arr(2 * index + 1) != guest) {
            swap(last, last-1)
            last -= 1
          }
        }
    }

    println(count)
  }

}