In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n.

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once.

In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.

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

object _489A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  val buffer = new ArrayBuffer[(Int, Int)]

  def doit(i: Int): Unit = {
    if (i < n) {
      val min = (i until n).minBy(i => a(i))
      if (i != min) {
        buffer.append((i, min))
        val cb = a(i)
        a(i) = a(min)
        a(min) = cb
      }
      doit(i + 1)
    }
  }

  doit(0)

  val ans = buffer.result
  println(ans.length)
  ans.foreach(pair => println(pair._1 + " " + pair._2))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data = in.next().split(" ").map(_.toInt)
  println(data.length - 1)
  println((0 until n - 1).map { i =>
    val index = data.indexOf(data.min) + i
    data(index - i) = data(0)
    data = data.tail
    s"$i $index"
  }.mkString("\n"))
}

object SB_1 {
  def main(args:Array[String]):Unit={
    val n:Int=readInt()
    val arr:Array[Int]=new Array[Int](n)

    val m=readLine()
    val line:Array[String]=m.split(" ")
    for(i<-0 until arr.length){
      arr(i)=line(i).toInt
    }

    var re:List[Array[Int]]=List()

    for(i<-0 until arr.length-1){
      var index:Int=i+1
      var sub:Int=arr(i)-arr(i+1)
      var flag:Boolean=false
      for(j<-i+1 until arr.length) {
        if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {
          sub = arr(i) - arr(j)
          index = j
          flag=true
        }
      }

      if(flag==true){
        val temp: Int = arr(i)
        arr(i) = arr(index)
        arr(index) = temp
        re = re ++ List(Array(i, index))
      }
    }
    println(re.length)
    if(re.length>0)
      for(l<-re)
        println(l(0)+" "+l(1))
  }

}

object A489 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val res = cu.ArrayBuffer.empty[(Int, Int)]
    for(i <- 0 until n){
      val sl = in.slice(i, n)
      val min = sl.min
      val idx = sl.indexOf(min)
      if(idx != 0) {
        res.append((i, i+idx))
        val temp = in(i+idx)
        in(i+idx) = in(i)
        in(i) = temp
      }
    }
    println(res.length)
    println(res.map{case (x, y) => s"$x $y"}.mkString("\n"))
  }

  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 scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object SwapSort {

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

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

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

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

   def findSwaps(xs: IndexedSeq[Int]) : List[(Int,Int)] = {
     def go(xs: IndexedSeq[Int], acc: List[(Int,Int)]) : List[(Int,Int)] = {
       if (xs.size == 1) acc.reverse
       else {
         val maxIndex = xs.indexOf(xs.max)
         if (maxIndex == xs.size - 1) go(xs.init,acc)
         else {
         val (first,second) = xs.splitAt(maxIndex)
         go ( (first ++ (xs.last +: second.tail)).init,
             (maxIndex, xs.size - 1) :: acc)
         }
       }

     }
     go(xs,List())
   }

   def main(args: Array[String]) : Unit = {
     val n = readInt
     val xs = readInts
     val swaps = findSwaps(xs)
     println(swaps.length)
     swaps.foreach{
       case (i,j) => println(s"$i $j")
     }
   }

}

object A {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    if (n == 0) {
      println(0)
    } else {
      val a = readLine().split(" ").toList.map(_.toInt)
      val steps = find(a, 0, List()).reverse
      println(steps.size)
      steps.foreach(x => println(x._1 + " " + x._2))
    }
  }

  def find(a: List[Int], pos: Int, steps: List[(Int, Int)]): List[(Int, Int)] = a match {
    case Nil => steps
    case x :: xs => {
      val min = a.min
      if (x == min) find(xs, pos + 1, steps)
      else {
        val p = xs.indexOf(min)
        find(xs.updated(p, x), pos + 1, (pos, pos + p + 1) :: steps)
      }
    }
  }
}

object A {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    if (n == 0) {
      println(0)
    } else {
      val a = readLine().split(" ").toList.map(_.toInt)
      val steps = find(a, 0, List()).reverse
      println(steps.size)
      steps.foreach(x => println(x._1 + " " + x._2))
    }
  }

  def find(a: List[Int], pos: Int, steps: List[(Int, Int)]): List[(Int, Int)] = a match {
    case Nil => steps
    case x :: xs => {
      val min = a.min
      if (x == min) find(xs, pos + 1, steps)
      else {
        val p = xs.indexOf(min)
        val split0 = xs.splitAt(p)
        val split1 = xs.splitAt(p + 1)
        find(List(split0._1, List(x), split1._2).flatten, pos + 1, (pos, pos + p + 1) :: steps)
      }
    }
  }
}

object SB_1 {
  def main(args:Array[String]):Unit={
    val n:Int=readInt()
    val arr:Array[Int]=new Array[Int](n)

    val m=readLine()
    val line:Array[String]=m.split(" ")
    for(i<-0 until arr.length){
      arr(i)=line(i).toInt
    }

//    var re:List[Array[Int]]=List()
//
//    for(i<-0 until arr.length-1){
//      var index:Int=i+1
//      var sub:Int=arr(i)-arr(i+1)
//      for(j<-i+1 until arr.length) {
//        if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {
//          sub = arr(i) - arr(j)
//          index = j
//
//          val temp: Int = arr(i)
//          arr(i) = arr(j)
//          arr(j) = temp
//          re = re ++ List(Array(i, j))
//        }
//      }
//    }

    var re:List[Array[Int]]=List()

    for(i<-0 until arr.length-1){
      for (j<-0 until arr.length - 1 - i)
        if (arr(j)>arr(i)) {
                    val temp: Int = arr(i)
                    arr(i) = arr(j)
                    arr(j) = temp
                    re = re ++ List(Array(i, j))
                  }
    }

    println(re.length)
    if(re.length>0)
      for(l<-re)
        println(l(0)+" "+l(1))
  }

}

object SB_1 {
  def main(args:Array[String]):Unit={
    val n:Int=readInt()
    val arr:Array[Int]=new Array[Int](n)

    val m=readLine()
    val line:Array[String]=m.split(" ")
    for(i<-0 until arr.length){
      arr(i)=line(i).toInt
    }

    var re:List[Array[Int]]=List()

    for(i<-0 until arr.length-1){
      var index:Int=i+1
      var sub:Int=arr(i)-arr(i+1)
      for(j<-i+1 until arr.length) {
        if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {
          sub = arr(i) - arr(j)
          index = j

          val temp: Int = arr(i)
          arr(i) = arr(j)
          arr(j) = temp
          re = re ++ List(Array(i, j))
        }
      }
    }

    println(re.length)
    if(re.length>0)
      for(l<-re)
        println(l(0)+" "+l(1))
  }

}


The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,  The chosen c prisoners has to form a contiguous segment of prisoners.  Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the c prisoners.

The first line of input will contain three space separated integers n (1 ≤ n ≤ 2·105), t (0 ≤ t ≤ 109) and c (1 ≤ c ≤ n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109.

Print a single integer — the number of ways you can choose the c prisoners.

import java.util
import java.util.StringTokenizer

object _427B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val t = next.toInt
  val c = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val queue = new util.ArrayDeque[Int]
  var ans = 0

  {
    var i = 0
    while(i < c) {
      while(!queue.isEmpty && a(queue.getLast) <= a(i)) queue.pollLast()
      queue.addLast(i)
      i += 1
    }
    if (a(queue.getFirst) <= t) ans += 1

    while(i < n) {
      while(!queue.isEmpty && a(queue.getLast) <= a(i)) queue.pollLast()
      queue.addLast(i)
      if (queue.getLast - queue.getFirst + 1 > c) queue.pollFirst()
      if (a(queue.getFirst) <= t) ans += 1

      i += 1
    }
  }
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, t, c) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val r = data.foldLeft(0, 0) {
    case ((soFar, l), el) if el > t => (soFar + (if (l >= c) l - c + 1 else 0), 0)
    case ((soFar, l), el) => (soFar, l + 1)
  }
  println(r._1 + (if (r._2 >= c) r._2 - c + 1 else 0))
}

object B427 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, t, c) = readInts(3)
    val in = readInts(n)
    var res = 0
    var curr = 0
    var i = 0
    while(i < n) {
      if(in(i) > t) curr = 0
      else {
        curr += 1
        if(curr >= c)
          res += 1
      }
      i += 1
    }
    println(res)
  }

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

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

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

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

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

}

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

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

  // N prisoners
  // C of prisoners to be transfered to another city
  // the severity of the crime
  // contiguous segment
  // crime level should not be greater then T

  def solve(): Int = {
    val N, T, C = sc.nextInt

    @tailrec
    def loop(acc: Int, p: Int, n: Int): Int = {
      val w = (p - C + 1) max 0
      if (n == N) acc + w
      else if (sc.nextInt > T) loop(acc + w, 0, n + 1)
      else loop(acc, p + 1, n + 1)
    }

    loop(0, 0, 0)
  }

  out.println(solve)
  out.close
}

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

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

  def solve(): Long = {
    val N, T, C = sc.nextInt

    @tailrec
    def loop(acc: Long, i: Int, j: Int): Long = {

      @inline
      def ways(k: Int): Int = 0 max (k - C + 1)

      if (j == N) acc + ways(i)
      else if (sc.nextInt <= T) loop(acc, i + 1, j + 1)
      else loop(acc + ways(i), 0, j + 1)
    }

    loop(0, 0, 0)
  }

  out.println(solve)
  out.close
}

import scala.io.StdIn._

object _427_B extends App {
  val input = readLine().split(" ").map(_.toInt)
  val n = input(0)
  val t = input(1)
  val c = input(2)

  val prisoners = readLine().split(" ").map(_.toInt)

  var answer = 0
  var counter = 0
  for (i <- 0 until n) {
    if (prisoners(i) <= t) counter += 1
    else counter = 0

    if (counter == c) {
      answer += 1
      counter -= 1
    }
  }

  println(answer)
}

object Transfer extends App {
	val Array(n, t, c) = readLine.split(' ').map(_.toInt)
	val ok = readLine.split(' ').map(_.toInt).map(_ <= t)
	var (ans, i, j) = (0, 0, 0)
	while (i < n) {
		if (ok(i)) {
			j = i
			while (j < n && ok(j)) j += 1
			if (j - i >= c) ans += j - i - c + 1
			i = j
		} else i += 1
	}
	print(ans)
}

object B extends App {
  val sc = new java.util.Scanner(System.in)
  val n, t, c = sc.nextInt()
  val al = Array.fill(n)(sc.nextInt())
  def func(p:Int, ct:Int):List[Int] = {
    if (p == al.length) List[Int]()
    else al(p) match {
        case x if x >  t => 0 :: func(p+1, 0)
        case _ => ct+1 :: func(p+1, ct+1)
    }
  }
  println(func(0, 0).count(_ >= c))
}

import java.io.FileInputStream
import java.util.Scanner
import scala.annotation.tailrec

object Main extends App {

  val sc = new Scanner(System.in)
//  val sc = new Scanner( new FileInputStream("src/input.txt") )

  val n,t,c = sc.nextInt
  val list = List.fill(n)(sc.nextInt)

  @tailrec
  def work(l: List[Int], res: List[List[Int]]): List[List[Int]] = {
    l match {
      case Nil =>
        res
      case xs =>
        val r = xs.span(_ <= t)
        if( r._1.size == 0 )
          work( r._2.dropWhile(_ > t), res )
        else
          work(r._2, r._1 :: res)
    }
  }

  val res = work(list, List.empty[List[Int]])
//  println(res)
  val ans = res.map(l => l.size - c + 1).filter(_>0).sum
  println(ans)
}


Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.

The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).  Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the numbers of the cities connected by the i-th road. It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.

Print a single integer — the minimum number of separated cities after the reform.

NoteIn the first sample the following road orientation is allowed: , , .The second sample: , , , , .The third sample: , , , , .

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

object _659E extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, m = io[Int]
    val edgeCount = map[Int] to 0

    val ds = new UnionFind[Int]
    (1 to n) foreach ds.+=

    repeat(m) {
      val u, v = io[Int]
      ds.union(u, v)
      edgeCount(u) += 1
    }

    val components = (1 to n).groupBy(ds)

    val ans = components.values count {comp =>
      val subEdges = comp.sumWith(edgeCount)
      comp.size == subEdges + 1
    }

    io += ans
  }

  class UnionFind[A] extends (A => Option[A]) {
    private[this] val parent = mutable.Map.empty[A, A]

    private[this] def find(x: A): A = parent(x) match {
      case `x` => x
      case y =>
        parent(x) = find(y)
        parent(x)
    }

    override def apply(x: A) = when(contains(x))(find(x))

    def union(x: A, y: A) = parent(find(x)) = find(y)

    def +=(x: A) = parent(x) = x

    def contains(x: A) = parent contains x
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to[K2, V] = to(Dict.empty[K2, V])
  }
  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 ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)

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


Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1n + 2n + 3n + 4n) mod 5for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).

The single line contains a single integer n (0 ≤ n ≤ 10105). The number doesn't contain any leading zeroes.

Print the value of the expression without leading zeros.

NoteOperation x mod y means taking remainder after division x by y.Note to the first sample:

import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 08.08.14.
 */
object B extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt

  def nextLong = in.nextLong

  def nextDouble = in.nextDouble

  def nextString = in.next

  def solve() = {
    val n = nextString
    if (n.takeRight(2).toInt % 4 == 0) {
      out.println(4)
    } else {
      out.println(0)
    }
  }

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

import java.util.StringTokenizer

object _456B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val _1 = Array(1, 1, 1, 1)
  val _2 = Array(1, 2, 4, 3)
  val _3 = Array(1, 3, 4, 2)
  val _4 = Array(1, 4, 1, 4)

  val n = next.takeRight(2).toInt % 4
  val ans = (_1(n) + _2(n) + _3(n) + _4(n)) % 5
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val n = str.takeRight(2).toInt
  if (n % 4 == 0) println("4")
  else println("0")

}

object B456 {

  import IO._

  def powMod(a: Int, pow: Int, mod: Int): Int = {
    if(pow == 0L) 1
    else {
      val half = powMod(a, pow/2, mod)
      if(pow%2 == 0) {
        (half*half)%mod
      } else {
        (a * (half*half)%mod)%mod
      }
    }
  }

  def main(args: Array[String]): Unit = {
    var x = read.takeRight(2).toInt
    println((powMod(1, x%4, 5) + powMod(2, x%4, 5) + powMod(3, x%4, 5) + powMod(4, x%4, 5))%5)
  }

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

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

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

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

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

}

object Main {
  val cin = scala.io.Source.stdin.getLines()
  def main(args: Array[String]) = {
    println(if(BigInt(cin.next().takeRight(2).toInt) % 4 > 0) 0 else 4)
  }
}

object Main {

  def main(args: Array[String]): Unit = {
    val ln = io.StdIn.readLine()
    print(if (Integer.parseInt(if (ln.length < 3) ln else ln.substring(ln.length - 2)) % 4 == 0) 4 else 0)
  }
}

import scala.io.StdIn._

object TaskB extends App {
  val l = readLine.takeRight(2).toInt
  val p = (1 :: Nil) :: (6 :: 2 :: 4 :: 8 :: Nil) :: (1 :: 3 :: 9 :: 7 :: Nil) :: (6 :: 4 :: Nil) :: Nil

  println(if (l == 0) 4 else (p.map(_.toArray).map(a => a(l % a.length)).sum) % 5)
}

import scala.io.StdIn._

object TaskB extends App {
  val l = readLine.last - '0'
  val p = (1 :: Nil) :: (6 :: 2 :: 4 :: 8 :: Nil) :: (1 :: 3 :: 9 :: 7 :: Nil) :: (6 :: 4 :: Nil) :: Nil

  println(if (l == 0) 4 else (p.map(_.toArray).map(a => a(l % a.length)).sum) % 5)
}


Polycarp has $$$26$$$ tasks. Each task is designated by a capital letter of the Latin alphabet.The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".Help Polycarp find out if his teacher might be suspicious.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of days during which Polycarp solved tasks. The second line contains a string of length $$$n$$$, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.

For each test case output:    "YES", if the teacher cannot be suspicious;  "NO", otherwise.  You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB

import sun.management.counter.Counter

import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.util.StringTokenizer
import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.Source
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========

  val lines = Source.fromInputStream(System.in).getLines()
  val writer = new PrintWriter(System.out)

  val testNumber = lines.next().toInt
  1.to(testNumber).foreach { _ =>
    val size = lines.next().toInt
    val string = lines.next()

    def findAnswer(index: Int, restrictedChars: Set[Char]): Boolean =
      if (index == size) true
      else if (restrictedChars.contains(string(index))) false
      else if (index + 1 < size && string(index + 1) != string(index)) findAnswer(index + 1, restrictedChars + string(index))
      else findAnswer(index + 1, restrictedChars)

    val answer = if (findAnswer(0, Set.empty)) "YES" else "NO"
    writer.append(StringBuilder.newBuilder.append(answer).append("\n"))
  }
  writer.close()

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def isEmpty() = multiSet.isEmpty
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import scala.collection._
import scala.collection.mutable.TreeSet
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util._

object z {
  def main(args: Array[String]): Unit = {
    val t = readInt()

    for (i <- 1 to t) {
      readLine()
      val line = readLine()

      val seen = Array.ofDim[Boolean](200)
      var lastchar = 0.toChar
      var done = false
      line.foreach(c => {
        if (c != lastchar) {
          seen(lastchar.toInt) = true;
        }

        if (seen(c) && !done) {
          println("NO")
          done = true
        }
        lastchar = c
      })

      if (!done) {
        println("YES")
      }
    }
  }
}


Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer $$$n$$$, he encrypts it in the following way: he picks three integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$l \leq a,b,c \leq r$$$, and then he computes the encrypted value $$$m = n \cdot a + b - c$$$.Unfortunately, an adversary intercepted the values $$$l$$$, $$$r$$$ and $$$m$$$. Is it possible to recover the original values of $$$a$$$, $$$b$$$ and $$$c$$$ from this information? More formally, you are asked to find any values of $$$a$$$, $$$b$$$ and $$$c$$$ such that  $$$a$$$, $$$b$$$ and $$$c$$$ are integers,  $$$l \leq a, b, c \leq r$$$,  there exists a strictly positive integer $$$n$$$, such that $$$n \cdot a + b - c = m$$$.

The first line contains the only integer $$$t$$$ ($$$1 \leq t \leq 20$$$) — the number of test cases. The following $$$t$$$ lines describe one test case each. Each test case consists of three integers $$$l$$$, $$$r$$$ and $$$m$$$ ($$$1 \leq l \leq r \leq 500\,000$$$, $$$1 \leq m \leq 10^{10}$$$). The numbers are such that the answer to the problem exists.

For each test case output three integers $$$a$$$, $$$b$$$ and $$$c$$$ such that, $$$l \leq a, b, c \leq r$$$ and there exists a strictly positive integer $$$n$$$ such that $$$n \cdot a + b - c = m$$$. It is guaranteed that there is at least one possible solution, and you can output any possible combination if there are multiple solutions.

NoteIn the first example $$$n = 3$$$ is possible, then $$$n \cdot 4 + 6 - 5 = 13 = m$$$. Other possible solutions include: $$$a = 4$$$, $$$b = 5$$$, $$$c = 4$$$ (when $$$n = 3$$$); $$$a = 5$$$, $$$b = 4$$$, $$$c = 6$$$ (when $$$n = 3$$$); $$$a = 6$$$, $$$b = 6$$$, $$$c = 5$$$ (when $$$n = 2$$$); $$$a = 6$$$, $$$b = 5$$$, $$$c = 4$$$ (when $$$n = 2$$$).In the second example the only possible case is $$$n = 1$$$: in this case $$$n \cdot 2 + 2 - 3 = 1 = m$$$. Note that, $$$n = 0$$$ is not possible, since in that case $$$n$$$ is not a strictly positive integer.

object B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      while (a <= r) {
        var n = math.max(1, m / a)
        if (a * n <= m && a * n + d >= m) {
          val c = l
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        } else {
          n = math.max(1, (m + d) / a)
          if (a * n - d <= m && a * n >= m) {
            val c = r
            val b = m - a * n + c
            out.println(s"$a $b $c")
            a = r
          }
        }
        a += 1
      }
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(l, r, m) = readLine().split(" ").map(_.toLong)

    val (p, q) = (m + l - r, m + r - l)

    (l to r).view.map(a => (q / a, a)).collectFirst {
      case (n, a) if n > 0 && n * a >= p && n * a <= q =>
        if (n * a - m < 0) (a, l + m - n * a, l)
        else (a, r + m - n * a, r)
    } match {
      case Some((a, b, c)) => println(s"$a $b $c")
      case None            => throw new Error("unexpeted exception")
    }
  }
}

object B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      while (a <= r) {
        val n = math.max(1, (m + (d + 1) / 2) / a)
        if (a * n <= m && a * n + d >= m) {
          val c = l
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        } else if (a * n - d <= m && a * n >= m) {
          val c = r
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        }
        a += 1
      }
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

object B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      while (a <= r) {
        val n = math.max(1, m / a)
        if (a * n <= m && a * n + d >= m) {
          val c = l
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        } else if (a * n - d <= m) {
          val c = r
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        }
        a += 1
      }
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

object B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      var n = math.max(1, m / a)
//            println(n)
      if (a * n <= m && a * n + d >= m) {
        val c = l
        val b = m - a * n + c
        out.println(s"$a $b $c")
      } else {
        //n += 1 //math.max(1, m / a)
        if (a * n - d <= m) {
          val c = r
          val b = m - a * n + c
          out.println(s"$a $b $c")
        }
      }
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

object B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      while (a <= r) {
        val n = math.max(1, (m + d / 2) / a)
        if (a * n <= m && a * n + d >= m) {
          val c = l
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        } else if (a * n - d <= m && a * n >= m) {
          val c = r
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        }
        a += 1
      }
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(l, r, m) = readLine().split(" ").map(_.toLong)

    val (p, q) = (m + l - r, m + r - l)

    (l to r).collectFirst {
      case a if q / a > 0 && q / a * a >= p && q / a * a <= q => (a, l, r)
    } match {
      case Some((a, b, c)) => println(s"$a $b $c")
      case None => throw new Error("unexpeted exception")
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(l, r, m) = readLine().split(" ").map(_.toLong)

    val (p, q) = (m + l - r, m + r - l)

    (l to r).view.map(a => (q / a, a)).collectFirst {
      case (n, a) if n > 0 && n * a >= p && n * a <= q =>
        (a, l + m - n * a, l)
    } match {
      case Some((a, b, c)) => println(s"$a $b $c")
      case None            => throw new Error("unexpeted exception")
    }
  }
}


Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.

The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.

Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.

8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina

NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:   alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows:  ivan  alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows:  roman  ivan  alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:  ivan  roman  alex

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next()).reverse.distinct
  println(data.mkString("\n"))
}

/**
 * Created by AngrySCV on 18.03.16.
 * https://github.com/angrySCV
 * https://vk.com/angrySCV
 */

import scala.collection.mutable

object B extends App {
  val count = Console.in.readLine().toInt

  var hranilishe = mutable.HashMap[String, Int]()
  var globalCounter = 0
  (1 to count).foreach(item => {
    hranilishe.update(Console.in.readLine(), globalCounter)
    globalCounter += 1
  })
  hranilishe.toSeq.sortWith(_._2 > _._2).map(_._1).foreach(println)

}

import scala.collection.mutable

object B extends App {
  val Array(n) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val a = mutable.HashMap.empty[String, Int]
  (1 to n).foreach { i =>
    a += scala.io.StdIn.readLine() -> i
  }

  a.toSeq.sortBy(-_._2).foreach(q => println(q._1))
}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.io.Codec

/**
  * @author itegulov
  */
object B extends App {

  import scala.collection.mutable.{Map => MMap}

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

  val n = in.nextInt()
  val map: MMap[String, Int] = MMap()

  for (i <- 1 to n) map(in.next()) = i

  val answer: List[String] = map.map(_.swap).toList.sortWith((a, b) => a._1 > b._1).map(_._2)

  for (name <- answer) {
    out.println(name)
  }

  in.close()
  out.close()

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

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

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.io.Codec

/**
  * @author itegulov
  */
object B extends App {

  import scala.collection.mutable.{Map => MMap}

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

  val n = in.nextInt()
  val map: MMap[String, Int] = MMap()

  for (i <- 1 to n) map(in.next()) = i

  map.map(_.swap).toList.sortWith((a, b) => a._1 > b._1).map(_._2).foreach(out.println)

  in.close()
  out.close()

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

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

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

/**
 * Created by AngrySCV on 18.03.16.
 * https://github.com/angrySCV
 * https://vk.com/angrySCV
 */

import scala.collection.mutable

object B extends App {
  val count = Console.in.readLine()
  val name = Console.in.readLine().split(" ")
  var hranilishe = mutable.HashMap[String, Int]()
  var globalCounter = 0
  name.foreach(item => {
    hranilishe.update(item, globalCounter)
    globalCounter += 1
  })
  hranilishe.toSeq.sortWith(_._2 > _._2).map(_._1).foreach(println)

}


Nikolay lives in a two-storied house. There are $$$n$$$ rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between $$$1$$$ and $$$n$$$). If Nikolay is currently in some room, he can move to any of the neighbouring rooms (if they exist). Rooms with numbers $$$i$$$ and $$$i+1$$$ on each floor are neighbouring, for all $$$1 \leq i \leq n - 1$$$. There may also be staircases that connect two rooms from different floors having the same numbers. If there is a staircase connecting the room $$$x$$$ on the first floor and the room $$$x$$$ on the second floor, then Nikolay can use it to move from one room to another.     The picture illustrates a house with $$$n = 4$$$. There is a staircase between the room $$$2$$$ on the first floor and the room $$$2$$$ on the second floor, and another staircase between the room $$$4$$$ on the first floor and the room $$$4$$$ on the second floor. The arrows denote possible directions in which Nikolay can move. The picture corresponds to the string "0101" in the input.  Nikolay wants to move through some rooms in his house. To do this, he firstly chooses any room where he starts. Then Nikolay moves between rooms according to the aforementioned rules. Nikolay never visits the same room twice (he won't enter a room where he has already been). Calculate the maximum number of rooms Nikolay can visit during his tour, if:  he can start in any room on any floor of his choice,  and he won't visit the same room twice.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then test cases follow. Each test case consists of two lines. The first line contains one integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of rooms on each floor. The second line contains one string consisting of $$$n$$$ characters, each character is either a '0' or a '1'. If the $$$i$$$-th character is a '1', then there is a staircase between the room $$$i$$$ on the first floor and the room $$$i$$$ on the second floor. If the $$$i$$$-th character is a '0', then there is no staircase between the room $$$i$$$ on the first floor and the room $$$i$$$ on the second floor. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.

For each test case print one integer — the maximum number of rooms Nikolay can visit during his tour, if he can start in any room on any floor, and he won't visit the same room twice.

NoteIn the first test case Nikolay may start in the first room of the first floor. Then he moves to the second room on the first floor, and then — to the third room on the first floor. Then he uses a staircase to get to the third room on the second floor. Then he goes to the fourth room on the second floor, and then — to the fifth room on the second floor. So, Nikolay visits $$$6$$$ rooms.There are no staircases in the second test case, so Nikolay can only visit all rooms on the same floor (if he starts in the leftmost or in the rightmost room).In the third test case it is possible to visit all rooms: first floor, first room $$$\rightarrow$$$ second floor, first room $$$\rightarrow$$$ second floor, second room $$$\rightarrow$$$ first floor, second room $$$\rightarrow$$$ first floor, third room $$$\rightarrow$$$ second floor, third room $$$\rightarrow$$$ second floor, fourth room $$$\rightarrow$$$ first floor, fourth room $$$\rightarrow$$$ first floor, fifth room $$$\rightarrow$$$ second floor, fifth room.In the fourth test case it is also possible to visit all rooms: second floor, third room $$$\rightarrow$$$ second floor, second room $$$\rightarrow$$$ second floor, first room $$$\rightarrow$$$ first floor, first room $$$\rightarrow$$$ first floor, second room $$$\rightarrow$$$ first floor, third room.

//package codeforces.contest1244

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

      val total = io.StdIn.readInt()
      val stairs = io.StdIn.readLine()

      val leftmost = stairs.indexOf('1')
      val rightmost = stairs.lastIndexOf('1')

      println {
        if (leftmost != -1 && rightmost != -1)
          ((rightmost + 1) * 2) max (total - rightmost) * 2 max total max ((leftmost + 1) * 2) max (total - leftmost) * 2
        else total
      }
    }
  }

}

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

  val t = nextInt

  for (_ <- 1 to t) {
    val n = nextInt
    val s = nextLine
    val l = s.indexWhere(_ == '1')
    val r = s.lastIndexWhere(_ == '1')
    val res = if (l == -1) n
    else {
      val d = math.max(r + 1, n - l)
      val a = 2 * d
      val b = n + s.count(_ == '1')
      math.max(a, b)
    }
    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
  }
}


Alice and Bob play a game. Alice has $$$n$$$ cards, the $$$i$$$-th of them has the integer $$$a_i$$$ written on it. Bob has $$$m$$$ cards, the $$$j$$$-th of them has the integer $$$b_j$$$ written on it.On the first turn of the game, the first player chooses one of his/her cards and puts it on the table (plays it). On the second turn, the second player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the first turn, and plays it. On the third turn, the first player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the second turn, and plays it, and so on — the players take turns, and each player has to choose one of his/her cards with greater integer than the card played by the other player on the last turn.If some player cannot make a turn, he/she loses.For example, if Alice has $$$4$$$ cards with numbers $$$[10, 5, 3, 8]$$$, and Bob has $$$3$$$ cards with numbers $$$[6, 11, 6]$$$, the game may go as follows:  Alice can choose any of her cards. She chooses the card with integer $$$5$$$ and plays it.  Bob can choose any of his cards with number greater than $$$5$$$. He chooses a card with integer $$$6$$$ and plays it.  Alice can choose any of her cards with number greater than $$$6$$$. She chooses the card with integer $$$10$$$ and plays it.  Bob can choose any of his cards with number greater than $$$10$$$. He chooses a card with integer $$$11$$$ and plays it.  Alice can choose any of her cards with number greater than $$$11$$$, but she has no such cards, so she loses. Both Alice and Bob play optimally (if a player is able to win the game no matter how the other player plays, the former player will definitely win the game).You have to answer two questions:  who wins if Alice is the first player?  who wins if Bob is the first player?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of four lines. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of cards Alice has. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — the numbers written on the cards that Alice has. The third line contains one integer $$$m$$$ ($$$1 \le m \le 50$$$) — the number of Bob's cards. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le 50$$$) — the numbers on Bob's cards.

For each test case, print two lines. The first line should be Alice if Alice wins when she is the first player; otherwise, the first line should be Bob. The second line should contain the name of the winner if Bob is the first player, in the same format.

NoteLet's consider the first test case of the example.Alice has one card with integer $$$6$$$, Bob has two cards with numbers $$$[6, 8]$$$.If Alice is the first player, she has to play the card with number $$$6$$$. Bob then has to play the card with number $$$8$$$. Alice has no cards left, so she loses.If Bob is the first player, then no matter which of his cards he chooses on the first turn, Alice won't be able to play her card on the second turn, so she will lose.

/*
https://codeforces.com/contest/1681/problem/A
 */
//package round_129

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

object task_A extends App {
    def solving(x: Array[Int], y: Array[Int]) = {
        val max_x = x.max
        val max_y = y.max
        if (max_x > max_y) {
            1
        }
        else if (max_x < max_y) {
            -1
        }
        else {
            0
        }
    }

    var sb = new StringBuilder()
    val t = StdIn.readLine().toInt
    for (i <- 0 until(t)) {
        val n = StdIn.readLine().toInt
        val a = StdIn.readLine().split(" ").map(_.toInt)
//        val a = Array(n)
//        for (ii <- 0 until(n)) a(ii) = StdIn.readLine().split(" ").toInt
        val m = StdIn.readLine().toInt
        val b = StdIn.readLine().split(" ").map(_.toInt)
//        val b = Array(m)
//        for (ii <- 0 until(m)) b(ii) = StdIn.readLine().toInt
        val ans = solving(a, b)
        if (ans == 1) {
//            println("Alice")
//            println("Alice")

            sb.append("Alice").append("\n").append("Alice").append("\n")
        }
        else if (ans == -1) {
//            println("Bob")
//            println("Bob")

            sb.append("Bob").append("\n").append("Bob").append("\n")
        }
        else {
//            println("Alice")
//            println("Bob")

            sb.append("Alice").append("\n").append("Bob").append("\n")

        }
    }

    print(sb)
}

/*
https://codeforces.com/contest/1681/problem/A
 */
//package round_129

import scala.io.StdIn

object task_A extends App {
    def solving(x: Array[Int], y: Array[Int]) = {
        val max_x = x.max
        val max_y = y.max
        if (max_x > max_y) {
            1
        }
        else if (max_x < max_y) {
            -1
        }
        else {
            0
        }
    }

    val t = StdIn.readLine().toInt
    for (i <- 0 until(t)) {
        val n = StdIn.readLine().toInt
        val a = StdIn.readLine().split(" ").map(_.toInt)
//        val a = Array(n)
//        for (ii <- 0 until(n)) a(ii) = StdIn.readLine().split(" ").toInt
        val m = StdIn.readLine().toInt
        val b = StdIn.readLine().split(" ").map(_.toInt)
//        val b = Array(m)
//        for (ii <- 0 until(m)) b(ii) = StdIn.readLine().toInt
        val ans = solving(a, b)
        if (ans == 1) {
            println("Alice")
            println("Alice")
        }
        else if (ans == -1) {
            println("Bob")
            println("Bob")
        }
        else {
            println("Alice")
            println("Bob")
        }

    }
}

import scala.io.StdIn

object Main extends App {
  val t = StdIn.readLine().toInt
  for (_ <- 0 until t) {
    StdIn.readLine().toInt
    val a_max:Int = StdIn.readLine().split(" ").map(_.toInt).max
    StdIn.readLine().toInt
    val b_max:Int = StdIn.readLine().split(" ").map(_.toInt).max
    println(if (a_max >= b_max) "Alice" else "Bob")
    println(if (b_max >= a_max) "Bob" else "Alice")
  }
}


Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.

Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).

NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".

object E extends App {

  val s = readLine

  var l = 0
  var r = s.length - 1
  val prefix = new StringBuilder
  var res = ""

  while (res == "") {
    if (l == r) {
      val half = prefix.result()
      res = half + s(l) + half.reverse
    } else if (l > r) {
      val half = prefix.result()
      res = half + half.reverse
    } else if (s(l) == s(r)) {
      prefix += s(l)
      l += 1
      r -= 1
    } else if (s(l) == s(r - 1)) {
      r -= 1
    } else {
      l += 1
    }
  }

  println(if (res.length < s.length / 2) "IMPOSSIBLE" else res)
}


Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n + 1 points with coordinates (1, y1), (2, y2), ..., (2n + 1, y2n + 1), with the i-th segment connecting the point (i, yi) and the point (i + 1, yi + 1). For any even i (2 ≤ i ≤ 2n) the following condition holds: yi - 1 < yi and yi > yi + 1. We shall call a vertex of a polyline with an even x coordinate a mountain peak.   The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2.  Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1, r1), (2, r2), ..., (2n + 1, r2n + 1).Given Bolek's final picture, restore the initial one.

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100). The next line contains 2n + 1 space-separated integers r1, r2, ..., r2n + 1 (0 ≤ ri ≤ 100) — the y coordinates of the polyline vertices on Bolek's picture. It is guaranteed that we can obtain the given picture after performing the described actions on some picture of mountain peaks.

Print 2n + 1 integers y1, y2, ..., y2n + 1 — the y coordinates of the vertices of the polyline on the initial picture. If there are multiple answers, output any one of them.

object Main {
  def main(args: Array[String]): Unit = {
    val  temp = readLine.split(" ")
    val n = temp(0).toInt
    var k = temp(1).toInt
    val a = readLine.split(' ') map (_.toInt)
    assert(a.length == 2 * n + 1)

    for(i <- 0 to 2 * n) {
        if(k != 0 && i % 2 == 1 && a(i)-a(i-1) > 1 && a(i) - a(i+1) > 1) {
            a(i) -=1
            k -= 1
        }
        print(a(i) + " ")
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    var rest = k
    for(i <- 1 to 2 * n by 2) {
      if (rest != 0 && a(i) - 1 > a(i - 1) && a(i) - 1 > a(i + 1)) {
        a(i) -= 1
        rest-= 1
      }
    }
    println(a.mkString(" "))
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    var rest = k
    val tr = a.map{ i =>
      if (i > 0 && rest != 0) { rest -= 1; i - 1}
      else i
    }
    println(tr.mkString(" "))
  }
}


The only difference between easy and hard versions is constraints.Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.There are $$$n$$$ voters, and two ways to convince each of them to vote for you. The first way to convince the $$$i$$$-th voter is to pay him $$$p_i$$$ coins. The second way is to make $$$m_i$$$ other voters vote for you, and the $$$i$$$-th voter will vote for free.Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $$$m_1 = 1$$$, $$$m_2 = 2$$$, $$$m_3 = 2$$$, $$$m_4 = 4$$$, $$$m_5 = 5$$$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: $$${5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}$$$.Calculate the minimum number of coins you have to spend so that everyone votes for you.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of voters. The next $$$n$$$ lines contains the description of voters. $$$i$$$-th line contains two integers $$$m_i$$$ and $$$p_i$$$ ($$$1 \le p_i \le 10^9, 0 \le m_i < n$$$). It is guaranteed that the sum of all $$$n$$$ over all test cases does not exceed $$$5000$$$.

For each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you.

NoteIn the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: $$${3} \rightarrow {1, 3} \rightarrow {1, 2, 3}$$$.In the second example you don't need to buy votes. The set of people voting for you will change as follows: $$${1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}$$$.In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: $$${2, 5} \rightarrow {1, 2, 3, 4, 5} \rightarrow {1, 2, 3, 4, 5, 6}$$$.

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._

  case class Voter(p: Int, m: Int)

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    java.util.Arrays.sort(a)
    a
  }
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      import java.util.Comparator
      val n = ni()
      val V = Array.ofDim[Voter](n)
      REP(n) { i =>
        val m, p = ni()
        V(i) = Voter(p, m)
      }
      sort(V, new Comparator[Voter] {
        override def compare(o1: Voter, o2: Voter): Int = Integer.compare(o1.m, o2.m)
      })
      val inf = 1e18.toLong
      var cur, next = Array.ofDim[Long](n)
      var s = 0
      def process(i: Int): Unit = {
        debug(s"process($i)")
        import java.util
        util.Arrays.fill(next, inf)

        val len = i - s + 1
        val p = Array.ofDim[Int](len)
        REP(len) { j =>
          p(j) = V(s + j).p
        }
        Workspace.sort(p)
        val cum = cumSum(p)
        REP(len + 1) { j =>
          var k = 0
          while(k < n) {
            if (j == len || s + j + k >= V(i).m) {
              if (k + j < n) next(k) = min(next(k), cur(k + j) + cum(j))
            }
            k += 1
          }
        }

        debug(next)

        val t = cur
        cur = next
        next = t
        s = i + 1
      }

      REP(n) { i =>
        if (i > 0 && V(i).m != V(i - 1).m) {
          process(i - 1)
        }
      }
      process(n - 1)
      out.println(cur(0))
    }
  }
}

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n = ni()
      val Ps = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())
      REP(n) { _ =>
        val m, p = ni()
        Ps(m) += p
      }
      var pref = n
      var cnt = 0
      var ans = 0L
      val q = new java.util.PriorityQueue[Int]
      REP_r(n) { i =>
        pref -= Ps(i).length
        REP(Ps(i).length) { j =>
          q.add(Ps(i)(j))
        }
        val need = i - pref
        while(cnt < need) {
          cnt += 1
          ans += q.poll()
        }
      }
      out.println(ans)
    }
  }
}


You are given $$$n$$$ points with integer coordinates on a coordinate axis $$$OX$$$. The coordinate of the $$$i$$$-th point is $$$x_i$$$. All points' coordinates are distinct and given in strictly increasing order.For each point $$$i$$$, you can do the following operation no more than once: take this point and move it by $$$1$$$ to the left or to the right (i..e., you can change its coordinate $$$x_i$$$ to $$$x_i - 1$$$ or to $$$x_i + 1$$$). In other words, for each point, you choose (separately) its new coordinate. For the $$$i$$$-th point, it can be either $$$x_i - 1$$$, $$$x_i$$$ or $$$x_i + 1$$$.Your task is to determine if you can move some points as described above in such a way that the new set of points forms a consecutive segment of integers, i. e. for some integer $$$l$$$ the coordinates of points should be equal to $$$l, l + 1, \ldots, l + n - 1$$$.Note that the resulting points should have distinct coordinates.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points in the set $$$x$$$. The second line of the test case contains $$$n$$$ integers $$$x_1 < x_2 < \ldots < x_n$$$ ($$$1 \le x_i \le 10^6$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th point. It is guaranteed that the points are given in strictly increasing order (this also means that all coordinates are distinct). It is also guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — if the set of points from the test case can be moved to form a consecutive segment of integers, print YES, otherwise print NO.

import scala.io.StdIn

object Task2 extends App {
  def getNextNum: Int = StdIn.readLine().toInt

  val inputSize = getNextNum

  for (_ <- 0 until inputSize) {
    getNextNum

    val points = StdIn.readLine().split(" ").map(_.toInt)

    var bigDistancesSum: Long = 0l
    var prevPoint = points(0)

    for (i <- points.tail) {
      bigDistancesSum += i - prevPoint - 1
      prevPoint = i
    }

    if (bigDistancesSum > 2) println("NO")
    else println("YES")
  }

}


Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handkerchief pattern should look like that:           0        0 1 0      0 1 2 1 0    0 1 2 3 2 1 0  0 1 2 3 4 3 2 1 00 1 2 3 4 5 4 3 2 1 0  0 1 2 3 4 3 2 1 0    0 1 2 3 2 1 0      0 1 2 1 0        0 1 0          0Your task is to determine the way the handkerchief will look like by the given n.

The first line contains the single integer n (2 ≤ n ≤ 9).

Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.

import java.util.StringTokenizer

object _118B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt + 1
  for (i <- 0 until n) {
    print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)
    for (j <- 0 to i) print(j + (if (j < i) " " else ""))
    for (j <- (i - 1).to(0, -1)) print(" " + j)
    println
  }
  for (i <- (n - 2).to(0, -1)) {
    print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)
    for (j <- 0 to i) print(j + (if (j < i) " " else ""))
    for (j <- (i - 1).to(0, -1)) print(" " + j)
    println
  }
}

object B118 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val res = Array.fill(n+1)(Array.fill[Char](2*n+1)(' '))
    for(i <- 0 until n+1; j <- 0 until 2*n+1) {
      if(i + j >= n && j <= n) {
        res(i)(j) = ('0' + (i+j) - n).toChar
      } else if (j > n && j <= i+n) {
        res(i)(j) = ('0' + i+n - j).toChar
      }
    }

    println(res.map(_.mkString(" ")).map(_.replaceAll("""(?m)\s+$""", "")).mkString("\n"))
    println(res.dropRight(1).reverse.map(_.mkString(" ")).map(_.replaceAll("""(?m)\s+$""", "")).mkString("\n"))
  }
}

import java.util.Scanner

object B extends App {
	val n = new Scanner(System.in).nextInt()
	for (i <- 0 until 2 * n + 1) {
		val line = new StringBuffer()
		val numberOfSpaces = (n - i).abs
		val max = (2 * n - i) min i
		for (_ <- 1 to numberOfSpaces) line.append("  ")
		for (j <- 0 to max) {
			line.append(j)
			line.append(' ')
		}
		for (j <- max - 1 to 0 by -1) {
			line.append(j)
			line.append(' ')
		}
		line.deleteCharAt(line.length() - 1)
		println(line.toString)
	}
}

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

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

  val N = sc.nextInt

  def line(i: Int): String = {
    " " * 2 * (N - i) + ((0 until i) ++ List.range(i, -1, -1)).mkString(" ")
  }

  for (i <- (0 until N) ++ List.range(N, -1, -1))
    out.println(line(i))
  out.close
}

object Main {
  def genRow(rowMax: Int, centerMax: Int) = {
    (0 until (centerMax - rowMax)).map(_ => " ") ++ rowData(rowMax)
  }

  def rowData(rowMax: Int) = {
    ((0 until rowMax) ++ (rowMax to 0 by -1)).map(_.toString)
  }

  def main(args: Array[String]) {
    val num = readInt()
    for (i <- (0 until num) ++ (num to 0 by -1)) {
      println(genRow(i, num).mkString(" "))
    }
  }
}

import scala.collection.mutable.Queue
object Main {

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val arr = (0 until 2*n+1).foldLeft(List[Array[Char]]())((l,i)=>(" "*(2*n+1-Math.abs(i-n))).toCharArray()+:l).toArray
    val que= Queue((n,n,n))
    while(!que.isEmpty){
      val (x,y,v) = que.dequeue
      if(v>=0 && arr(y)(x)==' '){
        arr(y)(x) = (""+v)(0)
        List((0,1),(1,0),(0,-1),(-1,0)).map(dir=>que.enqueue((x+dir._1,y+dir._2,v-1)))
      }
    }
    arr.map(x=>println(x.mkString(" ")))
  }

}

import java.util.StringTokenizer

object _118B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  for (i <- 0 until n) {
    print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)
    for (j <- 0 to i) print(j + " ")
    for (j <- (i - 1).to(0, -1)) print(j + (if (j > 0) " " else ""))
    println
  }
  for (i <- (n - 2).to(0, -1)) {
    print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)
    for (j <- 0 to i) print(j + " ")
    for (j <- (i - 1).to(0, -1)) print(j + (if (j > 0) " " else ""))
    println
  }
}

import java.util.StringTokenizer

object _118B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt + 1
  for (i <- 0 until n) {
    print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)
    for (j <- 0 to i) print(j + " ")
    for (j <- (i - 1).to(0, -1)) print(j + (if (j > 0) " " else ""))
    println
  }
  for (i <- (n - 2).to(0, -1)) {
    print((1 to 2 * (n - 1 - i)).map(i => ' ').mkString)
    for (j <- 0 to i) print(j + " ")
    for (j <- (i - 1).to(0, -1)) print(j + (if (j > 0) " " else ""))
    println
  }
}

import java.util.Scanner

object B extends App {
	val n = new Scanner(System.in).nextInt()
	for (i <- 0 until 2 * n + 1) {
		val line = new StringBuffer()
		val numberOfSpaces = (n - i).abs
		val max = (2 * n - i) min i
		for (_ <- 1 to numberOfSpaces) line.append(' ')
		for (j <- 0 to max) line.append(j)
		for (j <- max - 1 to 0 by -1) line.append(j)
		println(line.toString)
	}
}

import scala.collection.mutable.Queue
object Main {

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val arr = (0 until 2*n+1).foldLeft(List[Array[Char]]())((l,i)=>(" "*(2*n+1-Math.abs(i-n))).toCharArray()+:l).toArray
    val que= Queue((n,n,n))
    while(!que.isEmpty){
      val (x,y,v) = que.dequeue
      if(v>=0 && arr(y)(x)==' '){
        arr(y)(x) = (""+v)(0)
        List((0,1),(1,0),(0,-1),(-1,0)).map(dir=>que.enqueue((x+dir._1,y+dir._2,v-1)))
      }
    }
    arr.map(x=>println(x.mkString))
  }

}

import scala.collection.mutable.Queue
object Main {

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val arr = (1 to 2*n+1).foldLeft(List[Array[Char]]())((l,_)=>(" "*(2*n+1)).toCharArray()+:l).toArray
    val que= Queue((n,n,n))
    while(!que.isEmpty){
      val (x,y,v) = que.dequeue
      if(v>=0 && arr(y)(x)==' '){
        arr(y)(x) = (""+v)(0)
        List((0,1),(1,0),(0,-1),(-1,0)).map(dir=>que.enqueue((x+dir._1,y+dir._2,v-1)))
      }
    }
    arr.map(x=>println(x.mkString))
  }

}