import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_484_B {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa2)
//    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    val rows = new Array[(Int, Int)](n)
    val rowLine = readLine
    (1 to n).foreach(x => rows(x-1) = x -> rowLine.int)
    val rowsSort = rows.sortBy(_._2)
    var indIntro = 0
    var emptyInros = List[Int]()

//    var resList = List[Int]()
    var resList = new Array[Int](n*2)
    var resListInt = 0
    val pLine = readLine.string
    for (p <- 1 to 2*n) {
      val pt = pLine(p-1)
      if (pt == '0') {
        val rowTaken = rowsSort(indIntro)._1
        resList(resListInt) = rowTaken
        emptyInros ::= rowTaken
        indIntro += 1
      } else {
        val rowTaken = emptyInros.head
        emptyInros = emptyInros.tail
        resList(resListInt) = rowTaken
      }
      resListInt += 1
    }
//    resList = resList.reverse

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

    val res = new StringBuffer()
    resList.foreach(x => res.append(x+" "))
//      resList.foldLeft("")((a, b) => a + b + " ")

    outLn(res.toString())
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
2
3 1
0011
"""

val sa2 = """
6
10 8 9 11 13 5
010010011101
"""

val sa3 = """
"""
}

}

import scala.io.StdIn

object Codeforces982B {
  def main(args: Array[String]): Unit = {
    val codeforces982B = new Codeforces982B()

    val n = StdIn.readInt()
    val w = StdIn.readLine().split(" ").map(_.toInt)

    val passengers = StdIn.readLine()

    val seatNumbers = codeforces982B.getPassengersSeatNumbers(n, w, passengers)

    println(seatNumbers.mkString(" "))
  }
}

class Codeforces982B {
  def getPassengersSeatNumbers(n: Int, w: Array[Int], passengers: String): Array[Int] = {
    val seats = w.zipWithIndex.map(z => new Seat(weight = z._1, number = z._2 + 1)).sortBy(s => s.weight)

    val dummyHead = new Node(null)
    var cursor = dummyHead
    for (seat <- seats) {
      cursor.next = new Node(seat, prev = cursor)
      cursor = cursor.next
    }
    val dummyTail = new Node(null, prev = cursor)
    cursor.next = dummyTail

    var introvertCursor = dummyHead.next
    var extrovertCursor: Node = null

    val seatNumbers = passengers.map(passenger => {
      if (passenger == '0') {
        val seatNumber = introvertCursor.seat.number
        extrovertCursor = introvertCursor
        introvertCursor = introvertCursor.next
        seatNumber
      } else {
        val seatNumber = extrovertCursor.seat.number
        extrovertCursor.prev.next = extrovertCursor.next
        extrovertCursor.next.prev = extrovertCursor.prev
        extrovertCursor = extrovertCursor.prev
        seatNumber
      }
    }).toArray

    return seatNumbers

  }

  class Seat(val weight: Int, val number: Int) {}

  class Node(val seat: Seat, var prev: Node = null, var next: Node = null) {}

}


object CodeforcesRound1392C {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  // 5 3 5 3 5 3 5
  // 5 5 5 5 5 5 5
  //   2   2   2

  // 5 4 3 2 1 3 2 5
  //      ld=1
  // 5 3 3 2 2 3 2 2 5
  // 5 3 3 2 2 3 3 3 5
  // 5 3 3 2 2 3 2 2 5

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val n = rl_int
    val a = rll_int
    val res: Long = if (n == 0) {
      0L
    } else {
      val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)
      val maxai = aisorted.last
      val maxa = a(maxai)
      var increases: Long = 0L
      for (i <- 1 until n - 1) {
        val j = if (i >= maxai) i + 1 else i - 1
        if (a(i) < a(j)) {
          increases += a(j) - a(i)
        }
      }
      increases += maxa - a(n-1)
      increases
    }
    writer.println(res)
  }

//  def equalize0(a: Array[Int]): Long = {
//    val n = a.length
//    val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)
//    val maxai = aisorted.last
//    val maxa = a(maxai)
//    var curAiSortedI = 0
//    var curAi = aisorted(curAiSortedI)
//    var increases: Long = 0L
//    while (a(curAi) != maxa) {
//      val ld =
//        if ((curAi == 0) || (a(curAi - 1) - a(curAi)) <= 0) {
//          Integer.MAX_VALUE
//        } else {
//          a(curAi - 1) - a(curAi) // >= 0
//        }
//      val rd =
//        if ((curAi + 1 == n) || (a(curAi + 1) - a(curAi)) <= 0) {
//          Integer.MAX_VALUE
//        } else {
//          a(curAi + 1) - a(curAi) // >= 0
//        }
//      val d = Integer.min(ld, rd)
//      //        println(s"a[$curAi]=${a(curAi)}, ld=$ld, rd=$rd, d=$d, increases0=$increases")
//      if (d != Integer.MAX_VALUE) {
//        increases += d
//        a(curAi) += d // Not necessary?
//      }
//      curAiSortedI += 1
//      curAi = aisorted(curAiSortedI)
//    }
//    increases
//  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextLongs(n)
      var res = 0L
      for (i <- 1 until n) {
        val d = as(i) - as(i - 1)
        if (d < 0) {
          res -= d
        }
      }

      out.println(res)
    }

    out.flush()
  }

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

object CodeforcesRound1392C {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  // 5 3 5 3 5 3 5
  // 5 5 5 5 5 5 5
  //   2   2   2

  // 5 4 3 2 1 3 2 5
  //      ld=1
  // 5 3 3 2 2 3 2 2 5
  // 5 3 3 2 2 3 3 3 5
  // 5 3 3 2 2 3 2 2 5

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val n = rl_int
    val a = rll_int
    val res: Long = if (n == 0) {
      0L
    } else {
      val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)
      val maxai = aisorted.last
      val maxa = a(maxai)
      var increases = 0
      for (i <- 1 until n - 1) {
        val j = if (i >= maxai) i + 1 else i - 1
        if (a(i) < a(j)) {
          increases += a(j) - a(i)
        }
      }
      increases += maxa - a(n-1)
      increases
    }
    writer.println(res)
  }

//  def equalize0(a: Array[Int]): Long = {
//    val n = a.length
//    val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)
//    val maxai = aisorted.last
//    val maxa = a(maxai)
//    var curAiSortedI = 0
//    var curAi = aisorted(curAiSortedI)
//    var increases: Long = 0L
//    while (a(curAi) != maxa) {
//      val ld =
//        if ((curAi == 0) || (a(curAi - 1) - a(curAi)) <= 0) {
//          Integer.MAX_VALUE
//        } else {
//          a(curAi - 1) - a(curAi) // >= 0
//        }
//      val rd =
//        if ((curAi + 1 == n) || (a(curAi + 1) - a(curAi)) <= 0) {
//          Integer.MAX_VALUE
//        } else {
//          a(curAi + 1) - a(curAi) // >= 0
//        }
//      val d = Integer.min(ld, rd)
//      //        println(s"a[$curAi]=${a(curAi)}, ld=$ld, rd=$rd, d=$d, increases0=$increases")
//      if (d != Integer.MAX_VALUE) {
//        increases += d
//        a(curAi) += d // Not necessary?
//      }
//      curAiSortedI += 1
//      curAi = aisorted(curAiSortedI)
//    }
//    increases
//  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}


import scala.collection.mutable._

//https://codeforces.com/problemset/problem/893/C
object Rumor {
  var graph: Array[ArrayBuffer[Int]] = null
  var bribe: Array[Int] = null
  var vis: Array[Boolean] = null

  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    var arr = in.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val m = arr(1)
    if (m > 1) {
      bribe = in.readLine().split(" ").map(_.toInt)
      graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
      for (i <- 0 until m) {
        arr = in.readLine().split(" ").map(_.toInt - 1)
        graph(arr(0)) += arr(1)
        graph(arr(1)) += arr(0)
      }
      var minCost = 0L
      vis = Array.fill[Boolean](n)(false)
      for (i <- 0 until n) {
        if (!vis(i)) {
          val cost = new ArrayBuffer[Int]()
          cost += Int.MaxValue
          //dfs( i, cost)
          bfs(i, cost)
          minCost += cost(0)
        }
      }
      println(minCost)
    } else {
      var minCost = 0L
      println(in.readLine().split(" ").map(_.toLong).reduce(_ + _))
    }
  }

  def bfs(n: Int, minCost: ArrayBuffer[Int]): Unit = {
    val queue = Queue[Int]()
    queue.enqueue(n)
    while (!queue.isEmpty) {
      val u = queue.dequeue()
      vis(u) = true
      minCost(0) = math.min(minCost(0), bribe(u))
      for (v <- 0 until graph(u).length if (!vis(graph(u)(v)))) {
        queue.enqueue(graph(u)(v))
      }
    }
  }

  def dfs(n: Int, minCost: ArrayBuffer[Int]): Unit = {
    if (!vis(n)) {
      vis(n) = true
      minCost(0) = math.min(minCost(0), bribe(n))
      for (i <- 0 until graph(n).length if (!vis(graph(n)(i)))) {
        dfs(graph(n)(i), minCost)
      }
    }
  }
}

import scala.collection.mutable._

//https://codeforces.com/problemset/problem/893/C
object Rumor {
   def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    var arr = in.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val m = arr(1)

    val bribe = in.readLine().split(" ").map(_.toInt)
    val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for (i <- 0 until m) {
      arr = in.readLine().split(" ").map(_.toInt - 1)
      graph(arr(0)) += arr(1)
      graph(arr(1)) += arr(0)
    }
    var minCost = 0L
    val vis = Array.fill[Boolean](n)(false)
    for (i <- 0 until n) {
      if (!vis(i)) {
        val cost = new ArrayBuffer[Int]()
        cost += Int.MaxValue
        //dfs(graph,i,vis,bribe, cost)
        bfs(graph,i,vis,bribe, cost)
        minCost += cost(0)
      }
    }
    println(minCost)

  }

  def bfs(graph:Array[ArrayBuffer[Int]],n: Int,vis:Array[Boolean],bribe:Array[Int],minCost: ArrayBuffer[Int]): Unit = {
    val queue = Queue[Int]()
    queue.enqueue(n)
    while (!queue.isEmpty) {
      val u = queue.dequeue()
      vis(u) = true
      minCost(0) = math.min(minCost(0), bribe(u))
      for (v <- 0 until graph(u).length if (!vis(graph(u)(v)))) {
        queue.enqueue(graph(u)(v))
      }
    }
  }

  //DFS is throwing Memory limit exceed
  def dfs(graph:Array[ArrayBuffer[Int]],n: Int,vis:Array[Boolean],bribe:Array[Int],minCost: ArrayBuffer[Int]): Unit = {
    if (!vis(n)) {
      vis(n) = true
      minCost(0) = math.min(minCost(0), bribe(n))
      for (i <- 0 until graph(n).length if (!vis(graph(n)(i)))) {
        dfs(graph,graph(n)(i),vis,bribe, minCost)
      }
    }
  }
}

object Main extends App {

  import scala.io.StdIn

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
  val c = StdIn.readLine().split(" ").map(_.toInt)
  val g = new Array[List[Int]](n)
  for (i <- 0 until n) g(i) = List()
  val used = new Array[Boolean](n)
  for (i <- 0 until m) {
    var Array(x, y) = StdIn.readLine().split(" ").map(_.toInt-1)
    g(x) = y :: g(x)
    g(y) = x :: g(y)
  }

  var ans = 0l
  for (i <- 0 until n) {
    if (!used(i)) ans += dfs(i)
  }

  println(ans)

  def dfs(v: Int): Int = {
    used(v) = true
    var res = c(v)
    for (u <- g(v))
      if (!used(u))
        res = Math.min(res, dfs(u))
    res
  }

}

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

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

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

  class UnionFind(var size : Int){
    var parents = Array.ofDim[Int](size)
    var sizes = Array.ofDim[Int](size)

    for (i <- 0 until size) {
      parents(i) = i
      sizes(i) = 1
    }

    def findParent(node : Int): Int = {
      var p = node
      while (parents(p) != p) {
        parents(p) = parents(parents(p))
        p = parents(p)
      }
      parents(node) = p
      p
    }

    def merge(a : Int, b : Int): Unit = {
      var pA = findParent(a)
      var pB = findParent(b)

      if (pA == pB) {
        return
      }

      if (sizes(pA) < sizes(pB)) {
        parents(pB) = pA
        sizes(pA) += sizes(pB)
      } else {
        parents(pA) = pB
        sizes(pB) += sizes(pA)
      }
    }
  }

  def doCase() : Unit = {
    val Array(n, m) = readIntLine()
    val costs = readIntLine()

    val uf = new UnionFind(n + 1)
    for (_ <- 0 until m) {
      val Array(f, t) = readIntLine()
      uf.merge(f, t)
    }

    var totalCost = 0L
    for ((cost, idx) <- costs.zipWithIndex.map{case (cost, idx) => (cost, idx + 1)}.sorted) {
      if (uf.findParent(idx) != uf.findParent(0)) {
        uf.merge(idx, 0)
        totalCost += cost
      }
    }

    println(totalCost)

  }

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

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

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

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

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/893/C
object Rumor {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val bribe=in.readLine().split(" ").map(_.toInt)
    val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for(i<- 0 until m){
      arr=in.readLine().split(" ").map(_.toInt-1)
      graph(arr(0))+=arr(1)
      graph(arr(1))+=arr(0)
    }
    var minCost=0
    val vis=Array.fill[Boolean](n)(false)
    for(i<-0 until n){
      if(!vis(i)){
        val cost=new ArrayBuffer[Int]()
        cost+=Int.MaxValue
        dfs(graph,i,vis,bribe,cost)
        minCost+=cost(0)
      }
    }
    println(minCost)
  }
  def dfs(graph:Array[ArrayBuffer[Int]],n:Int,vis:Array[Boolean],bribe:Array[Int],minCost:ArrayBuffer[Int]):Unit={
    if(!vis(n)){
      vis(n)=true
      minCost(0)=math.min(minCost(0),bribe(n))
      for(i<- 0 until graph(n).length if(!vis(graph(n)(i)))){
        dfs(graph,graph(n)(i),vis,bribe,minCost)
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/893/C
object Rumor {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    if(m>1) {
      val bribe = in.readLine().split(" ").map(_.toInt)
      val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
      for (i <- 0 until m) {
        arr = in.readLine().split(" ").map(_.toInt - 1)
        graph(arr(0)) += arr(1)
        graph(arr(1)) += arr(0)
      }
      var minCost = 0L
      val vis = Array.fill[Boolean](n)(false)
      for (i <- 0 until n) {
        if (!vis(i)) {
          val cost = new ArrayBuffer[Int]()
          cost += Int.MaxValue
          dfs(graph, i, vis, bribe, cost)
          minCost += cost(0)
        }
      }
      println(minCost)
    }else{
      var minCost = 0L
      println(in.readLine().split(" ").map(_.toInt).reduce(_+_))
    }
  }
  def dfs(graph:Array[ArrayBuffer[Int]],n:Int,vis:Array[Boolean],bribe:Array[Int],minCost:ArrayBuffer[Int]):Unit={
    if(!vis(n)){
      vis(n)=true
      minCost(0)=math.min(minCost(0),bribe(n))
      for(i<- 0 until graph(n).length if(!vis(graph(n)(i)))){
        dfs(graph,graph(n)(i),vis,bribe,minCost)
      }
    }
  }
}


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

  val t = readInt()

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

    val ans = (1 to (y - x))
      .collectFirst {
        case d if (y - x) % d == 0 && (y - x + d) / d <= n => d
      }
      .map { d =>
        val ms = x.to(y, d)
        val ls = (x - d).until(0, -d).take(n - ms.length)
        val rs = (y + d).to(n * d, d).take(n - ms.length - ls.length)
        ls ++ ms ++ rs
      }
      .get

    println(ans.mkString(" "))
  }
}

//package codeforces.contests._1409

object YetAnotherArrayRestoration {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

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

      val (first, last, diff) = (0 to n - 2).map { i =>
        if ((y - x) % (i + 1) == 0) {
          val d = (y - x) / (i + 1)

          @scala.annotation.tailrec
          def loop(j: Int, r: Int = n - 2 - i): Int = if (j <= 0) j + d else if (r == 0) j else loop(j - d, r - 1)

          val f = loop(x)
          (f, f + (n - 1) * d, d)
        } else (Int.MaxValue, Int.MaxValue, Int.MaxValue)
      }.minBy(_._2)

      println {
        (first to last by diff).mkString(" ")
      }
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine.toInt
    for (_ <- 0 until t) {
      val arr = StdIn.readLine.split(" ").map(_.toInt)
      val (n, x, y) = (arr(0), arr(1), arr(2))

      def dmax(a: Int, b: Int, d: Int): (Int, Int) = {
        val n1 = (b-a) / d + 1
        if (n1 > n) (Int.MaxValue, d)
        else if (n1 == n) (b, d)
        else {
          val n2 =  (a-1) / d
          if (n1 + n2 >= n) (b, d) else {
            ((n-n1-n2) * d + b, d)
          }
        }

      }

      val (max, d) = (for (i <- 1 to y-x if (y-x) % i == 0) yield dmax(x, y, i)).minBy(_._1)

      val r = (max - (n-1)*d to max by d).mkString(" ")
      println(r)
    }
  }
}


object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val en = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val c = en.sorted
      .foldLeft((0L, 0L)) {
        case ((c, r), i) =>
          (c + (r + 1) / i, (r + 1) % i)
      }
      ._1

    println(c)
  }
}

import java.util.Scanner

object Main extends App {

  val s = new Scanner(System.in)

  var t = s.nextInt()

  for(_ <- 0 until t) {

    val n = s.nextInt()
    val es = Array.fill(n)(s.nextInt())
    scala.util.Sorting.quickSort(es)

    var i = 0
    var groups = 0

    while(i < n) {
      var gs = es(i) // requested group size
      var formed = false // did we formed the group?
      var j = i + gs - 1 // index pointing to last member of considered group

      while(j < n && !formed) {
        if (es(j) == gs) {
          formed = true
          i = j + 1
        } else {
          gs = es(j)
          j = i + gs - 1
        }
      }

      if(formed) {
        groups += 1
      } else {
        i = n
      }
    }

    println(groups)
  }
}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

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

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

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

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

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

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

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val arr = new Array[Int](n + 1)
    for (i <- 0 until n) {
      val ei = in.nextInt()
      arr(ei) = arr(ei) + 1
    }
    var result = 0

    var currentSum = 0

    for (i <- 1 to n) {
      currentSum = currentSum + arr(i)
      val newGroupCount = currentSum / i
      currentSum = currentSum - newGroupCount * i
      result = result + newGroupCount
    }

    println(result)
  }

}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val T = ni()
    REP(T) { _ =>
      val N = ni()
      val cnt = Array.fill[Int](N+1)(0)
      REP(N) { i =>
        cnt(ni()) += 1
      }

      var ans = 0L
      var rm = 0L
      REP(N+1) { i =>
        if(i > 0) {
          val x = cnt(i) + rm
          ans += (x / i)
          rm = x % i
        }
      }
      out.println(ans)
    }
  }
}

import java.util.Scanner

object Main extends App {

  val s = new Scanner(System.in)

  var t = s.nextInt()

  for(_ <- 0 until t) {

    val n = s.nextInt()

    val es = Array.fill(n)(s.nextInt())
    val ess = es.sorted(Ordering[Int].reverse)

    var i = 0
    var groups = 0

    while(i < n) {
      i += ess(i)
      groups += 1
    }

    println(groups)
  }
}

import java.util.Scanner

object Main extends App {

  val s = new Scanner(System.in)

  var t = s.nextInt()

  for(_ <- 0 until t) {

    val n = s.nextInt()

    val es = Array.fill(n)(s.nextInt())
    val ess = es.sorted(Ordering[Int].reverse)

    var i = 0
    var groups = 0

    while(i < n) {
      i += ess(i)
      groups += 1
    }

    print(groups)
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val T = ni()
    REP(T) { _ =>
      val N = ni()
      val cnt = Array.fill[Int](N+1)(0)
      REP(N) { i =>
        cnt(ni()) += 1
      }

      var ans = 0L
      REP(N) { i =>
        if(i > 0) ans += (cnt(i) / i)
      }
      out.println(ans)
    }
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val T = ni()
    REP(T) { _ =>
      val N = ni()
      val cnt = Array.fill[Int](N+1)(0)
      REP(N) { i =>
        cnt(ni()) += 1
      }

      var ans = 0L
      var rm = 0L
      REP(N) { i =>
        if(i > 0) {
          ans += (cnt(i) / i)
          val x = cnt(i) % i
          if(x + rm >= i) {
            ans +=1
            rm = x + rm - i
          } else rm += x
        }
      }
      out.println(ans)
    }
  }
}


object E{
  import scala.collection.mutable.Queue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    val A=Array.fill(n)(0)
    val B=Array.fill(n)(0)
    for(i<-0 until n){
      A(i)=nextInt
    }
    for(i<-0 until n){
      B(i)=nextInt
    }
    val nE=2*n+2
    val c=Array.ofDim[Int](nE,nE)

    val inf=Int.MaxValue
    //source
    for(i<-0 until n){
      if(A(i)>B(i)){
        //source
        c(2*n)(2*i)=A(i)-B(i)
      }
      else{
        c(2*i)(2*n+1)=B(i)-A(i)
      }
      c(2*i)(2*i+1)=A(i)
    }
    for(_<-0 until m){
      val i=nextInt-1
      val j=nextInt-1
      c(2*i+1)(2*j)=inf
      c(2*j+1)(2*i)=inf
    }
    def maximumFlow(c:Array[Array[Int]],source:Int,sink:Int):Array[Array[Int]]={
      val n=c.size
      val cr=Array.ofDim[Int](n,n)
      val f=Array.ofDim[Int](n,n)
      def shortestPath():Array[Int]={
        val s=Array.fill(n)(-1)

        val q=Queue[Int]()
        q+=source
        breakable{
          while(!q.isEmpty){

            val p=q.dequeue
            for(i<-0 until n){
              if(cr(p)(i)>0&&s(i)== -1){
                s(i)=p
                if(i==sink){
                  break
                }
                q+=i
              }
            }
          }
        }
        if(s(sink)== -1){
          return Array[Int]()
        }
        else{
          return s
        }
      }
      for(i<-0 until n){
        for(j<-0 until n){
          if(c(i)(j)>0){
            cr(i)(j)=c(i)(j)
          }
        }
      }
      var s=shortestPath
      while(s.size>0){

        var p=sink
        var min=Int.MaxValue
        while(p!=source){
          min=Math.min(min,cr(s(p))(p))
          p=s(p)

        }
        p=sink
        while(p!=source){
          if(c(s(p))(p)>0){
            f(s(p))(p)+=min
          }else{
            f(p)(s(p))-=min
          }
          //out.println(s"${s(p)->p}")
          cr(s(p))(p)-=min
          cr(p)(s(p))+=min
          p=s(p)
        }
//        out.println(min)
        s=shortestPath
      }
      return f
    }
    val f=maximumFlow(c,2*n,2*n+1)
//    for(i<-f){for(j<-i){out.print(j+" ")};out.println()}
    var solve=true
    for(i<-0 until n){
      if(f(2*n)(2*i)<c(2*n)(2*i)){
        solve=false
      }
      if(f(2*i)(2*n+1)<c(2*i)(2*n+1)){
        solve=false
      }
    }
    if(solve){
      out.println("YES")
      for(i<-0 until n){
        for(j<-0 until n){
          if(i==j){
            out.print((A(i)-f(2*i)(2*i+1))+" ")
          }else{
            out.print(f(2*i+1)(2*j)+" ")
          }

        }
        out.println()
      }
    }
    else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}

object E{
  import scala.collection.mutable.Queue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    val A=Array.fill(n)(0)
    val B=Array.fill(n)(0)
    for(i<-0 until n){
      A(i)=nextInt
    }
    for(i<-0 until n){
      B(i)=nextInt
    }
    val nE=2*n+2
    val c=Array.ofDim[Int](nE,nE)

    val inf=Int.MaxValue
    //source
    for(i<-0 until n){
      if(A(i)>B(i)){
        //source
        c(2*n)(2*i)=A(i)-B(i)
      }
      else{
        c(2*i)(2*n+1)=B(i)-A(i)
      }
      c(2*i)(2*i+1)=A(i)
    }
    for(_<-0 until m){
      val i=nextInt-1
      val j=nextInt-1
      c(2*i+1)(2*j)=inf
      c(2*j+1)(2*i)=inf
    }
    def maximumFlow(c:Array[Array[Int]],source:Int,sink:Int):Array[Array[Int]]={
      val n=c.size
      val cr=Array.ofDim[Int](n,n)
      val f=Array.ofDim[Int](n,n)
      def shortestPath():Array[Int]={
        val s=Array.fill(n)(-1)

        val q=Queue[Int]()
        q+=source
        breakable{
          while(!q.isEmpty){

            val p=q.dequeue
            for(i<-0 until n){
              if(cr(p)(i)>0&&s(i)== -1){
                s(i)=p
                if(i==sink){
                  break
                }
                q+=i
              }
            }
          }
        }
        if(s(sink)== -1){
          return Array[Int]()
        }
        else{
          return s
        }
      }
      for(i<-0 until n){
        for(j<-0 until n){
          if(c(i)(j)>0){
            cr(i)(j)=c(i)(j)
          }
        }
      }
      var s=shortestPath
      while(s.size>0){

        var p=sink
        var min=Int.MaxValue
        while(p!=source){
          min=Math.min(min,cr(s(p))(p))
          p=s(p)

        }
        p=sink
        while(p!=source){
          if(c(s(p))(p)>0){
            f(s(p))(p)+=min
          }else{
            f(p)(s(p))-=min
          }
          //out.println(s"${s(p)->p}")
          cr(s(p))(p)-=min
          cr(p)(s(p))+=min
          p=s(p)
        }
//        out.println(min)
        s=shortestPath
      }
      return f
    }
    val f=maximumFlow(c,2*n,2*n+1)
//    for(i<-f){for(j<-i){out.print(j+" ")};out.println()}
    var solve=true
    for(i<-0 until n){
      if(f(2*n)(2*i)<c(2*n)(2*i)){
        solve=false
      }
      if(f(2*i)(2*n+1)<c(2*i)(2*n+1)){
        solve=false
      }
    }
    if(solve){
      out.println("YES")
      for(i<-0 until n){
        for(j<-0 until n){
          out.print(f(2*i+1)(2*j)+" ")

        }
        out.println()
      }
    }
    else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}


//18:45 - 21:55
import scala.io.StdIn.readLine
object C1336 {

  //it can return a.length if nothing is found
  def moveToNext(a:Array[(Int,String)],letter:String,currIndex:Int):Int ={
    assert(currIndex<a.length && currIndex>=0,"currIndex out of bounds")
    var j = currIndex + 1
    while(j < a.length && a(j)._2 != letter){
      j = j+1
    }
    j
  }
  //which letter didn't show up in the sequence yet?
  def returnMissing(s:String) ={
    assert(s.length ==2)
    if(!s.contains("A")){"A"}else
      if(!s.contains("B")){"B"}else{"C"}
  }

  def currAndPrevSymbol(a:Array[(Int,String)],j:Int,prevState:String)={

    (a(j)._2, prevState) match {
      case (_,"") => a(j)._2
      case (_,s2) if s2.length == 1 => s2+a(j)._2
      case (s1,s2) if s1==s2(1).toString => prevState//A BA-> BA
      case (s1,s2) if s1!=s2(1).toString => s2(1)+a(j)._2
    }
  }

  def mainFun(a:Array[(Int,String)],f:(Long,Long,Long)=>Long):Long={
    var mainCounter = 0 //main counter

    var lastA = -1
    var lastB = -1
    var lastC = -1

    var nextZ = -1

    var currentBlockPrefix = "" //first  two letters eg AB
    var nextSymbol = "" // eg if current block AB then C is missing

    var minVal = Long.MaxValue
    var currentVal = Long.MaxValue

    def lastX(letter:Char)={
      letter match{
        case 'A' => lastA
        case 'B' => lastB
        case 'C' => lastC
      }
    }

    while(mainCounter<a.length-1){

      //println(mainCounter)
      if(a(mainCounter)._2 == "A"){lastA=a(mainCounter)._1; currentBlockPrefix = currAndPrevSymbol(a, mainCounter,currentBlockPrefix)}
      if(a(mainCounter)._2 == "B"){lastB=a(mainCounter)._1; currentBlockPrefix = currAndPrevSymbol(a, mainCounter,currentBlockPrefix)}
      if(a(mainCounter)._2 == "C"){lastC=a(mainCounter)._1; currentBlockPrefix = currAndPrevSymbol(a, mainCounter,currentBlockPrefix)}

      //println(s"lastABC ${lastA},${lastB},${lastC}")

      if(mainCounter>=1 && mainCounter<a.length) {
        currentBlockPrefix = currAndPrevSymbol(a, mainCounter,currentBlockPrefix) //eg "AB"
        nextSymbol = returnMissing(currentBlockPrefix)
        nextZ = if(mainCounter==1 || mainCounter==nextZ){moveToNext(a, nextSymbol, mainCounter)}else{nextZ}

        //if((moveToNext(a, nextSymbol, mainCounter)<a.length)) {
          currentVal =if((nextZ<a.length) && Array("AB","BC","CA","BA","AC","CB").contains(currentBlockPrefix)  ) {
            //println(s"${lastX(currentBlockPrefix(0))}, ${a(mainCounter)._1}, ${a(moveToNext(a, nextSymbol, mainCounter))._1}")
            f(lastX(currentBlockPrefix(0)), a(mainCounter)._1, a(nextZ)._1)}else{currentVal} //      println(currentVal)
          //println(s"current value ${currentVal}")
          if (currentVal < minVal) {
            minVal = currentVal
          }
        //}

      }
      mainCounter = mainCounter+1
      //println(minVal)
    }
    minVal
  }

  def CalcFromInput(str:String)={

    val lines = str.split("\n")
    val t = lines(0).trim.toInt
    //println(t) //1<= t <100
    def f(x:Long,y:Long,z:Long):Long = (x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x)
    for(i <-(0 to t-1)){
      val Array(nA,nB,nC) = lines(1+4*i).trim.split(" ")
      //println(s"${nA} ${nB} ${nC}")
      val a0 = lines(1+4*i+1).trim.split(" ").map(_.toInt)
      val b0 = lines(1+4*i+2).trim.split(" ").map(_.toInt)
      val c0 = lines(1+4*i+3).trim.split(" ").map(_.toInt)
      //println(a0.mkString(","))
      //println(b0.mkString(","))
      //println(c0.mkString(","))
      val a = a0.map(x=>(x,"A"))
      val b = b0.map(x=>(x,"B"))
      val c = c0.map(x=>(x,"C"))

      val concat = (a++b++c).sortBy(_._1)
      //println(concat.map(x=>s"${x._1} ${x._2}").mkString(","))
      println(mainFun(concat,f))
    }
    //val Array(nA,nB,nC) = lines(1).split(' ')

    //val a = line()
    //println(s"${nA} ${nB} ${nC}")
  }

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

    //val lines = str.split("\n")
    val t = readLine.trim.toInt
    //println(t) //1<= t <100
    def f(x:Long,y:Long,z:Long):Long = (x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x)
    for(i <-(0 to t-1)){
      val Array(nA,nB,nC) = readLine.trim.split(" ")
      //println(s"${nA} ${nB} ${nC}")
      val a0 = readLine.trim.split(" ").map(_.toInt)
      val b0 = readLine.trim.split(" ").map(_.toInt)
      val c0 = readLine.trim.split(" ").map(_.toInt)
      //println(a0.mkString(","))
      //println(b0.mkString(","))
      //println(c0.mkString(","))
      val a = a0.map(x=>(x,"A"))
      val b = b0.map(x=>(x,"B"))
      val c = c0.map(x=>(x,"C"))

      val concat = (a++b++c).sortBy(_._1)
      //println(concat.map(x=>s"${x._1} ${x._2}").mkString(","))
      println(mainFun(concat,f))
    }
  }

}
object C1336Tests extends App{
  import C1336._

  //val a: Array[(Int,String)]= Array((0,"C"),(0,"A"),(1,"B"),(5,"B"),(9,"B"),(10,"C"))
  val a: Array[(Int,String)]= Array((0,"A"),(1,"B"),(5,"B"),(10,"C"),(20,"A"))

  def runTests(): Unit ={
    //2 error found thx to this
    //println(moveToNext(a,"C",0)==5)
    //println(moveToNext(a,"B",0)==2)
    //println(moveToNext(a,"B",2)==3)
    //println(moveToNext(a,"C",5)==6)

    //println(returnMissing("AB")=="C")
    //println(returnMissing("BC")=="A")
    //println(returnMissing("CA")=="B")

    //for(i <- 1 to a.length-1){
    //  print(currAndPrevSymbol(a,i))
    //  print(",")
    //}
    //CABBBC
    //println(currAndPrevSymbol(a,0,"")=="C")
    //println(currAndPrevSymbol(a,1,"C")=="CA")
    //println(currAndPrevSymbol(a,2,"CA")=="AB")
    //println(currAndPrevSymbol(a,3,"AB") =="AB")
    //println(currAndPrevSymbol(a,4,"AB") =="AB")
    //println(currAndPrevSymbol(a,5,"AB")=="BC")
    //println(currAndPrevSymbol(a,6,"C")=="CA")
    //def f(x:Int,y:Int,z:Int) = (x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x)
    //mainFun(a,f)
    val input = """5
    2 2 3
    7 8
    6 3
    3 1 4
    1 1 1
    1
    1
    1000000000
    2 2 2
    1 2
    5 4
    6 7
    2 2 2
    1 2
    3 4
    6 7
    3 4 1
    3 2 1
    7 3 3 4
    6"""
  CalcFromInput(input)

  }
  runTests()
}

import scala.io.StdIn

object Solution_D extends App {
  val T = StdIn.readInt()

  def getCurrent(a0: Array[Long], a1: Array[Long], a2: Array[Long], positions: Array[Int]): Long = {
    val x = a0(positions(0)) - a1(positions(1))
    val y = a0(positions(0)) - a2(positions(2))
    val z = a1(positions(1)) - a2(positions(2))
    x * x + y * y + z * z
  }

  def findBestMove(a0: Array[Long], a1: Array[Long], a2: Array[Long], positions: Array[Int]): Int = {
    val current = getCurrent(a0, a1, a2, positions)
    var bestIdx = -1
    var bestSoFar = Long.MaxValue
    val sizes = Array(a0.size, a1.size, a2.size)
    for (pos <- 0 until 3) {
      if (positions(pos) < sizes(pos) - 1) {
        positions(pos) += 1
        val move = getCurrent(a0, a1, a2, positions)
        if (move - current < bestSoFar) {
          bestSoFar = move - current
          bestIdx = pos
        }
        positions(pos) -= 1
      }
    }
    bestIdx
  }
  for (t <- 1 to T) {
    val input = StdIn.readLine().split(' ').map{_.toInt}
    val Nr = input(0)
    val Ng = input(1)
    val Nb = input(2)
    val a0 = StdIn.readLine().split(' ').map{_.toLong}.sorted
    val a1 = StdIn.readLine().split(' ').map{_.toLong}.sorted
    val a2 = StdIn.readLine().split(' ').map{_.toLong}.sorted
    val positions = Array(0, 0, 0)
    var stop = false
    var result = getCurrent(a0, a1, a2, positions)
    while (!stop) {
      val best = findBestMove(a0, a1, a2, positions)
      if (best == -1) {
        stop = true
      } else {
        positions(best) += 1
        result = Math.min(result, getCurrent(a0, a1, a2, positions))
      }
    }
    println(result)
  }
}


object C {

  case class Rect(x1: Long, y1: Long, x2: Long, y2: Long)

  def splitV1(r: Rect, x: Int) = {
    if (x >= r.x2 || x <= r.x1) {
      Array(r)
    } else {
      Array(r.copy(x2 = x), r.copy(x1=x))
    }
  }

  def splitH1(r: Rect, y: Int) = {
    if (y >= r.y2 || y <= r.y1) {
      Array(r)
    } else {
      Array(r.copy(y2 = y), r.copy(y1=y))
    }
  }

  def splitV(r: Array[Rect], x: Int) = {
    r.flatMap(r => splitV1(r, x))
  }

  def splitH(r: Array[Rect], y: Int) = {
    r.flatMap(r => splitH1(r, y))
  }

  def in(r: Rect, o: Rect) = {
    if (r.x2 <= o.x2 && r.x1 >= o.x1 && r.y2 <= o.y2 && r.y1 >= o.y1) true
    else false
  }

  def getWhites(r: Rect) = {
    val a = r.x2 - r.x1
    val b = r.y2 - r.y1
    val t = (a * b)
    if (t % 2 == 0) {
      t / 2
    } else {
      if ((r.x1 + r.y1) % 2 == 0) {
        t / 2 + 1
      } else {
        t / 2
      }
    }
  }

  def main(args: Array[String]) = {
    val scanner = new java.util.Scanner(System.in)
    val t = scanner.nextInt
    (0 until t).foreach{_ =>
      val (n, m) = (scanner.nextInt(), scanner.nextInt())
      val (x1,y1,x2,y2) = (scanner.nextInt(), scanner.nextInt(), scanner.nextInt(), scanner.nextInt())
      val (x3,y3,x4,y4) = (scanner.nextInt(), scanner.nextInt(), scanner.nextInt(), scanner.nextInt())
      var rects = Array(Rect(1, 1, m+1, n+1))
      rects = splitV(rects, x = x1)
      rects = splitV(rects, x = x2+1)
      rects = splitV(rects, x = x3)
      rects = splitV(rects, x = x4+1)
      rects = splitH(rects, y = y1)
      rects = splitH(rects, y = y2+1)
      rects = splitH(rects, y = y3)
      rects = splitH(rects, y = y4+1)
      val white = Rect(x1, y1, x2+1, y2+1)
      val black = Rect(x3, y3, x4+1, y4+1)
      val (w, b) = rects.map{r =>
        val s = (r.x2 - r.x1) * (r.y2 - r.y1)
        if (in(r, black)) {
          (0L, s)
        } else if (in(r, white)) {
          (s, 0L)
        } else {
          val w = getWhites(r)
          (w, s-w)
        }
      }.reduce((a, b) => (a._1 + b._1, a._2 + b._2))
      System.out.println(w + " " + b)
    }
  }
}

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

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

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

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

  case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)

  def solve(): Unit = {

    /**
      * @return (white, black)
      */
    def count(r: Rect): (Long, Long) = {
      val s = max(0, r.x2 - r.x1 + 1).toLong * max(0, r.y2 - r.y1 + 1)
      if (s == 0) (0, 0)
      else if (s % 2 == 0) (s / 2, s / 2)
      else {
        // 0 == white, 1 == black
        def tpe(x: Int, y: Int): Int = {
          if (y % 2 == 1) {
            if (x % 2 == 1) 0
            else 1
          } else {
            if (x % 2 == 1) 1
            else 0
          }
        }

        tpe(r.x1, r.y1) match {
          case 0 => (s / 2 + 1, s / 2)
          case 1 => (s / 2, s / 2 + 1)
        }
      }
    }

    rep(ni()) { _ =>
      val n, m = ni()
      val x1, y1, x2, y2 = ni()
      val x3, y3, x4, y4 = ni()

      val wRec = Rect(x1, y1, x2, y2)
      val bRec = Rect(x3, y3, x4, y4)

      val dupRec = {
        val l = max(x1, x3)
        val r = min(x2, x4)
        val b = max(y1, y3)
        val t = min(y2, y4)
        Rect(l, b, r, t)
      }

      val (bw, bb) = count(bRec)
      val (ww, wb) = count(wRec)
      val (dw, db) = count(dupRec)

      val s = n.toLong * m
      val b = s / 2 + bw - (wb - db)
      val w = s - b
      out.println(s"$w $b")
    }
  }

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

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

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

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

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

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

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

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

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

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

  case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)

  def solve(): Unit = {

    /**
      * @return (white, black)
      */
    def count(r: Rect): (Long, Long) = {
      val s = (r.x2 - r.x1 + 1).toLong * (r.y2 - r.y1 + 1)
      if (s % 2 == 0) (s / 2, s / 2)
      else {
        // 0 == white, 1 == black
        def tpe(x: Int, y: Int): Int = {
          if (y % 2 == 1) {
            if (x % 2 == 1) 0
            else 1
          } else {
            if (x % 2 == 1) 1
            else 0
          }
        }

        tpe(r.x1, r.y1) match {
          case 0 => (s / 2 + 1, s / 2)
          case 1 => (s / 2, s / 2 + 1)
        }
      }
    }

    rep(ni()) { _ =>
      val n, m = ni()
      val x1, y1, x2, y2 = ni()
      val x3, y3, x4, y4 = ni()

      val wRec = Rect(x1, y1, x2, y2)
      val bRec = Rect(x3, y3, x4, y4)

      val dupRec = {
        val l = max(x1, x3)
        val r = min(x2, x4)
        val b = max(y1, y3)
        val t = min(y2, y4)
        Rect(l, b, r, t)
      }

      val (bw, bb) = count(bRec)
      val (ww, wb) = count(wRec)
      val (rw, rb) = count(dupRec)

      val s = n.toLong * m
      val b = s / 2 + bw - (wb - rb)
      val w = s - b
      out.println(s"$w $b")
    }
  }

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

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

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

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

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

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

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

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

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

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

  case class Rect(x1: Int, y1: Int, x2: Int, y2: Int)

  def solve(): Unit = {

    /**
      * @return (white, black)
      */
    def count(r: Rect): (Long, Long) = {
      val s = (r.x2 - r.x1 + 1).toLong * (r.y2 - r.y1 + 1)
      if (s < 0) (0, 0)
      else if (s % 2 == 0) (s / 2, s / 2)
      else {
        // 0 == white, 1 == black
        def tpe(x: Int, y: Int): Int = {
          if (y % 2 == 1) {
            if (x % 2 == 1) 0
            else 1
          } else {
            if (x % 2 == 1) 1
            else 0
          }
        }

        tpe(r.x1, r.y1) match {
          case 0 => (s / 2 + 1, s / 2)
          case 1 => (s / 2, s / 2 + 1)
        }
      }
    }

    rep(ni()) { _ =>
      val n, m = ni()
      val x1, y1, x2, y2 = ni()
      val x3, y3, x4, y4 = ni()

      val wRec = Rect(x1, y1, x2, y2)
      val bRec = Rect(x3, y3, x4, y4)

      val dupRec = {
        val l = max(x1, x3)
        val r = min(x2, x4)
        val b = max(y1, y3)
        val t = min(y2, y4)
        Rect(l, b, r, t)
      }

      val (bw, bb) = count(bRec)
      val (ww, wb) = count(wRec)
      val (dw, db) = count(dupRec)

      val s = n.toLong * m
      val b = s / 2 + bw - (wb - db)
      val w = s - b
      out.println(s"$w $b")
    }
  }

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

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

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

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

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

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


/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
    (a,b) match {
      case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
      case (Nil, Nil) => Nil
    }
  }
  def printList(a: Linst):Any ={
    a match{
      case Nil => None
      case b::tail => print(b + " "); printList(tail)
    }
  }
  def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
    val t = b.splitAt(idx)
    t._1 ++ List(byWhat) ++ t._2.tail
  }
  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
    b match {
      case Nil => false
      case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
      case a :: tail => existsDup(tail, num, pos, currPos + 1)
    }
  }
  def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    replace(a, drop, pos - 1)
  }
  def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)
    else replace(a, drop, pos2 - 1)
  }
  val n = StdIn.readLine().toInt
  val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val diff = findDifferences(A,B,1)
  println()
  diff.length match {
    case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))
    case 2 => {if(diff.head._2 == diff.tail.head._2)printList(fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3))
               else printList(fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3))}

  }
}

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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

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

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

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

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

    override def toString = s"MultiHashSet($map)"
  }

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

  def test(ans: Array[Int], a: Array[Int]): Boolean = {
    var diff = 0
    for (i <- 0 until ans.length) {
      if (ans(i) != a(i)) {
        diff += 1
      }
    }
    diff == 1
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    val set = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      b(i) = nextInt
      set += (i + 1)
    }
    val ans = new Array[Int](n)
    for (i <- 0 until n) {
      if (a(i) == b(i)) {
        ans(i) = a(i)
        set -= (ans(i))
      }
    }
    val firstPos = ans.indexOf(0)
    val remains = set.iterator.toList
    if (set.size == 1) {
      ans(firstPos) = remains.head
    } else if (set.size == 2) {
      ans(firstPos) = remains.head
      val lastPos = ans.lastIndexOf(0)
      ans(lastPos) = remains.last
      if (test(ans, a) && test(ans, b)) {
      } else {
        ans(firstPos) = remains.last
        ans(lastPos) = remains.head
      }
    }
    ans.foreach(x => print(s"$x "))
    return 0
  }
}

object EightOneFourB {
  def checkIfAllElementPresent(seq: Seq[Int]): Boolean = {
    val list = (1 to seq.size + 1).toArray.map(_ => 0)
    list(0) = 1
    seq.foreach(p => list(p) = 1)
    list.filter(_ == 0).size == 0
  }

  def findTheMissingElement(seq: Seq[Int]): Option[Int] = {
    val list = (1 to seq.size + 1).toArray.map(_ => 0)
    list(0) = 1
    seq.foreach(p => list(p) = 1)
    val result = list.zipWithIndex.filter(p => p._1 == 0)
    if (result.size > 0) Some(result.head._2) else None
  }

  def main(args: Array[String]): Unit = {
    val input = readLine()
    val stringA = readLine().toString.split(" ").map(_.toInt)
    val stringB = readLine().toString.split(" ").map(_.toInt)
    val missingAElement = findTheMissingElement(stringA)
    val missingBElement = findTheMissingElement(stringB)

    val permutations = stringA.zip(stringB).zipWithIndex
      .filter {
        case ((a, b), index) => {
          a != b
        }
      }
      .flatMap {
        case ((a, b), index) => {
          List(stringA.patch(index, List(missingAElement.getOrElse(a)), 1)
            , stringB.patch(index, List(missingBElement.getOrElse(b)), 1))
        }
      }

    println(permutations
      .filter(checkIfAllElementPresent(_))
      .filter(stringA.zip(_).filter(p => p._1 != p._2).size <= 1)
      .filter(stringB.zip(_).filter(p => p._1 != p._2).size <= 1)
      .head.mkString(" "))
  }
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  type Lin3st = List[(Int,Int,Int)]
  /*  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
      (a,b) match {
        case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
        case (Nil, Nil) => Nil
      }
    } // перекодено
   def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
   val t = b.splitAt(idx)
   t._1 ++ List(byWhat) ++ t._2.tail
  } //перекодено*/
def repl(b:Linst,e:Int,idx:Int):Linst = b.foldRight[(Linst,Int)](Nil,b.length-1)((i,T) => ((if(T._2 == idx) e else i) :: T._1,T._2 - 1))._1
def findDrop(b:Linst) = nats.filter(v => !b.contains(v)).head
def dupExists(d:Linst, e: Int, p:Int) = d.foldLeft[(Boolean,Int)]((false,0))((T,i) => (if(T._1)true else i == e && p != T._2,T._2 + 1))._1
/*  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
 b match {
   case Nil => false
   case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
   case a :: tail => existsDup(tail, num, pos, currPos + 1)
 }
}//перекодено
def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
   val nats = Stream.from(1,1).take(a.length).toList
   val drop = nats.filter(v => !a.contains(v)).head
   replace(a, drop, pos - 1)
 } // перекодено
 def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
   val nats = Stream.from(1,1).take(a.length).toList
   val drop = nats.filter(v => !a.contains(v)).head
   if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)
   else replace(a, drop, pos2 - 1)
 } // на очереди*/
def fixTransp2(a:Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) = repl(a,findDrop(a), if(dupExists(a,num1,pos1)) pos1 else pos2)
val n = StdIn.readLine().toInt
val nats = Stream.from(1,1).take(n).toList
val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
val diff = A.foldLeft[(Lin3st,Linst,Int)]((Nil,B,0))((T,i)=>(if(T._2.head != i)(i,T._2.head,T._3) :: T._1 else T._1,T._2.tail,T._3+1))._1
println((if(diff.length == 1) repl(A,findDrop(A),diff.head._3)
else if(diff.head._2 == diff.tail.head._2) fixTransp2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)
else fixTransp2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)).mkString(" "))
/*val AB = for(
 i <- nats;
 a <- A;
 b <- B
) yield (a,b,i)*/

/* val diff = findDifferences(A,B,1)
println(
diff.length match {
 case 1 => fixTransposition(A, diff.head._1, diff.head._3).mkString(" ")
 case 2 => {if(diff.head._2 == diff.tail.head._2)fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)
            else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)}.mkString(" ")

}
)*/
}

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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

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

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

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

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

    override def toString = s"MultiHashSet($map)"
  }

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    val set = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      b(i) = nextInt
      set += (i + 1)
    }
    val ans = new Array[Int](n)
    for (i <- 0 until n) {
      if (a(i) == b(i)) {
        ans(i) = a(i)
        set -= (ans(i))
      }
    }
    if (set.size == 1) {
      ans(ans.indexOf(0)) = set.iterator.toList.head
    } else if (set.size == 2) {
      ans(ans.indexOf(0)) = set.iterator.toList.head
      ans(ans.lastIndexOf(0)) = set.iterator.toList.last
    } else {
      throw new RuntimeException()
    }
    ans.foreach(x => print(s"$x "))
    return 0
  }
}

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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

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

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

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

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

    override def toString = s"MultiHashSet($map)"
  }

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

  def test(ans: Array[Int], a: Array[Int]): Boolean = {
    var diff = 0
    for (i <- 0 until ans.length) {
      if (ans(i) != a(i)) {
        diff += 1
      }
    }
    diff == 1
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    val set = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      b(i) = nextInt
      set += (i + 1)
    }
    val ans = new Array[Int](n)
    for (i <- 0 until n) {
      if (a(i) == b(i)) {
        ans(i) = a(i)
        set -= (ans(i))
      }
    }
    val firstPos = ans.indexOf(0)
    val remains = set.iterator.toList
    if (set.size == 1) {
      ans(firstPos) = remains.head
    } else if (set.size == 2) {
      ans(firstPos) = remains.head
      val lastPos = ans.lastIndexOf(0)
      ans(lastPos) = remains.last
      if (test(ans, a) || test(ans, b)) {
        ans(firstPos) = remains.last
        ans(lastPos) = remains.head
      }
    }
    ans.foreach(x => print(s"$x "))
    return 0
  }
}

object EightOneFourB {
  def checkIfAllElementPresent(seq: Seq[Int]): Boolean = {
    val list = (1 to seq.size + 1).toArray.map(_ => 0)
    list(0) = 1
    seq.foreach(p => list(p) = 1)
    list.filter(_ == 0).size == 0
  }

  def findTheMissingElement(seq: Seq[Int]): Option[Int] = {
    val list = (1 to seq.size + 1).toArray.map(_ => 0)
    list(0) = 1
    seq.foreach(p => list(p) = 1)
    val result = list.zipWithIndex.filter(p => p._1 == 0)
    if (result.size > 0) Some(result.head._2) else None
  }

  def main(args: Array[String]): Unit = {
    val input = readLine()
    val stringA = readLine().toString.split(" ").map(_.toInt)
    val stringB = readLine().toString.split(" ").map(_.toInt)
    val missingAElement = findTheMissingElement(stringA)
    val missingBElement = findTheMissingElement(stringB)

    val permutations = stringA.zip(stringB).zipWithIndex
      .filter {
        case ((a, b), index) => {
          a != b
        }
      }
      .flatMap {
        case ((a, b), index) => {
          List(stringA.patch(index, List(missingAElement.getOrElse(a)), 1)
            , stringB.patch(index, List(missingBElement.getOrElse(b)), 1))
        }
      }

    println(permutations.filter(checkIfAllElementPresent(_)).head.mkString(" "))
  }
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
    (a,b) match {
      case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
      case (Nil, Nil) => Nil
    }
  }
  def printList(a: Linst):Any ={
    a match{
      case Nil => None
      case b::tail => print(b + " "); printList(tail)
    }
  }
  def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
    val t = b.splitAt(idx)
    t._1 ++ List(byWhat) ++ t._2.tail
  }
  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
    b match {
      case Nil => false
      case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
      case a :: tail => existsDup(tail, num, pos, currPos + 1)
    }
  }
  def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    replace(a, drop, pos - 1)
  }
  def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)
    else replace(a, drop, pos2 - 1)
  }
  def check(a: Linst, p: Linst, i1: Int):Boolean ={
    if( a.isEmpty) i1 == 1
    else if(a.head != p.head) check(a.tail, p.tail, i1 + 1)
    else check(a.tail, p.tail, i1 + 1)
  }
  val n = StdIn.readLine().toInt
  val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val diff = findDifferences(A,B,1)
  println()
  diff.length match {
    case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))
    case 2 => printList({
      val v1 = fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)
      if(check(A,v1,0) && check(B,v1,0)) v1 else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)
    })
  }
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
    (a,b) match {
      case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
      case (Nil, Nil) => Nil
    }
  }
  def printList(a: Linst):Any ={
    a match{
      case Nil => None
      case b::tail => print(b + " "); printList(tail)
    }
  }
  def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
    val t = b.splitAt(idx)
    t._1 ++ List(byWhat) ++ t._2.tail
  }
  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
    b match {
      case Nil => false
      case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
      case a :: tail => existsDup(tail, num, pos, currPos + 1)
    }
  }
  def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    replace(a, drop, pos - 1)
  }
  def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    if (num1 == drop) replace(a, drop, pos1 - 1)
    else replace(a, drop, pos2 - 1)
  }
  def check(a: Linst, p: Linst, i1: Int):Boolean ={
    if( a.isEmpty) i1 == 1
    else if(a.head != p.head) check(a.tail, p.tail, i1 + 1)
    else check(a.tail, p.tail, i1 + 1)
  }
  val n = StdIn.readLine().toInt
  val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val diff = findDifferences(A,B,1)
  println()
  diff.length match {
    case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))
    case 2 => printList({
      val v1 = fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3)
      if(check(A,v1,0) && check(B,v1,0)) v1 else fixTransposition2(B, diff.head._2, diff.head._3, diff.tail.head._2, diff.tail.head._3)
    })
  }
}

/**
  * Created by Hyper on 22.06.2017.
  */
import javax.imageio.spi.ServiceRegistry.Filter

import scala.io.StdIn
object cf extends App{
  type Linst = List[Int]
  def findDifferences (a: Linst, b: Linst, i: Int): List[(Int,Int,Int)] ={
    (a,b) match {
      case (u :: utail, v :: vtail) => if( u == v ) findDifferences(utail, vtail, i + 1) else (u,v,i) :: findDifferences(utail, vtail, i + 1)
      case (Nil, Nil) => Nil
    }
  }
  def printList(a: Linst):Any ={
    a match{
      case Nil => None
      case b::tail => print(b + " "); printList(tail)
    }
  }
  def replace(b: List[Int], byWhat: Int, idx: Int): List[Int] ={
    val t = b.splitAt(idx)
    t._1 ++ List(byWhat) ++ t._2.tail
  }
  def existsDup(b: Linst, num: Int, pos: Int, currPos: Int): Boolean ={
    b match {
      case Nil => false
      case `num` :: tail => if(currPos != pos) true else existsDup(tail, num, pos, currPos + 1)
      case a :: tail => existsDup(tail, num, pos, currPos + 1)
    }
  }
  def fixTransposition(a: Linst, num: Int, pos: Int):Linst={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    replace(a, drop, pos - 1)
  }
  def fixTransposition2(a: Linst, num1: Int, pos1: Int, num2: Int, pos2: Int) ={
    val nats = Stream.from(1,1).take(a.length).toList
    val drop = nats.filter(v => !a.contains(v)).head
    if (existsDup(a, num1, pos1, 1)) replace(a, drop, pos1 - 1)
    else replace(a, drop, pos2 - 1)
  }
  val n = StdIn.readLine().toInt
  val A = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val B = StdIn.readLine().split(" ").toList.map(s => s.toInt)
  val diff = findDifferences(A,B,1)
  println()
  diff.length match {
    case 1 => printList(fixTransposition(A, diff.head._1, diff.head._3))
    case 2 => printList(fixTransposition2(A, diff.head._1, diff.head._3, diff.tail.head._1, diff.tail.head._3))
  }
}