Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive.

The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops.

In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero.

//package me.jetblack.cf

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object IntersetRing extends App {

  val s = new Scanner(System.in)

  val n = s.nextInt()
  val m = s.nextInt()

  var loop = false

  val vis = Array.ofDim[Boolean](n)

  val graph = Array.ofDim[Int](n, n)
  val deg = Array.ofDim[Int](n)

  val result = ArrayBuffer.empty[(Int, Int)]

  (0 until m).foreach { _ =>
    val (a, b) = (s.nextInt(), s.nextInt())
    connect(a - 1, b - 1)
  }

  def connect(a: Int, b: Int): Unit = {
    if (a == b) {
      loop = true
    }
    graph(a)(b) += 1
    graph(b)(a) += 1
    deg(a) += 1
    deg(b) += 1
  }

  if (n < m || deg.exists(_ > 2) || (loop && n > 1)) {
    println("NO")
  } else if (n == m && connected()) {
    println("YES")
    println("0")
  } else {
    for {
      i <- 0 until n
      j <- 0 until n
    } {
      if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {
        connect(i, j)
        result.append((i, j))
      }
    }
    val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted
    if (rest.size > 1) {
      println("YES")
      result.append((rest(0), rest(1)))
      println(result.size)
      result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + " " + x._2))
    } else if (n == 1 && m == 0) {
      println("YES")
      println("1")
      println("1 1")
    } else {
      println("NO")
    }

  }

  def reachable(a: Int, b: Int): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(a)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) == 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r(b)
  }

  def connected(): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(0)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) >= 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r.forall(x => x)
  }

}

//package me.jetblack.cf

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object IntersetRing extends App {

  val s = new Scanner(System.in)

  val n = s.nextInt()
  val m = s.nextInt()

  var loop = false

  val vis = Array.ofDim[Boolean](n)

  val graph = Array.ofDim[Int](n, n)
  val deg = Array.ofDim[Int](n)

  val result = ArrayBuffer.empty[(Int, Int)]

  (0 until m).foreach { _ =>
    val (a, b) = (s.nextInt(), s.nextInt())
    connect(a - 1, b - 1)
  }

  def connect(a: Int, b: Int): Unit = {
    if (a == b) {
      loop = true
    }
    graph(a)(b) += 1
    graph(b)(a) += 1
    deg(a) += 1
    deg(b) += 1
  }

  if (n < m || deg.exists(_ > 2) || (loop && n > 1) || graph.exists(_.exists(x => x > 1))) {
    println("NO")
  } else if (n == m && connected()) {
    println("YES")
    println("0")
  } else {
    println("YES")
    for {
      i <- 0 until n
      j <- 0 until n
    } {
      if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {
        connect(i, j)
        result.append((i, j))
      }
    }
    val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted
    result.append((rest(0), rest(1)))
    println(result.size)
    result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + " " + x._2))
  }

  def reachable(a: Int, b: Int): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(a)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) == 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r(b)
  }

  def connected(): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(0)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) >= 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r.forall(x => x)
  }

}

//package me.jetblack.cf

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object IntersetRing extends App {

  val s = new Scanner(System.in)

  val n = s.nextInt()
  val m = s.nextInt()

  var loop = false

  val vis = Array.ofDim[Boolean](n)

  val graph = Array.ofDim[Int](n, n)
  val deg = Array.ofDim[Int](n)

  val result = ArrayBuffer.empty[(Int, Int)]

  (0 until m).foreach { _ =>
    val (a, b) = (s.nextInt(), s.nextInt())
    connect(a - 1, b - 1)
  }

  def connect(a: Int, b: Int): Unit = {
    if (a == b) {
      loop = true
    }
    graph(a)(b) += 1
    graph(b)(a) += 1
    deg(a) += 1
    deg(b) += 1
  }

  if (n < m || deg.exists(_ > 2) || (graph.exists(_.exists(x => x > 1)) && n > 1)) {
    println("NO")
  } else if (n == m && connected()) {
    println("YES")
    println("0")
  } else {
    println("YES")
    for {
      i <- 0 until n
      j <- 0 until n
    } {
      if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {
        connect(i, j)
        result.append((i, j))
      }
    }
    val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted
    result.append((rest(0), rest(1)))
    println(result.size)
    result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + " " + x._2))
  }

  def reachable(a: Int, b: Int): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(a)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) == 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r(b)
  }

  def connected(): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(0)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) >= 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r.forall(x => x)
  }

}

//package me.jetblack.cf

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object IntersetRing extends App {

  val s = new Scanner(System.in)

  val n = s.nextInt()
  val m = s.nextInt()

  var loop = false

  val vis = Array.ofDim[Boolean](n)

  val graph = Array.ofDim[Int](n, n)
  val deg = Array.ofDim[Int](n)

  val result = ArrayBuffer.empty[(Int, Int)]

  (0 until m).foreach { _ =>
    val (a, b) = (s.nextInt(), s.nextInt())
    connect(a - 1, b - 1)
  }

  def connect(a: Int, b: Int): Unit = {
    if (a == b) {
      loop = true
    }
    graph(a)(b) += 1
    graph(b)(a) += 1
    deg(a) += 1
    deg(b) += 1
  }

  if (n < m || deg.exists(_ > 2) || (loop && n > 1)) {
    println("NO")
  } else if (n == m && connected()) {
    println("YES")
    println("0")
  } else {
    for {
      i <- 0 until n
      j <- 0 until n
    } {
      if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {
        connect(i, j)
        result.append((i, j))
      }
    }
    val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted
    if (rest.size > 2) {
      println("YES")
      result.append((rest(0), rest(1)))
      println(result.size)
      result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + " " + x._2))
    } else {
      println("NO")
    }

  }

  def reachable(a: Int, b: Int): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(a)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) == 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r(b)
  }

  def connected(): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(0)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) >= 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r.forall(x => x)
  }

}

//package me.jetblack.cf

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object IntersetRing extends App {

  val s = new Scanner(System.in)

  val n = s.nextInt()
  val m = s.nextInt()

  var loop = false

  val vis = Array.ofDim[Boolean](n)

  val graph = Array.ofDim[Int](n, n)
  val deg = Array.ofDim[Int](n)

  val result = ArrayBuffer.empty[(Int, Int)]

  (0 until m).foreach { _ =>
    val (a, b) = (s.nextInt(), s.nextInt())
    connect(a - 1, b - 1)
  }

  def connect(a: Int, b: Int): Unit = {
    if (a == b) {
      loop = true
    }
    graph(a)(b) += 1
    graph(b)(a) += 1
    deg(a) += 1
    deg(b) += 1
  }

  if (n < m || deg.exists(_ > 2) || (loop && n > 1)) {
    println("NO")
  } else if (n == m && connected()) {
    println("YES")
    println("0")
  } else {
    for {
      i <- 0 until n
      j <- 0 until n
    } {
      if (deg(i) < 2 && deg(j) < 2 && !reachable(i, j) && i != j) {
        connect(i, j)
        result.append((i, j))
      }
    }
    val rest = deg.zipWithIndex.filter { case (d, i) => d == 1 }.map(_._2).sorted
    if (rest.size > 1) {
      println("YES")
      result.append((rest(0), rest(1)))
      println(result.size)
      result.map(a => (a._1 + 1, a._2 + 1)).foreach(x => println(x._1 + " " + x._2))
    } else {
      println("NO")
    }

  }

  def reachable(a: Int, b: Int): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(a)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) == 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r(b)
  }

  def connected(): Boolean = {
    val r = Array.ofDim[Boolean](n)
    val x = new java.util.LinkedList[Int]()
    var i = 0
    x.add(0)
    while (!x.isEmpty) {
      val cur = x.poll()
      r(cur) = true
      (0 until n).foreach { i =>
        if (graph(cur)(i) >= 1 && !r(i)) x.add(i)
      }
      i += 1
    }
    r.forall(x => x)
  }

}


Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds:   $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length);  in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.

The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.

Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record.

NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one.

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, M = ni()

    val (from, to) = na2(M, -1)
    val g = packUGraph(N, from, to)

    val visited = Array.ofDim[Boolean](N)
    val ans = ArrayBuffer[Int]()
    type Visit = Int
    val queue = new java.util.PriorityQueue[Visit]()
    queue.add(0)

    while(!queue.isEmpty) {
      val v = queue.poll()
      if (!visited(v)) {
        visited(v) = true
        ans += v + 1

        REP(g(v).length) { i =>
          val e = g(v)(i)
          if (!visited(e)) {
            queue.add(e)
          }
        }
      }
    }

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

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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


You are given an array $$$A$$$, consisting of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$, and an array $$$B$$$, consisting of $$$m$$$ positive integers $$$b_1, b_2, \dots, b_m$$$. Choose some element $$$a$$$ of $$$A$$$ and some element $$$b$$$ of $$$B$$$ such that $$$a+b$$$ doesn't belong to $$$A$$$ and doesn't belong to $$$B$$$. For example, if $$$A = [2, 1, 7]$$$ and $$$B = [1, 3, 4]$$$, we can choose $$$1$$$ from $$$A$$$ and $$$4$$$ from $$$B$$$, as number $$$5 = 1 + 4$$$ doesn't belong to $$$A$$$ and doesn't belong to $$$B$$$. However, we can't choose $$$2$$$ from $$$A$$$ and $$$1$$$ from $$$B$$$, as $$$3 = 2 + 1$$$ belongs to $$$B$$$.It can be shown that such a pair exists. If there are multiple answers, print any.Choose and print any such two numbers.

The first line contains one integer $$$n$$$ ($$$1\le n \le 100$$$) — the number of elements of $$$A$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 200$$$) — the elements of $$$A$$$. The third line contains one integer $$$m$$$ ($$$1\le m \le 100$$$) — the number of elements of $$$B$$$. The fourth line contains $$$m$$$ different integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le 200$$$) — the elements of $$$B$$$. It can be shown that the answer always exists.

Output two numbers $$$a$$$ and $$$b$$$ such that $$$a$$$ belongs to $$$A$$$, $$$b$$$ belongs to $$$B$$$, but $$$a+b$$$ doesn't belong to nor $$$A$$$ neither $$$B$$$. If there are multiple answers, print any.

NoteIn the first example, we can choose $$$20$$$ from array $$$[20]$$$ and $$$20$$$ from array $$$[10, 20]$$$. Number $$$40 = 20 + 20$$$ doesn't belong to any of those arrays. However, it is possible to choose $$$10$$$ from the second array too.In the second example, we can choose $$$3$$$ from array $$$[3, 2, 2]$$$ and $$$1$$$ from array $$$[1, 5, 7, 7, 9]$$$. Number $$$4 = 3 + 1$$$ doesn't belong to any of those arrays.In the third example, we can choose $$$1$$$ from array $$$[1, 3, 5, 7]$$$ and $$$1$$$ from array $$$[7, 5, 3, 1]$$$. Number $$$2 = 1 + 1$$$ doesn't belong to any of those arrays.

import scala.io.StdIn._

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

  val AA = A.toSet
  val BB = B.toSet

  def find(): (Int, Int) = {
    for {
      i <- 0 until n
      j <- 0 until m
    } {
      val x = A(i) + B(j)
      if (!AA.contains(x) && !BB.contains(x)) {
        return (A(i), B(j))
      }
    }

    (0, 0)
  }

  val (a, b) = find()
  println(a + " " + b)
}


Given a sequence $$$a_1, a_2, \ldots, a_n$$$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $$$2$$$ consecutive elements is even.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2,\dots,a_n$$$ ($$$1\leq a_i\leq10^9$$$) — elements of the sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the minimum number of elements to remove from the sequence such that the sum of every $$$2$$$ consecutive elements is even.

NoteIn the first test case, after removing $$$3$$$, the sequence becomes $$$[2,4,6,8]$$$. The pairs of consecutive elements are $$$\{[2, 4], [4, 6], [6, 8]\}$$$. Each consecutive pair has an even sum now. Hence, we only need to remove $$$1$$$ element to satisfy the condition asked.In the second test case, each consecutive pair already has an even sum so we need not remove any element.

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

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

import scala.io.StdIn

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

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

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


Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts. The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts. The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi.  It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.

If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.

import java.util.StringTokenizer

object D extends App {
  val INF = 1000000000000000000L

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

  val n = readInt
  val weights = readLongs

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

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

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

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

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

import scala.collection.mutable

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

  val n = readInt
  val weights = readLongs

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

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

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

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

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

import scala.collection.mutable

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

  val n = readInt
  val weights = readLongs

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

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

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

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

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

import java.util.StringTokenizer

object D extends App {
  val INF = 1000000000000000000L

  var st: StringTokenizer = _

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

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

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

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

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

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

    children.foreach(main(_, cur))

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

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

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

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

import java.util.StringTokenizer

import scala.collection.mutable

object D extends App {
  val INF = 1000000000000000000L

  var st: StringTokenizer = _

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

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

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

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

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

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

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

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

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

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

import java.util.StringTokenizer

object D extends App {
  val INF = 1000000000000000000L

  var st: StringTokenizer = _

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

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

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

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

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

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

    children.foreach(main(_, cur))

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

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

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

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

import scala.collection.mutable

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

  val n = readInt
  val weights = readLongs

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

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

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

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

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

import scala.collection.mutable

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

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

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

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

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

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

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

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

import scala.collection.mutable

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

  val n = readInt
  val weights = readLongs

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

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

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

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

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

import scala.collection.mutable

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

  val n = readInt
  val weights = readLongs

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

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

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

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

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

import scala.collection.mutable

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

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

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

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

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

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


Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.

Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.

NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example:  In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.

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
    val N, M, P = ni()
    val S = na(P)
    val g = nm_c(N, M)

    val CHARS = "123456789"

    def pos(n: Int, m: Int) = n * M + m
    val q = Array.fill[mutable.Set[Int]](P)(mutable.Set())

    REP(N) { i =>
      REP(M) { j =>
        if (g(i)(j) != '.' && g(i)(j) != '#') {
          q(g(i)(j) - '1').add(pos(i, j))
        }
      }
    }

    def canMove(n: Int, m: Int): Boolean = {
      n >= 0 && n < N && m >= 0 && m < M && g(n)(m) == '.'
    }

    val X = Array(-1, 1, 0, 0)
    val Y = Array(0, 0, -1, 1)

    /**
      * q(p)からはじめて、S(p)回移動して'.'を通っていける場所全部
      * 通ったところはp+1で塗りつぶす
      */
    def bfs(p: Int) {
      var s = S(p)

      while(s > 0 && q(p).nonEmpty) {
        val next = mutable.Set[Int]()
        q(p).foreach { x =>
          val n = x / M
          val m = x % M

          REP(4) { i =>
            val nn = n + X(i)
            val mm = m + Y(i)
            if (canMove(nn, mm)) {
              g(nn)(mm) = CHARS(p)
              next += pos(nn, mm)
            }
          }

        }
        q(p) = next
        s -= 1
      }
    }

    while (!q.forall(_.isEmpty)) {
      REP(P) { p =>
        bfs(p)
      }
    }

//    REP(N) { i =>
//      debug(g(i).mkString)
//    }

    val ans = Array.ofDim[Int](P)
    REP(N) { i =>
      REP(M) { j =>
        if (g(i)(j) != '.' && g(i)(j) != '#') {
          ans(g(i)(j) - '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)
  }

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


Allen is hosting a formal dinner party. $$$2n$$$ people come to the event in $$$n$$$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $$$2n$$$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$), the number of pairs of people. The second line contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$. For each $$$i$$$ with $$$1 \le i \le n$$$, $$$i$$$ appears exactly twice. If $$$a_j = a_k = i$$$, that means that the $$$j$$$-th and $$$k$$$-th people in the line form a couple.

Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.

NoteIn the first sample case, we can transform $$$1 1 2 3 3 2 4 4 \rightarrow 1 1 2 3 2 3 4 4 \rightarrow 1 1 2 2 3 3 4 4$$$ in two steps. Note that the sequence $$$1 1 2 3 3 2 4 4 \rightarrow 1 1 3 2 3 2 4 4 \rightarrow 1 1 3 3 2 2 4 4$$$ also works in the same number of steps.The second sample case already satisfies the constraints; therefore we need $$$0$$$ swaps.

import scala.collection.mutable._

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

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

import scala.io.StdIn

object D {

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

    val indices = 0 until pairs

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

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

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

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

    println(count)
  }

}


Optimizing the amount of data transmitted via a network is an important and interesting part of developing any network application.  In one secret game developed deep in the ZeptoLab company, the game universe consists of n levels, located in a circle. You can get from level i to levels i - 1 and i + 1, also you can get from level 1 to level n and vice versa. The map of the i-th level description size is ai bytes.In order to reduce the transmitted traffic, the game gets levels as follows. All the levels on the server are divided into m groups and each time a player finds himself on one of the levels of a certain group for the first time, the server sends all levels of the group to the game client as a single packet. Thus, when a player travels inside the levels of a single group, the application doesn't need any new information. Due to the technical limitations the packet can contain an arbitrary number of levels but their total size mustn't exceed b bytes, where b is some positive integer constant.Usual situation is that players finish levels one by one, that's why a decision was made to split n levels into m groups so that each group was a continuous segment containing multiple neighboring levels (also, the group can have two adjacent levels, n and 1). Specifically, if the descriptions of all levels have the total weight of at most b bytes, then they can all be united into one group to be sent in a single packet.Determine, what minimum number of groups do you need to make in order to organize the levels of the game observing the conditions above?As developing a game is a long process and technology never stagnates, it is yet impossible to predict exactly what value will take constant value b limiting the packet size when the game is out. That's why the developers ask you to find the answer for multiple values of b.

The first line contains two integers n, q (2 ≤ n ≤ 106, 1 ≤ q ≤ 50) — the number of levels in the game universe and the number of distinct values of b that you need to process. The second line contains n integers ai (1 ≤ ai ≤ 109) — the sizes of the levels in bytes. The next q lines contain integers bj (), determining the values of constant b, for which you need to determine the answer.

For each value of kj from the input print on a single line integer mj (1 ≤ mj ≤ n), determining the minimum number of groups to divide game levels into for transmission via network observing the given conditions.

NoteIn the test from the statement you can do in the following manner.  at b = 7 you can divide into two segments: 2|421|32 (note that one of the segments contains the fifth, sixth and first levels);  at b = 4 you can divide into four segments: 2|4|21|3|2;  at b = 6 you can divide into three segments: 24|21|32|.

object E 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) }

  val Array(n, q) = readInts(2)
  val as = readLongs(n)
  val rs = Array.ofDim[Int](n)
  val levels, last = Array.ofDim[Int](n + 1)
  levels(n) = 0
  last(n) = n

  for (p <- 0 until q) {

    val Array(b) = readLongs(1)

    var l, r = 0
    var lrSum = 0L
    while (r < n) {
      if (lrSum + as(r) <= b) {
        lrSum += as(r)
        r += 1
      } else {
        rs(l) = r
        lrSum -= as(l)
        l += 1
      }
    }

    while (l < n) {
      rs(l) = n
      l += 1
    }

    for (i <- n - 1 to 0 by -1) {
      if (rs(i) == n) {
        levels(i) = 0
        last(i) = i//n - 1
      } else {
        levels(i) = levels(rs(i)) + 1
        last(i) = if (levels(i) == 1) rs(i) else last(rs(i))
      }
    }

    l = 0
    var firstSum = 0L
    while (l < n && firstSum + as(l) <= b) {
      firstSum += as(l)
      l += 1
    }

    r = n - 1
    while (r > l && firstSum + as(r) <= b) {
      firstSum += as(r)
      r -= 1
    }
    r += 1

    var minLevelCount = Int.MaxValue

    while (l > 0) {

      var levelCount = levels(l) + 1
      if (last(l) < r) levelCount += 1

      if (levelCount < minLevelCount) minLevelCount = levelCount

      l -= 1
      if (l >= 0) {
        firstSum -= as(l)

        while (r - 1 > l && firstSum + as(r - 1) <= b) {
          r -= 1
          firstSum += as(r)
        }
      }
    }

    println(minLevelCount)
  }
}

import scala.collection._
import java.util.Arrays

object E 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, q) = readInts(2)
  val as = readLongs(n)
  val pSums = as.scan(0L)(_ + _)
  val total = pSums.last

  for (p <- 0 until q) {

    val Array(b) = readLongs(1)
    var bestStartSum = -1L
    var bestStart = 0
    var bestEnd = 0
    var start = 1

    while (start <= n && pSums(start) <= b) {
      val remain = b - pSums(start)
      val forEnd = total - remain
      val end0 = Arrays.binarySearch(pSums, forEnd)
      val end1 = if (end0 >= 0) end0 else -end0 - 1
      val end = end1 max start
      val startSum = pSums(start) + (total - pSums(end))
      if (startSum > bestStartSum) {
        bestStartSum = startSum
        bestStart = start
        bestEnd = end
        //println((bestStartSum, bestStart, bestEnd))
      }
      start += 1
    }

    var segments = 1
    var i = bestStart
    //println((bestStart, bestEnd))
    var currentSum = 0L
    while (i < bestEnd) {
      if (currentSum + as(i) > b) {
        segments += 1
        //println(i)
        if (i + 1 < bestEnd) {
          currentSum = as(i)
          i += 1
        } else currentSum = 0
      } else {
        currentSum += as(i)
        i += 1
      }
    }
    if (currentSum > 0L) segments += 1

    println(segments)
  }
}

import scala.collection._
import java.util.Arrays

object E 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, q) = readInts(2)
  val as = readLongs(n)
  val pSums = as.scan(0L)(_ + _)
  val total = pSums.last

  for (p <- 0 until q) {

    val Array(b) = readLongs(1)
    var bestStartSum = -1L
    var bestStart = 0
    var bestEnd = 0
    var start = 1

    while (start <= n && pSums(start) <= b) {
      val remain = b - pSums(start)
      val forEnd = total - remain
      val end0 = Arrays.binarySearch(pSums, forEnd)
      val end1 = if (end0 >= 0) end0 else -end0 - 1
      val end = end1 max (start + 1)
      val startSum = pSums(start) + (total - pSums(end))
      if (startSum > bestStartSum) {
        bestStartSum = startSum
        bestStart = start
        bestEnd = end
      }
      start += 1
    }

    var segments = 1
    var i = bestStart
    //println((bestStart, bestEnd))
    var currentSum = 0L
    while (i < bestEnd) {
      if (currentSum + as(i) > b) {
        segments += 1
        //println(i)
        if (i + 1 < bestEnd) {
          currentSum = as(i)
          i += 1
        } else currentSum = 0
      } else {
        currentSum += as(i)
        i += 1
      }
    }
    if (currentSum > 0) segments += 1

    println(segments)
  }
}

object E 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) }

  val Array(n, q) = readInts(2)
  val as = readLongs(n)
  val rs = Array.ofDim[Int](n)
  val levels, last = Array.ofDim[Int](n + 1)
  levels(n) = 0
  last(n) = n

  for (p <- 0 until q) {

    val Array(b) = readLongs(1)

    var l, r = 0
    var lrSum = 0L
    while (r < n) {
      if (lrSum + as(r) <= b) {
        lrSum += as(r)
        r += 1
      } else {
        rs(l) = r
        lrSum -= as(l)
        l += 1
      }
    }

    while (l < n) {
      rs(l) = n
      l += 1
    }

    for (i <- n - 1 to 0 by -1) {
      if (rs(i) == n) {
        levels(i) = 0
        last(i) = n
      } else {
        levels(i) = levels(rs(i)) + 1
        last(i) = if (levels(i) == 1) rs(i) else last(rs(i))
      }
    }

    l = 0
    var firstSum = 0L
    while (l < n && firstSum + as(l) <= b) {
      firstSum += as(l)
      l += 1
    }

    r = n - 1
    while (r > l && firstSum + as(r) <= b) {
      firstSum += as(r)
      r -= 1
    }
    r += 1

    var minLevelCount = Int.MaxValue

    while (l >= 0) {

      var levelCount = levels(l) + 1
      if (last(l) < r) levelCount += 1

      if (levelCount < minLevelCount) minLevelCount = levelCount

      l -= 1
      if (l >= 0) {
        firstSum -= as(l)

        while (r - 1 > l && firstSum + as(r - 1) <= b) {
          r -= 1
          firstSum += as(r)
        }
      }
    }

    println(minLevelCount)
  }
}

import scala.collection._
import java.util.Arrays

object E 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, q) = readInts(2)
  val as = readLongs(n)
  val pSums = as.scan(0L)(_ + _)
  val total = pSums.last

  for (p <- 0 until q) {

    val Array(b) = readInts(1)
    var bestStartSum = -1L
    var bestStart = 0
    var bestEnd = 0
    var start = 1

    while (start <= n && pSums(start) <= b) {
      val remain = b - pSums(start)
      val forEnd = total - remain
      val end0 = Arrays.binarySearch(pSums, forEnd)
      val end1 = if (end0 >= 0) end0 else -end0 - 1
      val end = end1 max (start + 1)
      val startSum = pSums(start) + (total - pSums(end))
      if (startSum > bestStartSum) {
        bestStartSum = startSum
        bestStart = start
        bestEnd = end
      }
      start += 1
    }

    var segments = 1
    var i = bestStart
    //println((bestStart, bestEnd))
    var currentSum = 0L
    while (i < bestEnd) {
      if (currentSum + as(i) > b) {
        segments += 1
        //println(i)
        if (i + 1 < bestEnd) {
          currentSum = as(i)
          i += 1
        } else currentSum = 0
      } else {
        currentSum += as(i)
        i += 1
      }
    }
    if (currentSum > 0) segments += 1

    println(segments)
  }
}


The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception.Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put ai coins to the i-th wallet from the left.Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row.Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.

The first line contains integer n (2 ≤ n ≤ 300) — the number of wallets. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 300). It is guaranteed that at least one ai is positive.

Print the sequence that consists of k (1 ≤ k ≤ 106) characters, each of them equals: "L", "R" or "P". Each character of the sequence is an instruction to the robot. Character "L" orders to move to the left, character "R" orders to move to the right, character "P" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions "L" if the robot is at wallet 1, or "R" at wallet n. As a result of the performed operations, the i-th wallet from the left must contain exactly ai coins. If there are multiple answers, you can print any of them.

import java.util.StringTokenizer

object _379B 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 ans = new StringBuilder

  def doit(i: Int): Unit = {
    if (i < n) {
      if (a(i) == 0) {
        if (i < n - 1) ans += 'R'
        doit(i + 1)
      }
      else {
        ans += 'P'
        a(i) -= 1
        if (a(i) == 0) {
          if (i < n - 1) ans += 'R'
          doit(i + 1)
        } else {
          if (i == 0) ans ++= "RL"
          else ans ++= "LR"
          doit(i)
        }
      }
    }
  }

  doit(0)
  println(ans.toString)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var left = data.sum
  var i = 0
  var result = List.empty[Char]
  var lbound = -1
  var took = false
  while (left != 0) {
    if (lbound == -1 && data(i) > 0)
      lbound = i
    if (data(i) > 0 && !took) {
      result ::= 'P'
      data(i) -= 1
      left -= 1
      took = true
      if (lbound == i && data(i) == 0)
        lbound = -1
    } else if (i != 0 && (lbound != -1 && lbound < i || i == n - 1)) {
      result ::= 'L'
      i -= 1
      took = false
    } else {
      result ::= 'R'
      i += 1
      took = false
    }
  }
  println(result.reverse.mkString)
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(" ").map(_.toInt).toList.toArray

    val sum = a.sum

    var cu = 0
    var p = 0

    var l = List.empty[Char]
    while (cu < sum) {
      if (a(p) == 0) {
        l = 'R' :: l
        p += 1
      } else if (p == a.length - 1) {
        l = 'R' :: 'L' :: 'P' :: l
        a(p) -= 1
        cu += 1
      } else if (p+1 < a.size && a(p+1) > 0 && a(p) > 1) {
        l = 'L' :: 'P' :: 'R' :: 'P' :: l
        cu += 2
        a(p) -= 1
        a(p+1) -= 1
      } else if (a(p) > 1) {
        l = 'L' :: 'R' :: 'P' :: l
        a(p) -= 1
        cu += 1
      } else {
        l = 'R' :: 'P' :: l
        a(p) -= 1
        cu += 1
        p += 1
      }
    }
    while (l.head != 'P') l = l.tail
    print(l.reverse.mkString)
  }
}

import scala.collection._

object B extends App {

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

  val n = readInt
  val as = readInts(n)
  val moves = Array.ofDim[Char](1000000)
  var m = 0

  var i = 0
  while (i < n) {
    if (as(i) > 0) {
      moves(m) = 'P'
      m += 1
      as(i) -= 1
    }
    moves(m) = if (i < n - 1) 'R' else 'L'
    m += 1
    if (as(i) > 0) {
      moves(m) = if (moves(m - 1) == 'R') 'L' else 'R'
      m += 1
    } else i += 1
  }

  println(moves.take(m).mkString)
}

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

object P379B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val A = List.fill(N)(sc.nextInt)

  def solve(): Unit = {
    val a0 = A.head
    out.print(List.fill(a0)("P").mkString("RL"))
    A.tail foreach { i =>
      out.print(List.fill(i)("P").mkString("R", "LR", ""))
    }
  }

  solve
  out.println
  out.close
}

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val a = readLine().split(" ").map(_.toInt)

    val len = a.size
    val reverse = "L" * (len - 1)
    val max = a.max
    for(i <- 1 to max) {
      for(j <- 0 until len - 1) {
        if(a(j) >= i) print("PR")
        else print("R")
      }
      if (a(len - 1) >= i) print("P")
      if (i != max) print(reverse)
    }
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-28.
 */
object B379 extends App{
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  var i = 0

  while (i < n) {
    val m = sc.nextInt()
    if (i < n - 1) {
      if (m == 0) {
        print('R')
      } else {
        print("P" + "RLP" * (m - 1) + "R")
      }
    } else {
      if (m != 0) {
        print("P" + "LRP" * (m - 1))
      }
    }

    i += 1
  }
}

import java.util.StringTokenizer

object _379B 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 ans = new StringBuilder

  def doit(i: Int): Unit = {
    if (i < n) {
      if (a(i) == 0) {
        if (i < n - 1) ans += 'R'
        ans += 'R'
        doit(i + 1)
      }
      else {
        ans += 'P'
        a(i) -= 1
        if (a(i) == 0) {
          if (i < n - 1) ans += 'R'
          doit(i + 1)
        } else {
          if (i == 0) ans ++= "RL"
          else ans ++= "LR"
          doit(i)
        }
      }
    }
  }

  doit(0)
  println(ans.toString)
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(" ").map(_.toInt).toList.toArray

    val sum = a.sum

    var cu = 0
    var p = 0

    var l = List.empty[Char]
    while (cu < sum) {
      if (a(p) == 0) {
        l = 'R' :: l
        p += 1
      } else if (p+1 < a.size && a(p+1) > 0 && a(p) > 1) {
        l = 'L' :: 'P' :: 'R' :: 'P' :: l
        cu += 2
        a(p) -= 1
        println(a.size + " " + p)
        a(p+1) -= 1
      } else if (a(p) > 1) {
        l = 'L' :: 'R' :: 'P' :: l
        a(p) -= 1
        cu += 1
      } else {
        l = 'R' :: 'P' :: l
        a(p) -= 1
        cu += 1
        p += 1
      }
    }
    print(l.reverse.mkString)
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()

    val n = input.next().toInt
    val a = input.next().split(" ").map(_.toInt).toList.toArray

    val sum = a.sum

    var cu = 0
    var p = 0

    var l = List.empty[Char]
    while (cu < sum) {
      if (a(p) == 0) {
        l = 'R' :: l
        p += 1
      } else if (p == a.length - 1) {
        l = 'R' :: 'L' :: 'P' :: l
        a(p) -= 1
        cu += 1
      } else if (p+1 < a.size && a(p+1) > 0 && a(p) > 1) {
        l = 'L' :: 'P' :: 'R' :: 'P' :: l
        cu += 2
        a(p) -= 1
        println(a.size + " " + p)
        a(p+1) -= 1
      } else if (a(p) > 1) {
        l = 'L' :: 'R' :: 'P' :: l
        a(p) -= 1
        cu += 1
      } else {
        l = 'R' :: 'P' :: l
        a(p) -= 1
        cu += 1
        p += 1
      }
    }
    while (l.head != 'P') l = l.tail
    print(l.reverse.mkString)
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-28.
 */
object B379 extends App{
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  var i = 0

  while (i < n) {
    val m = sc.nextInt()
    if (i < n - 1) {
      if (m == 0) {
        print('R')
      } else {
        print("P" + "RLP" * (m - 1) + "R")
      }
    } else {
      if (i != 0) {
        print("P" + "LRP" * (m - 1))
      }
    }

    i += 1
  }
}


You are given a sequence of positive integers x1, x2, ..., xn and two non-negative integers a and b. Your task is to transform a into b. To do that, you can perform the following moves:  subtract 1 from the current a;  subtract a mod xi (1 ≤ i ≤ n) from the current a. Operation a mod xi means taking the remainder after division of number a by number xi.Now you want to know the minimum number of moves needed to transform a into b.

The first line contains a single integer n (1 ≤  n ≤ 105). The second line contains n space-separated integers x1, x2, ..., xn (2 ≤  xi ≤ 109). The third line contains two integers a and b (0  ≤ b ≤  a ≤ 109, a - b ≤ 106).

Print a single integer — the required minimum number of moves needed to transform number a into number b.

import scala.collection._

object C extends App {

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

  val n = readString.toInt
  val xs = readInts(n).distinct.sorted.reverse
  var Array(a, b) = readInts(2)

  var steps = 0

  if (xs.head > a && b == 0 && a > b) {
    steps = 1
    a = 0
  }

  var start = 0

  while (a > b) {
    var maxMod = 1
    while (start < xs.size && a - a % xs(start) < b) start += 1
    var i = start
    while (i < xs.size && xs(i) > maxMod) {
      val mod = a % xs(i)
      if (mod > maxMod && a - mod >= b) maxMod = mod
      i += 1
    }
    a -= maxMod
    steps += 1
  }

  println(steps)
}


We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.

The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier.

Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't.

NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO".

object Main extends App {
  val bound = 1000010
  val primes = Array.ofDim[Boolean](bound)
  for {
    i <- 2 until bound
    if (!primes(i))
    j <- 2 * i until bound by i
  } primes(j) = true

  val n = readInt()
  val a = readLine().split(" ").map(_.toLong).map {
    case n if n < 3      => "NO"
    case n if n == 4     => "YES"
    case n if n % 2 == 0 => "NO"
    case n =>
      val sqrt = Math.round(Math.sqrt(n))
      if (sqrt * sqrt != n) "NO"
      else if (!primes(sqrt.toInt)) "YES"
      else "NO"
  }
  println(a.mkString("\n"))
}

import java.io.OutputStreamWriter
import java.io.BufferedWriter
import java.util.StringTokenizer

object _230B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val MAX = 1000001
  val isPrime = Array.fill(MAX)(true)
  isPrime(0) = false
  isPrime(1) = false

  {
    var i = 2
    while(i * i < MAX) {
      if (isPrime(i)) {
        var j = i + i
        while(j < MAX) {
          isPrime(j) = false
          j += i
        }
      }
      i += 1
    }
  }

  val primes = (0 until MAX).filter(i => isPrime(i))
  val cand = primes.map(i => i.toLong * i).toSet

  val cout = new BufferedWriter(new OutputStreamWriter(System.out))
  for (i <- 1 to next.toInt) {
    val x = next.toLong
    if (cand.contains(x)) cout.write("YES\n")
    else cout.write("NO\n")
  }

  cout.close
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val sieve = Array.ofDim[Boolean](1000001)
  (2 to 1000000).foreach { i =>
    if (!sieve(i)) {
      (i * 2 to 1000000 by i).foreach { j => sieve(j) = true }
    }
  }

  println(in.next().split(" ").map(_.toLong).map {
    case n if n < 3 => "NO"
    case n if n == 4 => "YES"
    case n if n % 2 == 0 => "NO"
    case n =>
      val sqrt = Math.round(Math.sqrt(n))

      if (sqrt * sqrt != n)
        "NO"
      else {
        if (!sieve(sqrt.toInt))
          "YES"
        else
          "NO"
      }

  }.mkString("\n"))

}

object Solution {
  import java.util.Scanner

  def main(args:Array[String]) {
    val it = new Iterator[Long] {
      private val sc = new Scanner(System.in)
      def hasNext = sc.hasNextLong
      def next = sc.nextLong
    }

    val tprimes = (new PrimeSet(1000000)).iterator.map(p => p.toLong * p).toSet

    val n = it.next
    it.take(n.toInt).foreach { x =>
      if (tprimes.contains(x))
        println("YES")
      else
        println("NO")
    }
  }
}

class PrimeSet(N:Int) extends Iterable[Int] {
  import java.util.BitSet

  private var sieved = 1
  private val flags = new BitSet()
  flags.set(2, N)

  private def square(n:Int) = BigInt(n).pow(2)

  def from(n:Int):Iterator[Int] = {
    if (n > sieved) from(sieved).dropWhile(n >)
    else new Iterator[Int] {
      private var p = flags.nextSetBit(n)
      def hasNext = p != -1
      def next = {
        val q = p
        if (q > sieved) {
          if (square(q) <= N) {
            (q * q to N by q).foreach(flags.clear(_))
            sieved = q
          } else {
            sieved = N
          }
        }
        p = flags.nextSetBit(p+1)
        q
      }
    }
  }

  def contains(n:Int) = {
    if (sieved < N && square(sieved) < n) {
      val sqrt = math.sqrt(n)
      from(sieved).dropWhile(sqrt >).next
    }
    flags.get(n)
  }

  def iterator = from(2)
}

object B230 {
  @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 isPrime(n: Long): Boolean = {
    var i = 2
    while(i*i <= n){
      if(n % i == 0) {
        return false
      }
      i += 1
    }
    true
  }

  def genPrimes(till: Int): Array[Boolean] = {
    val isPrime = Array.fill[Boolean](till+1)(true)
    isPrime(0) = false
    isPrime(1) = false // not composite
    for(i <- 4 to till by 2) {
      isPrime(i) = false
    }
    for(i <- 3 to till by 2 if isPrime(i)) {
      for(j <- i+i to till by i) isPrime(j) = false
    }
    isPrime
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val primes = genPrimes(1000000)
    val input = readLongs(n).map{ num =>
      val sqrt = math.sqrt(num)
      if(num != 1 && sqrt%1 == 0 && primes(sqrt.toInt)) true else false
    }
    println(input.map(x => if(x) "YES" else "NO").mkString("\n"))
  }
}

object B230 {
  @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 isPrime(n: Long): Boolean = {
    var i = 2
    while(i*i <= n){
      if(n % i == 0) {
        return false
      }
      i += 1
    }
    true
  }

  def genPrimes(till: Int): Set[Int] = {
    val isPrime = Array.fill[Boolean](till+1)(true)
    isPrime(0) = false
    isPrime(1) = false // not composite
    for(i <- 4 to till by 2) {
      isPrime(i) = false
    }
    for(i <- 3 to till by 2 if isPrime(i)) {
      for(j <- i+i to till by i) isPrime(j) = false
    }
    isPrime.zipWithIndex.filter(_._1).map(_._2).toSet
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val primes = genPrimes(1000000)
    val input = readLongs(n).map{ num =>
      val sqrt = math.sqrt(num)
      if(num != 1 && sqrt%1 == 0 && primes.contains(sqrt.toInt)) true else false
    }
    println(input.map(x => if(x) "YES" else "NO").mkString("\n"))
  }
}

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

object P230B extends App {

  object PrimeNumber {
    def apply(n: Int = 1000000): Array[Int] = sieve(n)

    def sieve(n: Int): Array[Int] = {
      val primes = new ArrayBuffer[Int]
      val isPrime = Array.fill(n + 1)(true)

      @tailrec
      def loop(i: Int): Unit = {

        @tailrec
        def innerLoop(j: Int): Unit = {
          if (j > n) ()
          else {
            isPrime(j) = false
            innerLoop(j + i)
          }
        }

        if (i > n) ()
        else {
          if (isPrime(i)) {
            primes += i
            innerLoop(i * 2)
          }
          loop(i + 1)
        }
      }

      loop(2)
      primes.toArray
    }
  }

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

  val tPrimes: Set[Long] = PrimeNumber(1000000).map(x => x.toLong * x.toLong).toSet
  for (_ <- 0 until sc.nextInt) {
    out.println(if (tPrimes(sc.nextLong)) "YES" else "NO") }

  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val max = 1000000
  val isPrime = Array.ofDim[Boolean](max).map(_ => true)
  var i = 2
  while(i < max) {
    if(isPrime(i)) {
      var j = i.toLong * i
      while(j < max) {
        isPrime(j.toInt) = false
        j += i
      }
    }
    i += 1
  }
  val squaredPrimes = (for(i <- 2 until max if isPrime(i)) yield i.toLong * i).toSet
  reader.readLine()
  def ans = readLongs.map(x => if(squaredPrimes.contains(x)) "YES" else "NO").mkString("\n")

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def sieve(n: Int) = {
    val primes = scala.collection.mutable.BitSet(2) ++ (3 to n by 2)
    for {
      cand <- 3 to Math.sqrt(n).toInt by 2
      if primes contains cand
    } primes --= (cand * cand to n by cand)
    primes
  }

  val primes = sieve(1000001).map{ i => i.toLong * i.toLong }

  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toLong)
    a.foreach{i =>
      if (primes contains i) println("YES")
      else println("NO")
    }
  }
}

import scala.math._
import scala.collection.immutable.TreeSet

object Olymp{
  def primes(N: Int): TreeSet[Int] = {
    var p = new Array[Boolean](N+1)
    for(i <- 2 to sqrt(N).round.toInt)
      if (!p(i)){
        for(j <- i*i to N by i)
          p(j) = true
      }
    var ret = new TreeSet[Int]
    for(i <- 2 to N)
      if (!p(i))
        ret = ret + i
    ret
  }
  def main(args: Array[String]): Unit = {
    val n = readLine toInt
    val p = readLine split (' ') map (_ toLong)
    val pr = primes(1000000)
    for (i <- p){
      if (i != 1 && abs(sqrt(i) - sqrt(i).round) < 1e-8 && pr.contains(sqrt(i).round.toInt)) println("YES")
      else println("NO")
    }
  }
}

import scala.io.StdIn._
import scala.language.postfixOps

object TaskA extends App {
   val n = readInt
   val list = readLine.split(" ").map(_.toLong)

  val max = 1e6 toInt
  val primes = Array.fill(max + 1)(true)
  primes(1) = false

  for(i <- 2 to 1000) {
    if (primes(i)) {
      var next = i * i
      while (next <= max) {
        primes(next) = false
        next += i
      }
    }
  }

  println(list.map(isTPrime)
    .map(b => if (b) "YES" else "NO")
    .mkString("\n"))

  def isTPrime(x: Long) = {
    val sqrt = math.sqrt(x).toLong
    sqrt * sqrt == x && primes(sqrt.toInt)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val sieve = Array.ofDim[Boolean](100001)
  (3 to 100000 by 2).foreach { i =>
    if (!sieve(i)) {
      (i to 100000 by i).foreach { j => sieve(j) = true }
    }
  }

  println(in.next().split(" ").map(_.toLong).map {
    case n if n < 3 => "NO"
    case n if n == 4 => "YES"
    case n if n % 2 == 0 => "NO"
    case n =>
      val sqrt = Math.sqrt(n).toLong
      if (sqrt * sqrt != n)
        "NO"
      else {
        val sqrtsqrt = Math.sqrt(sqrt).toInt
        if (!sieve(sqrtsqrt))
          "YES"
        else
          "NO"
      }

  }.mkString("\n"))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  in.next()
  println(in.next().split(" ").map(_.toLong).map {
    case n if n < 3 => "NO"
    case n if n == 4 => "YES"
    case n if n % 2 == 0 => "NO"
    case n =>
      val sqrt = Math.sqrt(n).toLong
      if (sqrt * sqrt != n)
        "NO"
      else {
        val sqrtsqrt = Math.sqrt(sqrt).toLong
        if ((3l until sqrtsqrt by 2).forall(n % _ != 0))
          "YES"
        else
          "NO"
      }

  }.mkString("\n"))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  in.next()
  println(in.next().split(" ").map(_.toLong).map {
    case n if n < 3 => "NO"
    case n if n == 4 => "YES"
    case n if n % 2 == 0 => "NO"
    case n =>
      val sqrt = Math.sqrt(n).toLong
      if (sqrt * sqrt != n)
        "NO"
      else {
        val sqrtsqrt = Math.sqrt(sqrt).toLong
        if (sqrtsqrt * sqrtsqrt == n && (3l until sqrtsqrt by 2).forall(n % _ != 0))
          "YES"
        else
          "NO"
      }

  }.mkString("\n"))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val sieve = Array.ofDim[Boolean](100001)
  sieve(1) = true
  sieve(3) = true
  (3 to 100000 by 2).foreach { i =>
    if (sieve(i)) {
      (i to 100000 by i).foreach { j => sieve(j) = true }
    }
  }

  println(in.next().split(" ").map(_.toLong).map {
    case n if n < 3 => "NO"
    case n if n == 4 => "YES"
    case n if n % 2 == 0 => "NO"
    case n =>
      val sqrt = Math.sqrt(n).toLong
      if (sqrt * sqrt != n)
        "NO"
      else {
        val sqrtsqrt = Math.sqrt(sqrt).toInt
        if (sieve(sqrtsqrt))
          "YES"
        else
          "NO"
      }

  }.mkString("\n"))

}

object B230 {
  @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 input = readLongs(n).map{ num => if(num != 1 && math.sqrt(num)%1 == 0) true else false}
    println(input.map(x => if(x) "YES" else "NO").mkString("\n"))
  }
}

object Main {
  def sieve(n: Long) = {
    val primes = scala.collection.mutable.BitSet(2) ++ (3L to n by 2)
    for {
      cand <- 3L to Math.sqrt(n).toLong by 2
      if primes contains cand
    } primes --= (cand * cand to n by cand)
    primes
  }

  val primes = sieve(1000000L)

  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toLong)
    a.foreach{i =>
      val sq = Math.sqrt(i).toInt
      if (sq * sq != i) println("NO")
      else if (primes contains sq) println("YES")
      else println("NO")
    }
  }
}

import scala.math._

object Olymp{
  def main(args: Array[String]): Unit = {
    val n = readLine toInt
    val p = readLine split (' ') map (_ toLong)
    for (i <- p){
      if (abs(sqrt(i) - sqrt(i).round) < 1e-8) println("YES")
      else println("NO")
    }
  }
}

import scala.math._

object Olymp{
  def main(args: Array[String]): Unit = {
    val n = readLine toInt
    val p = readLine split (' ') map (_ toLong)
    for (i <- p){
      if (i != 1 && abs(sqrt(i) - sqrt(i).round) < 1e-8) println("YES")
      else println("NO")
    }
  }
}

import scala.math._

object Olymp{
  def isPrime(n: Long) = (2 until sqrt(n).round.toInt) forall (n % _ != 0)
  def main(args: Array[String]): Unit = {
    val n = readLine toInt
    val p = readLine split (' ') map (_ toLong)
    for (i <- p){
      if (isPrime(i) && abs(sqrt(i) - sqrt(i).round) < 1e-8) println("YES")
      else println("NO")
    }
  }
}

import scala.io.StdIn._
import scala.language.postfixOps

object TaskA extends App {
   val n = readInt
   val list = readLine.split(" ").map(_.toLong)

  val max = 1e6 toInt
  val primes = Array.fill(max + 1)(true)
  primes(1) = false

  for(i <- 2 to 1000) {
    if (primes(i)) {
      var next = i * i
      while (next < max) {
        primes(next) = false
        next += i
      }
    }
  }

  println(list.map(isTPrime)
    .map(b => if (b) "YES" else "NO")
    .mkString("\n"))

  def isTPrime(x: Long) = {
    val sqrt = math.sqrt(x).toLong
    sqrt * sqrt == x && primes(sqrt.toInt)
  }
}

import scala.io.StdIn._
import scala.language.postfixOps

object TaskA extends App {
   val n = readInt
   val list = readLine.split(" ").map(_.toLong)

  val max = 1e6 toInt
  val primes = Array.fill(max + 1)(true)

  for(i <- 2 to 1000) {
    if (primes(i)) {
      var next = i * i
      while (next < max) {
        primes(next) = false
        next += i
      }
    }
  }

  list.map(isTPrime)
    .map(b => if (b) "YES" else "NO")
    .foreach(println)

  def isTPrime(x: Long) = {
    val sqrt = math.sqrt(x).toLong
    sqrt * sqrt == x && primes(sqrt.toInt)
  }
}