Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.

A single input line contains a single integer n (1 ≤ n ≤ 105).

Print a single integer — the answer to the problem without leading zeroes, or "-1" (without the quotes), if the number that meet the problem condition does not exist.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val x = 2 * 3 * 5 * 7
  val n = in.next().toInt
  if (n < 3)
    println(-1)
  else if (n == 3)
    println("210")
  else {
    val t = n - 3
    val left = Map(0 -> "110", 1 -> "050", 2 -> "080", 3 -> "170", 4 -> "020", 5 -> "200")(t % 6)
    println("1" + "0" * (n - 4) + left)
  }
}

object B248 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    if(n < 3)
      println("-1")
    else
      println((BigInt(10).pow(n-1)/210 + 1)*210)
  }

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

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import java.util.Scanner
import java.math._

object B extends App
{
	val cin=new Scanner(System.in)
	val n=cin.nextInt()
	if(n<3) println(-1)
	else if(n==3) println(210)
	else
	{
		val mod=math.BigInt(10).modPow(math.BigInt((n-1).toString),math.BigInt(210)).toInt
		val add=210-mod
		println("1"+"0"*(n-4+3-add.toString.length)+add)
	}
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}
    if(n==3){println(210);exit}

    var last=7-(1 until n-1).foldLeft(1){(x,y)=>x*10%7}
    while((last.toString.map(_-'0').sum+1)%3!=0) last+=7
    println("1"+"0"*(n-2-last.toString.length)+last+"0")
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}
    if(n==3){println(210);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

    var last=7-dp(n-2)
    while((last.toString.map(_-'0').sum+1)%3!=0) last+=7
    println("1"+"0"*(n-2-last.toString.length)+last+"0")
}

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

    val n=readLine.toInt

    if(n<=2){
      println(-1)
    }else if(n==3){
      println(210)
    }else{
      val amari=
        (1 to n-1).fold(1)((x,y)=> x*10%210)

      val add=210-amari
      print("1")
      print("0"*(n-4))
      println("%03d".format(add))
    }
  }
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

   for(i<- 1 until n-1 reverse)
   {
	   var last=7%dp(i)
	   while((last.toString.map(_-'0').sum+1)%3!=0)
	  	   last+=7

	   println("1"+"0"*(i-last.toString.length)+last+"0"*(n-i-1))
	   exit
   }
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

    var i=n-2
    var last=7-dp(i)

    while((last.toString.map(_-'0').sum+1)%3!=0) last+=7

    println("1"+"0"*(i-last.toString.length)+last+"0"*(n-i-1))
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

   for(i<- 1 until n-1 reverse)
   {
	   var last=7%dp(i)
       if((last+1)%3!=0 && last<3) last+=7
       if((last+1)%3==0)
       {
    	   println("1"+"0"*(i-1)+last+"0"*(n-i-1))
    	   exit
       }
   }
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

   for(i<- 1 until n-1 reverse)
   {
	   var last=7-dp(i)

	   while((last.toString.map(_-'0').sum+1)%3!=0)
	   {
	  	       println(last)
	  	       last+=7
	   }

	   println("1"+"0"*(i-last.toString.length)+last+"0"*(n-i-1))
	   exit
   }
}


Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.

The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r".

Output n lines — on the i-th line you should print the i-th stone's number from the left.

NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val str = in.next()
  val res = Array.ofDim[Int](str.length)
  str.foldLeft((0, str.length - 1, 1)) {
    case ((left, right, number), 'l') => res(right) = number
      (left, right - 1, number + 1)
    case ((left, right, number), 'r') => res(left) = number
      (left + 1, right, number + 1)
  }
  println(res.mkString("\n"))
}

import scala.collection.mutable.ListBuffer

object Test2 {
def main(args: Array[String]) {
    val (_,left,right) = readLine.foldLeft((1, ListBuffer[Int](), ListBuffer[Int]()))((r, c) =>{
      c match {
        case 'l' =>  r._1 +=:r._3
        case _ => r._2 +=r._1
      }
      (r._1 + 1, r._2,  r._3)
    }
    )

    println(left.mkString("\n"));
    println(right.mkString("\n"));

  }
}

object Test1 {
  def main(args: Array[String]) {
    val (_,left,right) = readLine.foldLeft((1, List[Int](), List[Int]()))((r, c) =>
      c match {
        case 'l' => (r._1 + 1, r._2, r._1 :: r._3)
        case _ => (r._1 + 1, r._1 :: r._2, r._3)
      })

    println(left.reverse.mkString("\n"));
    println(right.mkString("\n"));

  }

}

object Test3 {

   def main(args: Array[String]) {
    val s = readLine;
    val (_,_,_,result) = s.foldLeft(1,0,s.length-1,new Array[Int](s.length))((r, c) =>c match {
        case 'l' => r._4(r._3) = r._1; (r._1+1,r._2,r._3-1,r._4)
        case _ => r._4(r._2) = r._1; (r._1+1,r._2+1,r._3,r._4)
      })
    println(result.mkString("\n"));

  }

}

object test {
  def main(args: Array[String]): Unit = {
      val s=readLine
      val a=new Array[Int](s.length())
      var i=0
      var j=s.length-1
      var k=0
      while(k<s.length)
      {
        if(s(k)=='l')
        {
          a(j)=k+1
          j-=1
        }
        else
        {
          a(i)=k+1
          i+=1
        }
        k+=1
      }
      println(a.mkString("\n"))
  }

}

object test {
  def main(args: Array[String]): Unit = {
val beforeRead = System.currentTimeMillis
      val s = readLine
      val ss = s.zipWithIndex.partition(_._1 != 'l')
      val a = ss._1.map(_._2 + 1).mkString("\n") + "\n" +
              ss._2.reverseMap(_._2 + 1).mkString("\n")
      println(a)
  }
}

object test {
  def main(args: Array[String]): Unit = {
      val s=readLine
      val a=new Array[Int](s.length())
      var i=0
      var j=s.length-1

      for(k <- 0 to s.length-1)
        if(s(k)=='l')
        {
          a(j)=k+1
          j-=1
        }
        else
        {
          a(i)=k+1
          i+=1
        }
      println(a.mkString("\n"))
  }
}

import scala.annotation.tailrec
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.io.PrintWriter
object Main {

  def main(args: Array[String]): Unit = {
    @tailrec
    def rec(ind:Int,seq:List[Char],left:List[Int],right:List[Int]):List[Int]=seq match{
      case List() => return left.reverse++right
      case _ if(seq.head=='l') => return rec(ind+1,seq.tail,left,ind+:right)
      case _ => return rec(ind+1,seq.tail,ind+:left,right)
    }
    val br = new BufferedReader(new InputStreamReader(System.in))
    val pw = new PrintWriter(new OutputStreamWriter(System.out))
    rec(1,br.readLine().toList,List(),List()).map(pw.println(_))
    pw.flush()
  }

}

import scala.annotation.tailrec
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
object Main {

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val pw = new PrintWriter(new OutputStreamWriter(System.out))
    val inp = br.readLine()
    var res = new Array[Int](inp.length())
    @tailrec
    def rec(ind:Int,seq:List[Char],left:Int,right:Int):Unit=seq match{
      case List() => return
      case _ => {
        res(if(seq.head=='l') right else left) = ind
        if(seq.head=='l')rec(ind+1,seq.tail,left,right-1) else rec(ind+1,seq.tail,left+1,right)
      }
    }
    rec(1,inp.toList,0,inp.length()-1)
    res.map(pw.println(_))
    pw.flush()
  }

}

import scala.annotation.tailrec
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
object Main {

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val pw = new PrintWriter(System.out)
    val inp = br.readLine()
    var res = new Array[Int](inp.length())
    @tailrec
    def rec(ind:Int,seq:List[Char],left:Int,right:Int):Unit={
      if(!seq.isEmpty)seq.head match{
        case 'l' => {res(right) = ind;rec(ind+1,seq.tail,left,right-1)}
        case 'r' => {res(left)  = ind;rec(ind+1,seq.tail,left+1,right)}
      }
    }
    rec(1,inp.toList,0,inp.length()-1)
    res.map(pw.println(_))
    pw.flush()
  }

}

import scala.collection.mutable.LinkedList
object Main265C {
  def main(args: Array[String]) {
    val cmds = readLine
    val array1 = Array.ofDim[Int](cmds length)
    val array2 = Array.ofDim[Int](cmds length)
    var pos1, pos2 = 0
    var nextNum = 1
    for (c <- cmds) {
      if (c == 'l') {
        array1(pos1) = nextNum
        pos1 += 1
      }
      else {
        array2(pos2) = nextNum
        pos2 += 1
      }
      nextNum += 1
    }
    val sb = new StringBuilder()
    for (i <- 0 to (pos2-1))
      sb.append(array2(i)).append("\n")
    for (i <- (pos1-1) to 0 by -1)
      sb.append(array1(i)).append("\n")
    print(sb)
  }
}

object C265 {

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

  def main(args: Array[String]): Unit = {
    val in = read
    val a = cu.ArrayBuffer.empty[Int]
    val b = cu.ArrayBuffer.empty[Int]
    for(i <- 0 until in.length)
      if(in(i) == 'l') a.append(i+1)
      else b.append(i+1)
    println(b.mkString("\n"))
    println(a.reverse.mkString("\n"))
  }

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

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object CF265C {
  def main(args: Array[String]) {
    val s = readLine()
    print((1 to s.length)
      .sortWith((i, j) => (i < j && s(i - 1) == 'r') | (i > j && s(j - 1) == 'l'))
      .mkString("\n"))
  }
}

object CF265C {
  def main(args: Array[String]) {
    val s = readLine()
    print((0 until s.length)
      .sortWith((i, j) => (i < j && s(i) == 'r') | (i > j && s(j) == 'l'))
      .map(_ + 1)
      .mkString("\n"))
  }
}

object Main extends App {
  import scala.io._
  val input = Source.stdin
  val s = input.getLines().next
  val n = s.length
  println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).toList.mkString("", "\n", ""))
  println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).toList.mkString("", "\n", ""))
}

object Main extends App {
  import scala.io._
  val input = Source.stdin
  val s = input.getLines().next
  val n = s.length
  println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).mkString("", "\n", ""))
  println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).mkString("", "\n", ""))
}

object Main extends App {
  import scala.io._
  val input = Source.stdin
  val s = input.getLines().next
  val n = s.length
  println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).mkString("\n"))
  println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).mkString("\n"))
}

import scala.collection.mutable.LinkedList
object Main265C {
  def main(args: Array[String]) {
    val cmds = readLine
    val list = LinkedList(-1, -1)
    var beginning = list
    var ending = list.next
    var nextNum = 1
    for (c <- cmds) {
      beginning.next = new LinkedList(nextNum, ending)
      if (c == 'l')
        ending = beginning.next
      else
        beginning = beginning.next
      nextNum += 1
    }
    var next = list.next
    val sb = new StringBuilder()
    while (next.elem != -1) {
      sb.append(next.elem).append("\n")
      next = next.next
    }
    print(sb)
  }
}


You are given two integers $$$a$$$ and $$$b$$$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $$$1$$$; during the second operation you choose one of these numbers and increase it by $$$2$$$, and so on. You choose the number of these operations yourself.For example, if $$$a = 1$$$ and $$$b = 3$$$, you can perform the following sequence of three operations:   add $$$1$$$ to $$$a$$$, then $$$a = 2$$$ and $$$b = 3$$$;  add $$$2$$$ to $$$b$$$, then $$$a = 2$$$ and $$$b = 5$$$;  add $$$3$$$ to $$$a$$$, then $$$a = 5$$$ and $$$b = 5$$$. Calculate the minimum number of operations required to make $$$a$$$ and $$$b$$$ equal.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print one integer — the minimum numbers of operations required to make $$$a$$$ and $$$b$$$ equal.

NoteFirst test case considered in the statement.In the second test case integers $$$a$$$ and $$$b$$$ are already equal, so you don't need to perform any operations.In the third test case you have to apply the first, the second, the third and the fourth operation to $$$b$$$ ($$$b$$$ turns into $$$20 + 1 + 2 + 3 + 4 = 30$$$).

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

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

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  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[Int]]): 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 = {
    if (oj){ System.err.println(s) }
  }
  def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

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

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

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

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

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

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

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

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

  def solve2(): Int = {
    val A, B = ni()
    val D = abs(A - B)
    var i = 0
    while(true) {
      val s = i.toLong * (i + 1) / 2
      if (s >= D && s % 2 == D % 2) {
        return i
      }
      i += 1
    }

    ???
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      out.println(solve2())
    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val a, b = io.read[Int]
    val d = (a - b).abs
    val ans = Iterator.from(0).find({n =>
      val k = n*(n+1) - 2*d
      k >= 0 && k%4 == 0
    }).get
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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
      }
    }
  }
}


Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.

Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.

5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503

5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503

NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val res = (1 to n).map { _ =>
    val Array(name, region, score) = in.next().split(' ')
    (name, region.toInt, score.toInt)
  }.groupBy(_._2).mapValues(_.sortBy(-_._3)).mapValues{
    case(participans) if participans.length == 2 => participans.map(_._1).mkString(" ")
    case(participans) if participans(1)._3 == participans(2)._3 => "?"
    case(participans) => participans.take(2).map(_._1).mkString(" ")
  }
  println((1 to m).map(res).mkString("\n"))
}

import collection.mutable._

object Qualifying {

  class Person (
    val name : String,
    val score : Int) extends Ordered[Person] {
    def compare(that : Person) = this.score compare that.score
    override def toString() = ("name: " + name + " score : " + score)
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)
    var region = new Array[PriorityQueue[Person]](m+1)
    for (i<-1 to m) region(i) = new PriorityQueue[Person]()
    for (i<-0 until n) {
      val r = io.StdIn.readLine.split(" ")
      val p = new Person(r(0), r(2).toInt)
      region(r(1).toInt).enqueue(p)
    }
    for (i<-1 to m) {
      //print(region(i))
      if (region(i).size == 2) println(region(i).dequeue.name + " " + region(i).dequeue.name)
      else {
        val top = region(i).dequeue
        val sec = region(i).dequeue
        if (top.score == sec.score) {
          if (sec.score == region(i).head.score) println("?")
          else println(top.name + " " + sec.name)
        } else { // 1st is unique, checking for 2nd
          if (sec.score == region(i).head.score) println("?")
          else println(top.name + " " + sec.name)
        }
      }
    }
  }
}

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

object _659B extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, m = io[Int]
    val scores = Array.fill(m)(mutable.Map.empty[String, Int])

    repeat(n) {
      val (name, region, score) = io[(String, Int, Int)]
      scores(region - 1)(name) = score
    }

    io.separator = newLine

    scores foreach {score =>
      val top = score.toIndexedSeq.sortBy(_._2)(desc)
      if (top.length <= 2 || top(1)._2 != top(2)._2) {
        io += (top(0)._1 -> top(1)._1)
      } else {
        io += '?'
      }
    }

    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 partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sum[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
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val newLine: String = "\n"
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

import collection.mutable._

object Qualifying {

  class Person (
    val name : String,
    val score : Int) extends Ordered[Person] {
    def compare(that : Person) = this.score compare that.score
    override def toString() = ("name: " + name + " score : " + score)
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)
    var region = new Array[PriorityQueue[Person]](m+1)
    for (i<-1 to m) region(i) = new PriorityQueue[Person]()
    for (i<-0 until n) {
      val r = io.StdIn.readLine.split(" ")
      val p = new Person(r(0), r(2).toInt)
      region(r(1).toInt).enqueue(p)
    }
    for (i<-1 to m) {
      //print(region(i))
      if (region(i).size == 2) println(region(i).dequeue.name + " " + region(i).dequeue.name)
      else {
        val top = region(i).dequeue
        var sec = region(i).dequeue
        while (!region(i).isEmpty && top.score == sec.score) {
          sec = region(i).dequeue
        }
        if (sec.score == top.score) { // all are the same
          println("?")
        } else if (!region(i).isEmpty && region(i).head.score == sec.score) {
          // tiebreak 2nd
          //println(region(i).head, sec)
          println("?")
        } else println(top.name + " " + sec.name)
      }
    }
  }
}


You are given a permutation of length $$$n$$$. Recall that the permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You can perform at most $$$n-1$$$ operations with the given permutation (it is possible that you don't perform any operations at all). The $$$i$$$-th operation allows you to swap elements of the given permutation on positions $$$i$$$ and $$$i+1$$$. Each operation can be performed at most once. The operations can be performed in arbitrary order.Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.You can see the definition of the lexicographical order in the notes section.You have to answer $$$q$$$ independent test cases.For example, let's consider the permutation $$$[5, 4, 1, 3, 2]$$$. The minimum possible permutation we can obtain is $$$[1, 5, 2, 4, 3]$$$ and we can do it in the following way:  perform the second operation (swap the second and the third elements) and obtain the permutation $$$[5, 1, 4, 3, 2]$$$;  perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $$$[5, 1, 4, 2, 3]$$$;  perform the third operation (swap the third and the fourth elements) and obtain the permutation $$$[5, 1, 2, 4, 3]$$$.  perform the first operation (swap the first and the second elements) and obtain the permutation $$$[1, 5, 2, 4, 3]$$$; Another example is $$$[1, 2, 4, 3]$$$. The minimum possible permutation we can obtain is $$$[1, 2, 3, 4]$$$ by performing the third operation (swap the third and the fourth elements).

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases. Then $$$q$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation.

For each test case, print the answer on it — the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.

NoteRecall that the permutation $$$p$$$ of length $$$n$$$ is lexicographically less than the permutation $$$q$$$ of length $$$n$$$ if there is such index $$$i \le n$$$ that for all $$$j$$$ from $$$1$$$ to $$$i - 1$$$ the condition $$$p_j = q_j$$$ is satisfied, and $$$p_i < q_i$$$. For example:  $$$p = [1, 3, 5, 2, 4]$$$ is less than $$$q = [1, 3, 5, 4, 2]$$$ (such $$$i=4$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$),  $$$p = [1, 2]$$$ is less than $$$q = [2, 1]$$$ (such $$$i=1$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$).

//package codeforces.contest1256

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

      val ls = io.StdIn.readLine().split(" ").map(_.toInt).toList

      def loop(given: List[Int], acc: List[Int] = Nil): List[Int] = {
        if (given.isEmpty) acc
        else {
          val min = given.min

          val (left, right) = given.span(_ != min)

          if (left.isEmpty)
            loop(given.tail, acc :+ given.head)
          else
            loop(left.last +: right.tail, acc ++ (right.head +: left.dropRight(1)))
        }
      }

      println {
        loop(ls).mkString(" ")
      }

    }

  }

}

object Main {
  def main(args: Array[String]): Unit = {
    val q = readInt
    (0 until q).foreach((x) => f1)
  }

  def f1: Unit = {
    val n = readInt
    var a = readLine.split(" ").map(_.toInt).toList
    println(f2(a).mkString(" "))
  }

  def f2(a: List[Int]): List[Int] = a match {
    case Nil => Nil
    case hd :: tl  => {
      val (_, _, i) = tl.foldLeft((hd, 1, 0)){
        case ((mv, i, mi), h) => if (h < mv) (h, i + 1, i) else (mv, i + 1, mi)
      }
      val (at, bt) = a splitAt i
      (at, bt) match {
        case (_, Nil) => throw new Exception("Not occur")
        case (Nil, x :: y) => x :: f2(y)
        case (l, x :: y) => (x :: l.init) ++ f2(l.last :: y)
      }
    }
  }
}

object B1256 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      val n = readInt
      val arr = readInts(n)
      val vis = Array.fill(n)(false)
      for (i <- 1 to n) {
        var idx = arr.indexWhere(_ == i)
        while (idx > 0 && arr(idx) < arr(idx - 1) && !vis(idx - 1)) {
          vis(idx - 1) = true
          val tmp = arr(idx - 1)
          arr(idx - 1) = arr(idx)
          arr(idx) = tmp

          idx -= 1
        }
      }
      out.println(arr.mkString(" "))
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object SmallestPermutation {

  def main(args: Array[String]): Unit = {
    import InOut._
    val inputSequences = nextInt
    for {_ <- 0 until inputSequences} {
      val operations = (0 until nextInt).dropRight(1)
      val initialPermutation = nextLine.trim.split(" ").map(_.toInt).toSeq
      val finalPermutation = findSmallestPermutation(initialPermutation, operations)
      out.println(finalPermutation.mkString(" "))
    }
    out.flush()
  }

  @scala.annotation.tailrec
  def findSmallestPermutation(permutation: Seq[Int], possibleOperations: Seq[Int]): Seq[Int] = {
    val operation = nextOperation(permutation, possibleOperations)
    if (operation == -1) permutation else findSmallestPermutation(swapOperation(operation)(permutation), possibleOperations.filter(_ != operation))
  }

  private def nextOperation(permutation: Seq[Int], possibleOperations: Seq[Int]): Int = {
    val relevantOperation = possibleOperations.filter(op => permutation(op) > permutation(op + 1))
    if (relevantOperation.isEmpty) {
      -1
    } else {
      relevantOperation.reduce {
        (op1, op2) => if (permutation(op1 + 1) < permutation(op2 + 1)) op1 else op2
      }
    }
  }

  private def swapOperation[T](index: Int)(collection: Seq[T]): Seq[T] =
    collection.updated(index, collection(index + 1)).updated(index + 1, collection(index))

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

    def nextInt: Int = Integer.parseInt(nextToken)

    def nextLine: String = in.readLine

    private val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    private[this] var tokenizer: java.util.StringTokenizer = _

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

}

import java.util.Scanner

import scala.language.postfixOps

object TaskB extends App {
  val sc = new Scanner(System.in)
  val q = sc.nextInt

  val out = 1 to q map { _ =>
    val n = sc.nextInt
    val arr = (1 to n map (_ => sc.nextInt()) toArray)
    minimize(arr, 0, n)
    arr.mkString(" ")
  } mkString "\n"

  println(out)

  def minimize(arr: Array[Int], l: Int, r: Int): Unit = {
    if (l < r - 1) {
      val minInd = arr.zipWithIndex.slice(l, r).minBy(_._1)._2
      if (minInd == l) {
        minimize(arr, l + 1, r)
      } else {
        move(arr, minInd, l)
        minimize(arr, minInd, r)
      }
    }
  }

  def move(arr: Array[Int], from: Int, to: Int) = {
    val temp = arr(from)
    from until to by -1 foreach (i => arr(i) = arr(i - 1))
    arr(to) = temp
  }
}

object B1256 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      val n = readInt
      val arr = readInts(n)
      val vis = Array.fill(n)(false)
      for (i <- 1 to n) {
        var idx = arr.indexWhere(_ == i)
        while (i != idx + 1 && !vis(idx - 1) && vis.count(!_) > 1) {
          vis(idx - 1) = true
          val tmp = arr(idx - 1)
          arr(idx - 1) = arr(idx)
          arr(idx) = tmp

          idx -= 1
        }
      }
      out.println(arr.mkString(" "))
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B1256 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      val n = readInt
      val arr = readInts(n)
      val vis = Array.fill(n)(false)
      for (i <- 1 to n) {
        var idx = arr.indexWhere(_ == i)
        while (i != idx + 1 && !vis(idx - 1)) {
          vis(idx - 1) = true
          val tmp = arr(idx - 1)
          arr(idx - 1) = arr(idx)
          arr(idx) = tmp

          idx -= 1
        }
      }
      out.println(arr.mkString(" "))
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

  @scala.annotation.tailrec
  def smallestPermutation(permutation: Seq[Int], possibleOperations: Seq[Int]): Seq[Int] = {
    val operation = nextOperation(permutation, possibleOperations)
    if (operation == -1) permutation else smallestPermutation(swapOperation(operation)(permutation), possibleOperations.filter(_ != operation))
  }

  private def nextOperation(permutation: Seq[Int], possibleOperations: Seq[Int]): Int = {
    val relevantOperation = possibleOperations.filter(op => permutation(op) > permutation(op + 1))
    if (relevantOperation.isEmpty) {
      -1
    } else {
      possibleOperations.reduce {
        (acc, value) => if (permutation(acc + 1) < permutation(value + 1)) acc else value
      }
    }
  }

  private def swapOperation[T](index: Int)(collection: Seq[T]): Seq[T] =
    collection.updated(index, collection(index + 1)).updated(index + 1, collection(index))

  val inputSequences = nextInt
  for {_ <- 0 until inputSequences} {
    val operations = (0 until nextInt).dropRight(1)
    val initialPermutation = nextLine.trim.split(" ").map(_.toInt).toSeq
    val finalPermutation = smallestPermutation(initialPermutation, operations)
    out.println(finalPermutation.mkString(" "))
  }
  out.flush()

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

    def nextInt: Int = Integer.parseInt(nextToken)

    def nextLine: String = in.readLine

    private val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    private[this] var tokenizer: java.util.StringTokenizer = _

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

}


Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.

The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one.

If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win.

NoteIn the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white.In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black.

object P049D extends App {
  val n = readInt
  val a = readLine.zipWithIndex
  val c1e = a.count(x => (x._1 == '1' && x._2 % 2 == 0))
  val c1o = a.count(x => (x._1 == '1' && x._2 % 2 == 1))
  val c0e = a.count(x => (x._1 == '0' && x._2 % 2 == 0))
  val c0o = a.count(x => (x._1 == '0' && x._2 % 2 == 1))
  println(math.min(c1e + c0o, c1o + c0e))
}