Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself.

Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number.

NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = nal(N)
    val cum = Array.ofDim[Long](N + 1)
    REP(N) { i =>
      cum(i + 1) = cum(i) ^ A(i)
    }

//    debug(cum)

    class Counter {
      var even: Long = 0
      var odd: Long = 0

      override def toString: String = s"($even, $odd)"
    }
    val ix = mutable.Map[Long, Counter]()
    REP(N + 1) { i =>
      if (!ix.contains(cum(i))) ix(cum(i)) = new Counter
      if (i % 2 == 0) ix(cum(i)).even += 1
      else ix(cum(i)).odd += 1
    }

//    debug(ix.mkString)

    var ans = 0L
    ix.foreach { case (_, cnt) =>
      ans += cnt.even * (cnt.even - 1) / 2
      ans += cnt.odd * (cnt.odd - 1) / 2
    }

    out.println(ans)
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

object Main
{
	def min (a : Int, b : Int) : Int =
		if (a < b) return a
		else return b
	def main (args : Array[String]) =
	{
		var parni = scala.collection.mutable.Map[Int,Int]()
		var neparni = scala.collection.mutable.Map[Int,Int]()

		val n = readLine.toInt
		val arr = readLine.split(' ').map(_.toInt)

		var dp = new Array[Int](n+2)
		dp(0) = 0
		for (i <- 1 to n)
			dp(i) = dp(i-1) ^ arr(i-1)
		var rez : BigInt = 0

		parni.update(0,1)

		for (i <- 1 to n)
		{
			//println("za i = " + i)
			var a = dp(i)
			//println("a = " + a)
			var b = 0

			if (i%2 == 1 && neparni.contains(a))
				b = neparni(a)
			else if (i%2 == 0 && parni.contains(a))
				b = parni(a)

			//println("b = " + b)

			rez += b
			//println("rez = " + rez)

			if (i%2 == 0)
				parni.update(a,b+1)
			else
				neparni.update(a,b+1)
		}
		println(rez)
	}
}

object Main
{
	def min (a : Int, b : Int) : Int =
		if (a < b) return a
		else return b
	def main (args : Array[String]) =
	{
		var parni = scala.collection.mutable.Map[Int,Int]()
		var neparni = scala.collection.mutable.Map[Int,Int]()

		val n = readLine.toInt
		val arr = readLine.split(' ').map(_.toInt)

		var dp = new Array[Int](n+2)
		dp(0) = 0
		for (i <- 1 to n)
			dp(i) = dp(i-1) ^ arr(i-1)
		var rez = 0

		parni.update(0,1)

		for (i <- 1 to n)
		{
			//println("za i = " + i)
			var a = dp(i)
			//println("a = " + a)
			var b = 0

			if (i%2 == 1 && neparni.contains(a))
				b = neparni(a)
			else if (i%2 == 0 && parni.contains(a))
				b = parni(a)

			//println("b = " + b)

			rez += b
			//println("rez = " + rez)

			if (i%2 == 0)
				parni.update(a,b+1)
			else
				neparni.update(a,b+1)
		}
		println(rez)
	}
}


An array $$$b$$$ is called to be a subarray of $$$a$$$ if it forms a continuous subsequence of $$$a$$$, that is, if it is equal to $$$a_l$$$, $$$a_{l + 1}$$$, $$$\ldots$$$, $$$a_r$$$ for some $$$l, r$$$.Suppose $$$m$$$ is some known constant. For any array, having $$$m$$$ or more elements, let's define it's beauty as the sum of $$$m$$$ largest elements of that array. For example:   For array $$$x = [4, 3, 1, 5, 2]$$$ and $$$m = 3$$$, the $$$3$$$ largest elements of $$$x$$$ are $$$5$$$, $$$4$$$ and $$$3$$$, so the beauty of $$$x$$$ is $$$5 + 4 + 3 = 12$$$. For array $$$x = [10, 10, 10]$$$ and $$$m = 2$$$, the beauty of $$$x$$$ is $$$10 + 10 = 20$$$.You are given an array $$$a_1, a_2, \ldots, a_n$$$, the value of the said constant $$$m$$$ and an integer $$$k$$$. Your need to split the array $$$a$$$ into exactly $$$k$$$ subarrays such that:  Each element from $$$a$$$ belongs to exactly one subarray. Each subarray has at least $$$m$$$ elements. The sum of all beauties of $$$k$$$ subarrays is maximum possible.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m$$$, $$$2 \le k$$$, $$$m \cdot k \le n$$$) — the number of elements in $$$a$$$, the constant $$$m$$$ in the definition of beauty and the number of subarrays to split to. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).

In the first line, print the maximum possible sum of the beauties of the subarrays in the optimal partition. In the second line, print $$$k-1$$$ integers $$$p_1, p_2, \ldots, p_{k-1}$$$ ($$$1 \le p_1 < p_2 < \ldots < p_{k-1} < n$$$) representing the partition of the array, in which:  All elements with indices from $$$1$$$ to $$$p_1$$$ belong to the first subarray. All elements with indices from $$$p_1 + 1$$$ to $$$p_2$$$ belong to the second subarray. $$$\ldots$$$. All elements with indices from $$$p_{k-1} + 1$$$ to $$$n$$$ belong to the last, $$$k$$$-th subarray. If there are several optimal partitions, print any of them.

NoteIn the first example, one of the optimal partitions is $$$[5, 2, 5]$$$, $$$[2, 4]$$$, $$$[1, 1, 3, 2]$$$.  The beauty of the subarray $$$[5, 2, 5]$$$ is $$$5 + 5 = 10$$$.  The beauty of the subarray $$$[2, 4]$$$ is $$$2 + 4 = 6$$$.  The beauty of the subarray $$$[1, 1, 3, 2]$$$ is $$$3 + 2 = 5$$$. The sum of their beauties is $$$10 + 6 + 5 = 21$$$.In the second example, one optimal partition is $$$[4]$$$, $$$[1, 3]$$$, $$$[2, 2]$$$, $$$[3]$$$.

import scala.io.StdIn.readLine

object B1114ArraySplit extends App {
  val n::m::k::_ = readLine().split(" ").map(_.toInt).toList
  val as = readLine().split(" ").map(BigInt(_)).toList

  val cuts = as.zipWithIndex.sortBy(_._1).takeRight(m * k).map(_._2).sorted.zipWithIndex.filter(x => x._2 % m == 0).map(_._1).tail

  println(as.sorted.takeRight(m * k).sum)
  println(cuts.mkString(" "))
}

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

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

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N, M, K = ni()
    val A = na(N)
    val ix = Array.ofDim[Integer](N)
    REP(N) { i =>
      ix(i) = i
    }

    // Aの降順で並べる
    java.util.Arrays.sort(ix, new Comparator[Integer] {
      override def compare(o1: Integer, o2: Integer): Int = Integer.compare(A(o2), A(o1))
    })

    // ixの昇順でソート
    val B = ix.take(M * K)
    java.util.Arrays.sort(B, new Comparator[Integer] {
      override def compare(o1: Integer, o2: Integer): Int = o1.compareTo(o2)
    })

    var S = 0L
    REP(B.length) { i =>
      S += A(B(i))
    }

    out.println(S)
//    debug(B.mkString(" "))

    val ans = ArrayBuffer[Int]()
    REP(K - 1, 1) { i =>
      ans += B(i * M - 1) + 1
    }
    out.println(ans.mkString(" "))
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

import scala.io.StdIn

object YetAnotherArrayPartition {
  def main(args: Array[String]): Unit = {
    val content = StdIn.readLine()
    val line1Arg = content.split(" ")
    val nums = line1Arg(0).toInt
    val minSize = line1Arg(1).toInt
    val partitions = line1Arg(2).toInt
    val line2 = StdIn.readLine()
    val line2Arg = line2.split(" ")
    val arrayBuffer = scala.collection.mutable.ArrayBuffer[Int]()
    for (i <- 0 until nums) {
      arrayBuffer.append(line2Arg(i).toInt)
    }
    val validNum = minSize * partitions
    val sorted = arrayBuffer.sorted.reverse
    val minValid = sorted(validNum - 1)
    var idx = validNum - 1
    var minValidNumCount = 0
    while (idx >= 0 && minValid == sorted(idx)) {
      minValidNumCount += 1
      idx -= 1
    }
    val splitArray = scala.collection.mutable.ListBuffer[Int]()
    var splitIdx = 0
    var remainValidCount = minValidNumCount
    var curPartitionValidNums = 0
    var i = 0
    var break = false
    var curPartitionSum = 0L
    var totalSum = 0L
    while (i < nums && !break) {
      if (arrayBuffer(i) > minValid) {
        curPartitionValidNums += 1
        curPartitionSum += arrayBuffer(i)
        if (curPartitionValidNums == minSize) {
          totalSum += curPartitionSum
          curPartitionSum = 0
          curPartitionValidNums = 0
          splitIdx += 1
          if (splitIdx != partitions) {
            splitArray.append(i + 1)
          }
        }
      } else if (arrayBuffer(i) == minValid && remainValidCount > 0) {
        remainValidCount -= 1
        curPartitionValidNums += 1
        curPartitionSum += arrayBuffer(i)
        if (curPartitionValidNums == minSize) {
          totalSum += curPartitionSum
          curPartitionSum = 0
          curPartitionValidNums = 0
          splitIdx += 1
          if (splitIdx != partitions) {
            splitArray.append(i + 1)
          }
        }
      } else {

      }

      if (splitIdx == partitions) {
        break = true
      }
      i += 1
    }
    println(totalSum)
    println(splitArray.mkString(" "))
  }
}

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

object Codeforces114B {

  def getSubArrayPartitions(n: Int, m: Int, k: Int, a: Seq[Int]): (Long, Seq[Int]) = {
    val largerNumbers = a.sorted.reverse.take(m * k)
    val largeNumberFrequencyMap: mutable.Map[Int, Int] = toFrequencyMap(largerNumbers)
    val partition = new Array[Int](k - 1)
    var inputIndex = 0
    for (outputIndex <- partition.indices) {
      var subArrayIndex = 0
      while (subArrayIndex < m) {
        val element = a(inputIndex)
        if (largeNumberFrequencyMap.getOrElse(element, 0) > 0) {
          largeNumberFrequencyMap(element) -= 1
          subArrayIndex += 1
        }
        inputIndex += 1
      }
      partition(outputIndex) = inputIndex
    }
    (largerNumbers.map(_.toLong).sum, partition)
  }

  private def toFrequencyMap(numbers: Seq[Int]): mutable.Map[Int, Int] = {
    val frequencyMap = new mutable.HashMap[Int, Int]()
    for (number <- numbers) {
      frequencyMap(number) = frequencyMap.getOrElse(number, 0) + 1
    }
    frequencyMap
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)

    val result = getSubArrayPartitions(n, m, k, a)
    val sum = result._1
    val partition = result._2
    println(sum)
    println(partition.mkString(" "))
  }
}

import scala.io.StdIn.readLine

object B1114ArraySplit extends App {
  val n::m::k::_ = readLine().split(" ").map(_.toInt).toList
  val as = readLine().split(" ").map(_.toInt).toList

  println(as.sorted.takeRight(m * k).sum)
  println((1 until k).map(x => x * m).mkString(" "))
}

import scala.io.StdIn.readLine

object B1114ArraySplit extends App {
  val n::m::k::_ = readLine().split(" ").map(_.toInt).toList
  val as = readLine().split(" ").map(_.toInt).toList

  val cuts = as.zipWithIndex.sortBy(_._1).takeRight(m * k).map(_._2).sorted.zipWithIndex.filter(x => x._2 % m == 0).map(_._1).tail

  println(as.sorted.takeRight(m * k).sum)
  println(cuts.mkString(" "))
}

import scala.io.StdIn

object YetAnotherArrayPartition {
  def main(args: Array[String]): Unit = {
    val content = StdIn.readLine()
    val line1Arg = content.split(" ")
    val nums = line1Arg(0).toInt
    val minSize = line1Arg(1).toInt
    val partitions = line1Arg(2).toInt
    val line2 = StdIn.readLine()
    val line2Arg = line2.split(" ")
    val arrayBuffer = scala.collection.mutable.ArrayBuffer[Int]()
    for (i <- 0 until nums) {
      arrayBuffer.append(line2Arg(i).toInt)
    }
    val validNum = minSize * partitions
    val sorted = arrayBuffer.sorted.reverse
    val minValid = sorted(validNum - 1)
    var idx = validNum - 1
    var minValidNumCount = 0
    while (minValid == sorted(idx)) {
      minValidNumCount += 1
      idx -= 1
    }
    val splitArray = scala.collection.mutable.ListBuffer[Int]()
    var splitIdx = 0
    var remainValidCount = minValidNumCount
    var curPartitionValidNums = 0
    var i = 0
    var break = false
    var curPartitionSum = 0
    var totalSum = 0
    while (i < nums && !break) {
      if (arrayBuffer(i) > minValid) {
        curPartitionValidNums += 1
        curPartitionSum += arrayBuffer(i)
        if (curPartitionValidNums == minSize) {
          totalSum += curPartitionSum
          curPartitionSum = 0
          curPartitionValidNums = 0
          splitIdx += 1
          if (splitIdx != partitions) {
            splitArray.append(i + 1)
          }
        }
      } else if (arrayBuffer(i) == minValid && remainValidCount > 0) {
        remainValidCount -= 1
        curPartitionValidNums += 1
        curPartitionSum += arrayBuffer(i)
        if (curPartitionValidNums == minSize) {
          totalSum += curPartitionSum
          curPartitionSum = 0
          curPartitionValidNums = 0
          splitIdx += 1
          if (splitIdx != partitions) {
            splitArray.append(i + 1)
          }
        }
      } else {

      }

      if (splitIdx == partitions) {
        break = true
      }
      i += 1
    }
    println(totalSum)
    println(splitArray.mkString(" "))
  }
}

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

object Codeforces114B {

  def getSubArrayPartitions(n: Int, m: Int, k: Int, a: Seq[Int]): (Int, Seq[Int]) = {
    val largerNumbers = a.sorted.reverse.take(m * k)
    val largeNumberFrequencyMap: mutable.Map[Int, Int] = toFrequencyMap(largerNumbers)
    val partition = new Array[Int](k - 1)
    var inputIndex = 0
    for (outputIndex <- partition.indices) {
      var subArrayIndex = 0
      while (subArrayIndex < m) {
        val element = a(inputIndex)
        if (largeNumberFrequencyMap.getOrElse(element, 0) > 0) {
          largeNumberFrequencyMap(element) -= 1
          subArrayIndex += 1
        }
        inputIndex += 1
      }
      partition(outputIndex) = inputIndex
    }
    (largerNumbers.sum, partition)
  }

  private def toFrequencyMap(numbers: Seq[Int]): mutable.Map[Int, Int] = {
    val frequencyMap = new mutable.HashMap[Int, Int]()
    for (number <- numbers) {
      frequencyMap(number) = frequencyMap.getOrElse(number, 0) + 1
    }
    frequencyMap
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)

    val result = getSubArrayPartitions(n, m, k, a)
    val sum = result._1
    val partition = result._2
    println(sum)
    println(partition.mkString(" "))
  }
}


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

object IceSkating {
  case class Edge(u:Int,v:Int) {
    def ==(that:Edge):Boolean={
      return (this.u==that.u)||(this.v==that.v)
    }
  }
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var n=in.readInt()
    val edges=Array.fill[Edge](n)(null)
    for(i<- 0 until n){
      val arr=in.readLine().split(" ").map(_.toInt)
      edges(i)=Edge(arr(0),arr(1))
    }

    //The intuition is to find connected component using dfs
    //and we will consider two component is connected is two points are fall under same x or y co-ordinate
    val visited=Array.fill[Boolean](n)(false)
    var cou=0
    for(i<- 0 until edges.length ){
      if(!visited(i)){
        cou+=1
        dfs(edges,visited,i)
      }
    }
    println(cou-1)
  }
  def dfs(edges:Array[Edge],vis:Array[Boolean],n:Int):Unit={
    vis(n)=true
    for(i<- 0 until edges.length if(!vis(i) && edges(i)==edges(n))){
      dfs(edges,vis,i)
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var cache = Set.empty[(Set[Int], Set[Int])]
  Range(0, n).map{_ =>
    in.next().split(" ").map(_.toInt)
  }.foreach {
    case Array(a, b) =>
      val first = cache.find(_._1.contains(a))
      val second = cache.find(_._2.contains(b))
      if (first.isEmpty && second.isEmpty)
        cache += ((Set(a), Set(b)))
      else if (first.isDefined && second.isDefined) {
        cache -= first.get
        cache -= second.get
        cache += ((first.get._1 ++ second.get._1, first.get._2 ++ second.get._2))
      } else if (first.isDefined) {
        cache -= first.get
        cache += ((first.get._1 + a, first.get._2 + b))
      } else {
        cache -= second.get
        cache += ((second.get._1 + a, second.get._2 + b))
      }
  }
  println(cache.size - 1)
}

import java.util

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A217 extends App {

  def dfs(g: mutable.Map[Int, util.ArrayList[Int]], start: Int, visited: Array[Boolean]): Unit = {
    visited(start) = true
    if (g.contains(start)) {
      val neighbors: util.ArrayList[Int] = g(start)
      for (i <- 0 until neighbors.size()) {
        val neighbor: Int = neighbors.get(i)
        if (!visited(neighbor)) {
          dfs(g, neighbor, visited)
        }
      }
    }
  }

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val coords: Array[(Int, Int)] = Array.ofDim(n)
    for (i <- 0 until n) {
      val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      coords(i) = (x, y)
    }
    val g: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty[Int, util.ArrayList[Int]]
    for (i <- 0 until n) {
      for (j <- i+1 until n) {
        if (coords(i)._1 == coords(j)._1 || coords(i)._2 == coords(j)._2) {
          if (!g.contains(i)) {
            g += (i -> new util.ArrayList[Int]())
          }
          g(i).add(j)
          if (!g.contains(j)) {
            g += (j -> new util.ArrayList[Int]())
          }
          g(j).add(i)
        }
      }
    }
    val visited: Array[Boolean] = Array.ofDim(n)
    var c = 0
    for (i <- 0 until n) {
      if (!visited(i)) {
        dfs(g, i, visited)
        c += 1
      }
    }
    println(c-1)
  }

  solve()

}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A217 extends App {

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val xs: mutable.Set[Int] = mutable.Set.empty[Int]
    val ys: mutable.Set[Int] = mutable.Set.empty[Int]
    for (i <- 0 until n) {
      val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      xs += x
      ys += y
    }
    println(Math.min(xs.size, ys.size) - 1)
  }

  solve()

}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Let's denote monotonic renumeration of array $$$a$$$ as an array $$$b$$$ consisting of $$$n$$$ integers such that all of the following conditions are met:  $$$b_1 = 0$$$;  for every pair of indices $$$i$$$ and $$$j$$$ such that $$$1 \le i, j \le n$$$, if $$$a_i = a_j$$$, then $$$b_i = b_j$$$ (note that if $$$a_i \ne a_j$$$, it is still possible that $$$b_i = b_j$$$);  for every index $$$i \in [1, n - 1]$$$ either $$$b_i = b_{i + 1}$$$ or $$$b_i + 1 = b_{i + 1}$$$. For example, if $$$a = [1, 2, 1, 2, 3]$$$, then two possible monotonic renumerations of $$$a$$$ are $$$b = [0, 0, 0, 0, 0]$$$ and $$$b = [0, 0, 0, 0, 1]$$$.Your task is to calculate the number of different monotonic renumerations of $$$a$$$. The answer may be large, so print it modulo $$$998244353$$$.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print one integer — the number of different monotonic renumerations of $$$a$$$, taken modulo $$$998244353$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)

    // [l, r]
    class Seg {
      var l: Int = -1
      var r: Int = -1
    }

    object Seg {
      def apply(l: Int, r: Int) = {
        val s = new Seg
        s.l = l
        s.r = r
        s
      }
    }

    // Aの初期セグメント
    val S = mutable.Map[Int, Seg]()
    REP(N) { i =>
      if (!S.contains(A(i))) S(A(i)) = Seg(i, i)
      else {
        val s = S(A(i))
        if (i < s.l) s.l = i
        else if (i > s.r) s.r = i
      }
    }

    val uf = new UnionFind(N)

    // unionfindのsetごとのセグメント
    val dynamicS = mutable.Map[Int, Seg]()
    REP(N) { i =>
      dynamicS(uf.find(i)) = Seg(i, i)
    }

    def uniteAll(ll: Int, r: Int): Unit = {
      var l = ll
      while(r > l) {
        uf.unite(l, l + 1)
        l += 1
      }
    }

    S.values.foreach { s =>
      // まだ同じセグメントになっていないなら２つのセグメントの間を全部融合する
      if (uf.find(s.l) != uf.find(s.r)) {
        val s1 = dynamicS(uf.find(s.l))
        val s2 = dynamicS(uf.find(s.r))
        // この２つのセグメントは必ず共通部分がない
        if (s1.l < s2.l) {
          uniteAll(s1.r, s2.l)
        } else {
          uniteAll(s2.r, s1.l)
        }

        dynamicS(uf.find(s.l)) = Seg(min(s1.l, s2.l), max(s1.r, s2.r))
      }
    }

    var ans = 1L
    val frees = countDisjointSets(uf) - 1 // b0が固定なので-1
    REP(frees) { _ =>
      ans = ans * 2 % MOD
    }

    out.println(ans)
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

  def countDisjointSets(uf: UnionFind): Int = {
    var cnt = 0
    REP(uf.n) { i =>
      if (uf.find(i) == i) cnt += 1
    }
    cnt
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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

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

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

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

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

object Main {
    import java.util.Scanner
    import java.io.PrintWriter
    import scala.collection.mutable.Map

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

    def main(args: Array[String]) {
        val MOD = 998244353
        def pwr2(e: Long): Long = {
            if (e == 0) 1
            else {
                val t: Long = pwr2(e / 2)
                if (e % 2 == 0) t * t % MOD
                else t * t * 2 % MOD
            }
        }

        val n = in.nextInt
        val a = (for (i <- 0 until n) yield in.nextInt).toArray
        val last = Map[Int, Int]()
        for (i <- 0 until n)
            last(a(i)) = i
        var r = -1
        var cnt = 0
        for (i <- 0 until n) {
            cnt = if (i > r) cnt + 1 else cnt
            r = if (last(a(i)) > r) last(a(i)) else r
        }
        println(pwr2(cnt - 1))
    }
}


There are $$$n$$$ piles of stones, where the $$$i$$$-th pile has $$$a_i$$$ stones. Two people play a game, where they take alternating turns removing stones.In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$)  — the number of piles. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$)  — $$$a_i$$$ is equal to the number of stones in the $$$i$$$-th pile. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second".

First
Second
Second
First
First
Second
First

NoteIn the first test case, the first player will win the game. His winning strategy is:   The first player should take the stones from the first pile. He will take $$$1$$$ stone. The numbers of stones in piles will be $$$[1, 5, 4]$$$.  The second player should take the stones from the first pile. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 5, 4]$$$.  The first player should take the stones from the second pile because the first pile is empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 1, 4]$$$.  The second player should take the stones from the second pile because the first pile is empty. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 0, 4]$$$.  The first player should take the stones from the third pile because the first and second piles are empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 0, 0]$$$.  The second player will lose the game because all piles will be empty.

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val pile = in.nextInt()

      val numbers = in.line().split(" ").map(_.toInt)

      var count = 0
      val len   = numbers.length

      var cons = 0
      var f    = false
      numbers.foreach(num => {
        if (num == 1 && !f) {
          cons = cons + 1
        } else {
          f = true
        }
      })

      if (cons == len) {
        if (len % 2 == 0) {
          println("Second")
        } else {
          println("First")
        }
      } else {
        if (cons % 2 == 1) {
          println("Second")
        } else {
          println("First")
        }
      }

      /*var start = false
      0.until(len)
        .foreach(index => {
          if (numbers(index) > 1) {
            start = true
          } else {
            if (start) count = count + 1
            count = count + 1
            start = false
          }
        })
      if (start) count = count + 1
      println(count)
      if (count % 2 == 0) println("Second") else println("First")*/
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(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(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

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

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val pile = in.nextInt()

      val numbers = in.line().split(" ").map(_.toInt)

      var count = 0
      val len   = numbers.length
      var start = false
      0.until(len)
        .foreach(index => {
          if (numbers(index) > 1) {
            start = true
          } else {
            if (start) count = count + 1
            count = count + 1
            start = false
          }
        })
      if (start) count = count + 1
      if (count % 2 == 0) println("Second") else println("First")
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(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(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

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


Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string — each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2·ai ≤ |s|.You face the following task: determine what Pasha's string will look like after m days.

The first line of the input contains Pasha's string s of length from 2 to 2·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≤ m ≤ 105) —  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≤ ai; 2·ai ≤ |s|) — the position from which Pasha started transforming the string on the i-th day.

In the first line of the output print what Pasha's string s will look like after m days.

object CF297B extends App{
  import scala.io.StdIn

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val sortedArray = StdIn
    .readLine()
    .split("\\s+")
    .map(x => x.toInt-1)
    .groupBy(x => x)
    .filter(valAndArray => valAndArray._2.length % 2 == 1)
    .keys
    .toArray
    .sorted

  for((valueFrom,index) <- sortedArray.view.zipWithIndex){
    if(index % 2 == 0){

      val valueUntil = if(sortedArray.length-1 == index)  inputLength/2 else sortedArray(index + 1)

      for(indexToChange <- valueFrom until valueUntil){
        val tmpValue = input(indexToChange)

        val oppositeIndexToChange = inputLength - indexToChange - 1

        input(indexToChange) = input(oppositeIndexToChange)

        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}

import scala.collection.mutable

object CF297B extends App{
  import scala.io.StdIn
  import scala.collection.mutable

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val inputArray = StdIn.readLine().split("\\s+").map(x => x.toInt-1).sorted.toList :+ inputLength / 2

//  val hashMap = new mutable.HashMap[Int, Int]()
//
//  inputArray.foreach(x => {
//    val value = hashMap.get(x)
//    var cnt = 1
//    if(value.isEmpty){
//      hashMap.put(x, 1)
//    } else {
//      hashMap.put(x, value.get + 1)
//    }
//  })
//
//  val sorted = hashMap.filter(keyValue => keyValue._2 % 2 == 1).keys.toList.sorted :+ inputLength / 2

  val sorted = mutable.MutableList[Int]()
  var prev = inputArray.head
  var cnt = 0
  inputArray.foreach(value => {
    if (prev != value){
      if(cnt % 2 == 1){
        sorted += prev
      }
      cnt = 1
      prev = value
    } else {
      cnt = cnt + 1
    }
  })
  if(cnt % 2 == 1)sorted += prev

  val arr = sorted.toArray

  for((value1,index) <- arr.view.zipWithIndex){
    if(index % 2 == 0 && index < arr.length-1){
      for(indexToChange <- value1 until arr(index+1)){
        val tmpValue = input(indexToChange)
        val oppositeIndexToChange = inputLength - indexToChange - 1
        input(indexToChange) = input(oppositeIndexToChange)
        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}

object CF297B extends App{
  import scala.io.StdIn
  import scala.collection.mutable

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val inputArray = StdIn.readLine().split("\\s+").map(x => x.toInt-1)

  val hashMap = new mutable.HashMap[Int, Int]()
  hashMap.put(inputLength / 2, 1)

  inputArray.foreach(x => {
    val value = hashMap.get(x)
    var cnt = 1
    if(value.isEmpty){
      hashMap.put(x, 1)
    } else {
      hashMap.put(x, value.get + 1)
    }
  })

  val arr = hashMap.filter(keyValue => keyValue._2 % 2 == 1).keys.toArray.sorted

  for((value1,index) <- arr.view.zipWithIndex){
    if(index % 2 == 0 && index < arr.length-1){
      for(indexToChange <- value1 until arr(index+1)){
        val tmpValue = input(indexToChange)
        val oppositeIndexToChange = inputLength - indexToChange - 1
        input(indexToChange) = input(oppositeIndexToChange)
        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}

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

import scala.StringBuilder
import scala.collection.mutable

object B {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def solve: Int = {
    val s = next.toCharArray
    val m = nextInt
    val length: Int = s.length
    val cnt = new Array[Int](length)
    val bitSet = new util.BitSet()
    val bits = new Array[Boolean](length)
    for (i <- 0 until length) {
      bits(i) = true
    }
    for (i <- 0 until m) {
      val x = nextInt - 1
      bits(x) = !bits(x)
      bits(length - x - 1) = !bits(length - x - 1)
    }
    var curr = 0
    val sb = new StringBuilder()
    for (i <- 0 until length / 2) {
      if (!bits(i)) {
        curr += 1
      }
      if (curr % 2 == 0) {
        out.print(s(i))
        sb.append(s(length - i - 1))
      } else {
        out.print(s(length - i - 1))
        sb.append((s(i)))
      }
    }
    if (length % 2 == 1) {
      out.print(s(length / 2))
    }
    out.println(sb.reverse.toString())
    return 0
  }
}

import java.lang.Math.pow

import scala.io.StdIn

/**
 * Created by pol on 29/03/15.
 */
object CR297_B extends App {
  var input = StdIn.readLine().toCharArray
  var m = StdIn.readInt()
  var ai = new Array[Int](pow(10d, 5d).toInt);
  for (i <- StdIn.readLine().trim().split(" ")) {
    ai(i.toInt-1) += 1
  }

  for (i <- 0 until input.length / 2) {
    if (i != 0) {
      ai(i) += ai(i - 1)
    }
    if (ai(i) % 2 == 1) {
      val left: Char = input(i)
      val right: Char = input(input.length - i - 1)
      input(i) = right
      input(input.length - i - 1) = left
    }
  }

  println(String.copyValueOf(input))
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val S=nextString.toCharArray
    val n=nextInt
    val a=Array.fill(n)(0)
    for(i<-0 until n){a(i)=nextInt-1}
    scala.util.Sorting.quickSort(a)
    var p=0
    var count=0
    for(i<-0 until S.length/2){

      while(p<n && a(p)==i){
        p+=1
        count+=1
      }
      if(count%2==1){
        val tmp=S(i)
        S(i)=S(S.length-i-1)
        S(S.length-i-1)=tmp
      }
    }
    for(i<-0 until S.length){out.print(S(i))}

    //code ends here
    out.flush
    out.close
  }
}

object CodeForces extends App {

  def solve = {
    val str = readLine
    val revStr = str.reverse
    val strLen = str.length
    val num = readLine toInt
    val opArr = readLine().split(' ').map(c => c.toInt)

    var revStatArr = Array.fill(strLen / 2)(0)
    for (op <- opArr if 2 * op <= strLen) {
      revStatArr(op - 1) += 1
    }

    var currRev = 0
    var sbF = new StringBuilder(strLen / 2)
    var sbB = new StringBuilder(strLen / 2)
    def isEven(n: Int) = n % 2 == 0

    for (i <- 0 until strLen / 2) {
      currRev += revStatArr(i)

      sbF append (if (isEven(currRev)) str(i) else revStr(i))
      sbB append (if (!isEven(currRev)) str(i) else revStr(i))
    }

    val resStr = sbF append (if (isEven(strLen)) "" else str(strLen / 2)) append sbB.reverse
    println(resStr)
  }

  solve
}

object CodeForces extends App {

  def solve = {
    val str = readLine
    val strLen = str.length
    val num = readLine toInt
    val opArr = readLine().split(' ').map(c => c.toInt)
    var revStatArr = Array.fill(strLen / 2)(0)

    for (op <- opArr if 2 * op <= strLen) {
      revStatArr(op - 1) += 1
    }

    var currRev = 0
    var sb = new StringBuilder(strLen)
    for (i <- 0 until strLen) sb += str(strLen / 2)
    def isEven(n: Int) = n % 2 == 0
    def oospar(i: Int) = strLen - i - 1

    for (i <- 0 until strLen / 2) {
      currRev += revStatArr(i)

      sb(i) = if (isEven(currRev)) str(i) else str(oospar(i))
      sb(oospar(i)) = if (!isEven(currRev)) str(i) else str(oospar(i))
    }

    val resStr = sb.toString()
    println(resStr)
  }

  solve
}

object CodeForces extends App {
    val str = readLine
    val revStr = str.reverse
    val strLen = str.length
    val num = readLine toInt
    val opArr = readLine().split(' ').map(c => c.toInt)

    val revStatArr = Array.fill(strLen / 2)(0)
    for (op <- opArr if 2 * op <= strLen) {
      revStatArr(op - 1) += 1
    }

    var currRev = 0
    val sbF = new StringBuilder(strLen / 2)
    val sbB = new StringBuilder(strLen / 2)

    def isEven(n: Int) = n % 2 == 0

    for (i <- 0 until strLen / 2) {
      currRev += revStatArr(i)
      sbF append (if (isEven(currRev)) str(i) else revStr(i))
      sbB append (if (!isEven(currRev)) str(i) else revStr(i))
    }

    println(sbF append (if (isEven(strLen)) "" else str(strLen / 2)) append sbB.reverse)
}

object CF297B extends App{
  import scala.io.StdIn

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val sortedArray = StdIn
    .readLine()
    .split("\\s+")
    .map(x => x.toInt-1)
    .groupBy(x => x)
    .filter(valAndArray => valAndArray._2.length % 2 == 1)
    .keys
    .toArray
    .sorted

  println("sortedArray" + sortedArray.map(x => x + 1).toList)

  for((valueFrom,index) <- sortedArray.view.zipWithIndex){
    if(index % 2 == 0){

      val valueUntil = if(sortedArray.length-1 == index)  inputLength/2 else sortedArray(index + 1)

      for(indexToChange <- valueFrom until valueUntil){
        val tmpValue = input(indexToChange)

        val oppositeIndexToChange = inputLength - indexToChange - 1

        input(indexToChange) = input(oppositeIndexToChange)

        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}

object CF297B extends App{
  import scala.io.StdIn

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val sortedArray = StdIn
    .readLine()
    .split("\\s+")
    .map(x => x.toInt-1)
    .groupBy(x => x)
    .filter(valAndArray => valAndArray._2.length % 2 == 1)
    .keys
    .toArray
    .sorted

  for((valueFrom,index) <- sortedArray.view.zipWithIndex){
    if(index % 2 == 0){

      val valueUntil = if(sortedArray.length-1 == index)  inputLength/2 else index + 1

      for(indexToChange <- valueFrom until valueUntil){
        val tmpValue = input(indexToChange)

        val oppositeIndexToChange = inputLength - indexToChange - 1

        input(indexToChange) = input(oppositeIndexToChange)

        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}


You are given a sequence $$$b_1, b_2, \ldots, b_n$$$. Find the lexicographically minimal permutation $$$a_1, a_2, \ldots, a_{2n}$$$ such that $$$b_i = \min(a_{2i-1}, a_{2i})$$$, or determine that it is impossible.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). The first line of each test case consists of one integer $$$n$$$ — the number of elements in the sequence $$$b$$$ ($$$1 \le n \le 100$$$). The second line of each test case consists of $$$n$$$ different integers $$$b_1, \ldots, b_n$$$ — elements of the sequence $$$b$$$ ($$$1 \le b_i \le 2n$$$). It is guaranteed that the sum of $$$n$$$ by all test cases doesn't exceed $$$100$$$.

For each test case, if there is no appropriate permutation, print one number $$$-1$$$. Otherwise, print $$$2n$$$ integers $$$a_1, \ldots, a_{2n}$$$ — required lexicographically minimal permutation of numbers from $$$1$$$ to $$$2n$$$.

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)

  }
  val edges = Array.fill(201)(Array.fill(201)(false))
  val used = Array.fill(201)(true)
  val res = Array.fill(201)(0)
  val pos = Array.fill(201)(0)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ numCase =>

      val n = in.nextInt()
      val n2 = n*2
      (1 to n2).foreach{ i =>
        used(i) = false
        (1 to n2).foreach{ j =>
          edges(i)(j) = false
        }
      }
      (1 to n).foreach{ i =>
        val b = in.nextInt()
        res(i*2-1) = b
        used(b) = true
        pos(b) = i*2-1
        ((b+1) to n2).foreach{ j =>
          edges(b)(j) = true
        }
      }

      var imposible = false
      (1 to n2).reverse.foreach{ b =>
        if(!used(b)){

          val potentials = (1 to n2).filter{ j =>  edges(j)(b)}
          if(potentials.isEmpty){
            imposible = true
          }else{
            val j = potentials.max
            used(b) = true
            pos(b) = pos(j) +1
            res(pos(b)) = b
            (1 to n2).foreach{ k =>
              edges(k)(b) = false
              edges(k)(j) = false
              edges(b)(k) = false
              edges(j)(k) = false
            }
          }
        }

      }
      if(imposible){
        out.println("-1")
      }else{
        //println(res.slice(1,n2+1).mkString(" "))

        (2 to n2 by 2).foreach{ i =>
          val pot = ((i+2) to n2 by 2).filter{ k =>  res(k) > res(i-1) && res(i) > res(k-1) && res(k) < res(i)}
          if(pot.nonEmpty){
            val j = pot.minBy(k => res(k))
            val z = res(j)
            res(j) = res(i)
            res(i) = z
          }
        }
        //println(res.slice(1,n2+1).mkString(" "))
        out.println(res.slice(1,n2+1).mkString(" "))
      }

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?

First line of input contains an integer n (2 ≤ n ≤ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — the bids of players.

Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.

NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.

//package round318.c

import java.util.Scanner

object Main extends App {

  def possible(a: Long, b: Long): Option[Long] = {

    import Math._
    var aa = a
    var k1 = 0
    var m1 = 0
    while(aa % 2 == 0) { aa /= 2; k1 += 1 }
    while(aa % 3 == 0) { aa /= 3; m1 += 1 }

    var bb = b
    var k2 = 0
    var m2 = 0
    while(bb % 2 == 0) { bb /= 2; k2 += 1 }
    while(bb % 3 == 0) { bb /= 3; m2 += 1 }

    if(aa != bb) None
    else Some((pow(2, max(k1,k2)) * pow(3, max(m1,m2))).toLong * aa)
  }

  val sc = new Scanner(System.in)

  val n = sc.nextInt
  var ok = true

  var bid = sc.nextLong

  (1 until n) foreach { _ =>
    val bid2 = sc.nextLong
    possible(bid, bid2) match {
      case None =>
        ok = false
      case Some(bid3) =>
        bid = bid3
    }
  }

  println(if (ok) "Yes" else "No")

}

object Codeforces extends App {
  val in = new java.util.Scanner(System.in)
  var n = in.nextInt()
  var a = Array.ofDim[Int](n);
  for (i <- 0 until n) {
    a(i) = in.nextInt()
    while (a(i) % 2 == 0) a(i) /= 2
    while (a(i) % 3 == 0) a(i) /= 3
  }
  var ok = true
  for (i <- 1 until n)
    if (a(i) != a(0))
      ok = false
  println(if (ok) "Yes" else "No")
}

object Solution extends App {

  def min(a: Int): Int = {
    if (a % 2 == 0) min(a / 2)
    else if (a % 3 == 0) min(a / 3)
    else a
  }

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).map(min)
  if (data.distinct.length == 1)
    println("Yes")
  else
    println("No")
}

object A573 {

  import IO._

  def gcd(a: Int, b: Int): Int = {
    if(b == 0) a else gcd(b, a%b)
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val g = in.foldLeft(in(0)){case (res, i) => gcd(res, i)}
    var break = false
    for(i <- 0 until n if !break) {
      var num = in(i)/g
      while(num%2 == 0) num /= 2
      while(num%3 == 0) num /= 3
      if(num != 1) {
        println("No")
        break = true
      }
    }
    if(!break) println("Yes")
  }

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

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

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

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

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

}

import scala.collection._

object A extends App {

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

  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)

  val Array(n) = readInts(1)
  val as = readInts(n)

  val d = as.reduce(gcd)
  val ds = as.map(_ / d)

  var ok = true
  for (x <- ds) {
    var xx = x
    while ((xx & 1) == 0) xx >>= 1
    while (xx % 3 == 0) xx /= 3
    if (xx > 1) ok = false
  }

  println(if (ok) "Yes" else "No")
}

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

object ProbA {

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

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

   /*def primeFactorsWithout23(a: Int) : Map[Int,Int] = {
     def go(a: Int, factors : Map[Int,Int],p: Int) : Map[Int,Int] = {
       //println(s"testing $a : factors" + factors)
       if (a == 1) factors
       else if (a%p == 0)
               go(a/p, factors + (p -> (factors.getOrElse(p, 0) + 1))  ,p)
            else go(a,factors,p+2)
     }
     var x = a
     while (x%2 == 0) x = x/2
     while (x%3 == 0) x = x/3
     go(x,Map(),5)
   }*/

   def remove2(a: Int) : Int = {
     if (a%2 != 0) a else remove2(a/2)
   }
    def remove3(a: Int) : Int = {
     if (a%3 != 0) a else remove3(a/3)
   }

   def main(args: Array[String]) {
     val n = readInt
     val bids = readInts
    // val primeFactors = primeFactorsWithout23(bids(0))
     val reduced = remove2(remove3(bids(0)))
     if (bids.forall{ a => remove2(remove3(a)) == reduced})
       println("YES")
     else
       println("NO")

   }

}


Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.

The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers.

Print the number of operations needed to destroy all towers.

NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.    After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.

object Codeforces extends App {
  val in = new java.util.Scanner(System.in)
  var n = in.nextInt()
  var a = Array.ofDim[Int](n + 2)
  for (i <- 1 to n)
    a(i) = in.nextInt()
  a(0) = 0
  a(n + 1) = 0
  for (i <- 1 to n)
    a(i) = Math.min(a(i), a(i - 1) + 1)
  for (i <- n to 1 by -1)
    a(i) = Math.min(a(i), a(i + 1) + 1)
  var res = 0
  for (i <- 1 to n)
    res = Math.max(res, a(i))
  println(res)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data = in.next().split(" ").map(_.toLong)
  val answer = Array.ofDim[Long](n)
  answer(0) = Math.min(data.head, 1)
  Range(1, n).foreach(i => answer(i) = Math.min(data(i), answer(i - 1) + 1))
  answer(n - 1) = Math.min(data.last, 1)
  Range(n - 2, 0, -1).foreach(i => answer(i) = Math.min(answer(i), answer(i + 1) + 1))

  println(answer.max)
}

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)
  val hs = readInts(n)

  val res = Array.ofDim[Int](n)

  var h = 0
  for (i <- hs.indices) {
    h = (h + 1) min hs(i)
    res(i) = h
  }

  h = 0
  for (i <- hs.indices.reverse) {
    h = (h + 1) min hs(i)
    res(i) = h min res(i)
  }

  println(res.max)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: IndexedSeq[Long] = in.next().split(" ").map(_.toLong).toIndexedSeq
  var sum = data.sum
  var j = 0
  if (data.min > (data.length + 1) / 2)
    println((data.length + 1) / 2)
  else
    while (sum > 0) {
      j += 1
      data = data.indices.map { i =>
        val ir =
          if (i > 0 && i < data.length - 1)
            Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
          else
            0
        sum += ir - data(i)
        ir
      }
      data = data.dropWhile(_ == 0).dropRight(1)
    }
  println(j)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Int] = in.next().split(" ").map(_.toInt)
  val data1: Array[Int] = data.clone()
  var left = 0
  var right = n - 1
  var sum = data.sum
  while (data(left) == 0 && left <= right)
    left += 1
  while (data(right) == 0 && right >= left)
    right -= 1
  var i = 0
//  println (sum)
  while (sum > 0) {
    i += 1
    sum -= data(left)
    sum -= data(right)
    data1(left) = 0
    data1(right) = 0
    Range(left + 1, right).foreach { i =>
      val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
      sum += ir - data(i)
      data(i) = ir
    }
    data = data1.clone()
//    println(sum)
//    println(data.mkString(" "))
    while (data(left) == 0 && left <= right)
      left += 1
    while (data(right) == 0 && right >= left)
      right -= 1
  }
  println(i + 1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Int] = in.next().split(" ").map(_.toInt)
  val data1: Array[Int] = data.clone()
  var sum = data.sum
//  println (sum)
  var j = 0
  while (sum > 0) {
    j += 1
    data.indices.foreach { i =>
      val ir =
        if (i > 0 && i < data.length - 1)
          Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
        else
          0
      sum += ir - data(i)
      data1(i) = ir
    }
    data = data1.clone()
  }
  println(j)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Int] = in.next().split(" ").map(_.toInt)
  val data1: Array[Int] = data.clone()
  var left = 0
  var right = n - 1
  var sum = data.sum
  while (data(left) == 0 && left < right)
    left += 1
  while (data(right) == 0 && right > left)
    right -= 1
  var i = 0
//  println (sum)
  while (sum > 0) {
    i += 1
    sum -= data(left)
    sum -= data(right)
    data1(left) = 0
    data1(right) = 0
    Range(left + 1, right).foreach { i =>
      val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
      sum += ir - data(i)
      data1(i) = ir
    }
    data = data1.clone()
    while (data(left) == 0 && left < right)
      left += 1
    while (data(right) == 0 && right > left)
      right -= 1
  }
  println(i)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Long] = in.next().split(" ").map(_.toLong)
  val data1: Array[Long] = data.clone()
  var sum = data.sum
//  println (sum)
  var j = 0
  while (sum > 0) {
    j += 1
    data.indices.foreach { i =>
      val ir =
        if (i > 0 && i < data.length - 1)
          Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
        else
          0
      sum -= ir + data(i)
      data1(i) = ir
    }
    data = data1.clone()
  }
  println(j)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Int] = in.next().split(" ").map(_.toInt)
  val data1: Array[Int] = data.clone()
  var left = 0
  var right = n - 1
  var sum = data.sum
  while (data(left) == 0 && left <= right)
    left += 1
  while (data(right) == 0 && right >= left)
    right -= 1
  var i = 0
//  println (sum)
  while (sum > 0) {
    i += 1
    sum -= data(left)
    sum -= data(right)
    data1(left) = 0
    data1(right) = 0
    Range(left + 1, right).foreach { i =>
      val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
      sum += ir - data(i)
      data1(i) = ir
    }
    data = data1.clone()
    while (data(left) == 0 && left <= right)
      left += 1
    while (data(right) == 0 && right >= left)
      right -= 1
  }
  println(i)
}


Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $$$T$$$, which coordinates to be found out.Bob travelled around the world and collected clues of the treasure location at $$$n$$$ obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?As everyone knows, the world is a two-dimensional plane. The $$$i$$$-th obelisk is at integer coordinates $$$(x_i, y_i)$$$. The $$$j$$$-th clue consists of $$$2$$$ integers $$$(a_j, b_j)$$$ and belongs to the obelisk $$$p_j$$$, where $$$p$$$ is some (unknown) permutation on $$$n$$$ elements. It means that the treasure is located at $$$T=(x_{p_j} + a_j, y_{p_j} + b_j)$$$. This point $$$T$$$ is the same for all clues.In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of obelisks, that is also equal to the number of clues. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^6 \leq x_i, y_i \leq 10^6$$$) — the coordinates of the $$$i$$$-th obelisk. All coordinates are distinct, that is $$$x_i \neq x_j$$$ or $$$y_i \neq y_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \neq j$$$.  Each of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$-2 \cdot 10^6 \leq a_i, b_i \leq 2 \cdot 10^6$$$) — the direction of the $$$i$$$-th clue. All coordinates are distinct, that is $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \neq j$$$.  It is guaranteed that there exists a permutation $$$p$$$, such that for all $$$i,j$$$ it holds $$$\left(x_{p_i} + a_i, y_{p_i} + b_i\right) = \left(x_{p_j} + a_j, y_{p_j} + b_j\right)$$$.

Output a single line containing two integers $$$T_x, T_y$$$ — the coordinates of the treasure. If there are multiple answers, you may print any of them.

NoteAs $$$n = 2$$$, we can consider all permutations on two elements. If $$$p = [1, 2]$$$, then the obelisk $$$(2, 5)$$$ holds the clue $$$(7, -2)$$$, which means that the treasure is hidden at $$$(9, 3)$$$. The second obelisk $$$(-6, 4)$$$ would give the clue $$$(-1,-3)$$$ and the treasure at $$$(-7, 1)$$$. However, both obelisks must give the same location, hence this is clearly not the correct permutation.If the hidden permutation is $$$[2, 1]$$$, then the first clue belongs to the second obelisk and the second clue belongs to the first obelisk. Hence $$$(-6, 4) + (7, -2) = (2,5) + (-1,-3) = (1, 2)$$$, so $$$T = (1,2)$$$ is the location of the treasure.  In the second sample, the hidden permutation is $$$[2, 3, 4, 1]$$$.

//package codeforces.contest1091

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object NewYearAndTheTreasureGeolocation {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readInt(): Int = {
    val st = new StringTokenizer(br.readLine())
    st.nextToken().toInt
  }

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def addIntPairs(p1: (Long, Long), p2: (Long, Long)): (Long, Long) = (p1._1 + p2._1, p1._2 + p2._2)

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val sum = (0 until 2 * n).foldLeft((0l, 0l))((acc, _) => addIntPairs(acc, readLongPair()))
    println(sum._1 / n + " " + sum._2 / n)
  }

}

object B extends App {

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

  val Array(n) = readInts(1)
  case class P(x: Int, y: Int)

  val obs = Array.fill(n) {
    val Array(x, y) = readInts(2)
    P(x, y)
  }

  val clues = Array.fill(n) {
    val Array(x, y) = readInts(2)
    P(x, y)
  }

  val oMinX = obs.map(_.x).min
  val oMinY = obs.map(_.y).min
  val cMaxX = clues.map(_.x).max
  val cMaxY = clues.map(_.y).max

  val tx = oMinX + cMaxX
  val ty = oMinY + cMaxY

  println(s"$tx $ty")
}

object B extends App {

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

  val Array(n) = readInts(1)
  case class P(x: Int, y: Int)

  val obs = Array.fill(n) {
    val Array(x, y) = readInts(2)
    P(x, y)
  }

  val clues = Array.fill(n) {
    val Array(x, y) = readInts(2)
    P(x, y)
  }

  val cSet = clues.toSet

  for (c1 <- clues) {
    val tx = obs(0).x + c1.x
    val ty = obs(0).y + c1.y
    var i = 1
    while (i < n && cSet.contains(P(tx - obs(i).x, ty - obs(i).y))) {
      i += 1
    }
    if (i == n) {
      println(s"$tx $ty")
      System.exit(0)
    }
  }
}

//package codeforces.contest1091

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object NewYearAndTheTreasureGeolocation {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readInt(): Int = {
    val st = new StringTokenizer(br.readLine())
    st.nextToken().toInt
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def addIntPairs(p1: (Int, Int), p2: (Int, Int)): (Int, Int) = (p1._1 + p2._1, p1._2 + p2._2)

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val sum = (0 until 2 * n).foldLeft((0, 0))((acc, _) => addIntPairs(acc, readIntPair()))
    println(sum._1 / n + " " + sum._2 / n)
  }

}


Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days.Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.

The first line of input contains three space-separated integers n, k, d (1 ≤ n, d ≤ 1000; 1 ≤ k ≤ 109).

If there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k.

NoteNote that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.

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

/**
 * Created by arseny on 15.08.14.
 */
object C 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 = nextInt
    val k = nextInt
    val d = nextInt
    val ans = Array.fill(d, n)(1)
    def can(n: Int, k: Int, d: Int): Boolean = {
      if(k >= n) {
        true
      } else if(d == 1) {
        false
      } else {
        can((n.toDouble / k.toDouble).ceil.toInt, k, d - 1)
      }
    }
    if(!can(n, k, d)) {
      out.println(-1)
    } else {
      def fillAns(from: Int, to: Int, k: Int, d: Int): Unit = {
        //out.println(from, to, k, d)
        if(k >= to - from + 1) {
          for(i <- from to to) {
            ans(d - 1)(i) = i + 1  - from
          }
        } else {
          val g = ((to - from + 1).toDouble / k.toDouble).ceil.toInt
          for(i <- from to to) {
            ans(d - 1)(i) = (i - from) / g + 1
          }
          for(i <- from to to by g) {
            fillAns(i, math.min(i + g - 1, to), k, d - 1)
          }
        }
      }
      fillAns(0, n - 1, k, d)
      (0 until d).foreach{day =>
        out.println(ans(day).mkString(" "))
      }
    }
  }

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

}

import java.math.BigInteger

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_3 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)

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

  val Array(n, k, d) = readInts(3)

  def nToBaseKWithDLen(n:Int):Array[Int] = {
    val res = Array.fill(d)(0)
    var curn = n
    var i = 0
    while(i < d) {
      res(i) = curn % k + 1
      curn = curn / k
      i = i + 1
    }
    res
  }

  val kbig = new BigInteger(k.toString)
  val dbig = new BigInteger(d.toString)
  val nbig = new BigInteger(n.toString)

  if(kbig.pow(d.toInt).compareTo(nbig) < 0){
    println(-1)
  } else {
    val solutions = (1 to n).map(nToBaseKWithDLen(_))
    for(day <- (1 to d)){
      println(solutions.map(_(day - 1)).mkString(" "))
    }
  }
}

object Main {

    def generate(n: Int, d: Int, m: Int): List[List[Int]] = {

        def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {

            def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {
                if (result.length >= n || value > m) {
                    return result
                } else {
                    return iterValue(value + 1,
                        iterPos(pos + 1, cur.+:(value), result))
                }
            }

            if (pos > d) {
                return result.+:(cur)
            } else {
                return iterValue(1, result)
            }

        }

        return iterPos(1, List[Int](), List[List[Int]]())

    }

    def transpose(mat: List[List[Int]]): List[List[Int]] = {
        def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {
            if (rem(0).isEmpty) {
                return result
            } else {
                return iter(rem.map(_.tail), result.+:(rem.map(_.head)))
            }
        }
        return iter(mat, List[List[Int]]())
    }

    def main(args: Array[String]) {
        val input = readLine().trim().split(" ").toList.map(_.toInt)
        val result = generate(input(0), input(2), input(1))
        if (result.length >= input(0)) {
            transpose(result.take(input(0))).foreach(entry => println(entry.mkString(" ")))
        } else {
            println(-1)
        }
    }

}

object Main {

    def generate(n: Int, d: Int, m: Int): List[List[Int]] = {

        def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {

            def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {
                if (result.length >= n || value > m) {
                    return result
                } else {
                    return iterValue(value + 1,
                        iterPos(pos + 1, cur.+:(value), result))
                }
            }

            if (pos > d) {
                return result.+:(cur)
            } else {
                return iterValue(1, result)
            }

        }

        return iterPos(1, List[Int](), List[List[Int]]())

    }

    def transpose(mat: List[List[Int]]): List[List[Int]] = {
        def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {
            if (rem(0).isEmpty) {
                return result
            } else {
                return iter(rem.map(_.tail), result.+:(rem.map(_.head)))
            }
        }
        return iter(mat, List[List[Int]]())
    }

    def main(args: Array[String]) {
        val input = readLine().trim().split(" ").toList.map(_.toInt)
        val result = generate(input(0), input(2), input(1))
        if (result.length == input(0)) {
            transpose(result).foreach(entry => println(entry.mkString(" ")))
        } else {
            println(-1)
        }
    }

}

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

/**
 * Created by arseny on 15.08.14.
 */
object C 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 = nextInt
    val k = nextInt
    val d = nextInt
    val ans = Array.fill(d, n)(1)
    def can(n: Int, k: Int, d: Int): Boolean = {
      if(k >= n) {
        true
      } else if(d == 1) {
        false
      } else {
        can((n.toDouble / k.toDouble).ceil.toInt, k, d - 1)
      }
    }
    if(!can(n, k, d)) {
      out.println(-1)
    } else {
      def getAns(from: Int, to: Int, k: Int, d: Int): Unit = {
        if(k >= to - from + 1) {
          for(i <- from to to) {
            ans(d - 1)(i) = i + 1  - from
          }
        } else {
          val g = ((to - from + 1).toDouble / k.toDouble).ceil.toInt
          for(i <- from to to) {
            ans(d - 1)(i) = i / g + 1
          }
          for(i <- from to to by(k)) {
            getAns(i, math.min(i + k - 1, to), k, d - 1)
          }
        }
      }
      getAns(0, n - 1, k, d)
      (0 until d).foreach{day =>
        out.println(ans(day).mkString(" "))
      }
    }
  }

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

}

object Main {

    def generate(n: Int, d: Int, m: Int): List[List[Int]] = {

        def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {

            def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {
                if (result.length >= n || value > m) {
                    return result
                } else {
                    return iterValue(value + 1,
                        iterPos(pos + 1, cur.+:(value), result))
                }
            }

            if (pos > d) {
                return result.+:(cur)
            } else {
                return iterValue(1, result)
            }

        }

        return iterPos(1, List[Int](), List[List[Int]]())

    }

    def transpose(mat: List[List[Int]]): List[List[Int]] = {
        def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {
            if (rem(0).isEmpty) {
                return result
            } else {
                return iter(rem.map(_.tail), result.+:(rem.map(_.head)))
            }
        }
        return iter(mat, List[List[Int]]())
    }

    def main(args: Array[String]) {
        val input = readLine().trim().split(" ").toList.map(_.toInt)
        val result = generate(input(0), input(1), input(2))
        if (result.length >= input(0)) {
            transpose(result.take(input(0))).foreach(entry => println(entry.mkString(" ")))
        } else {
            println(-1)
        }
    }

}