You are given an array $$$a_1, a_2, \dots, a_n$$$. You can perform operations on the array. In each operation you can choose an integer $$$i$$$ ($$$1 \le i < n$$$), and swap elements $$$a_i$$$ and $$$a_{i+1}$$$ of the array, if $$$a_i + a_{i+1}$$$ is odd.Determine whether it can be sorted in non-decreasing order using this operation any number of times.

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

For each test case, print "Yes" or "No" depending on whether you can or can not sort the given array. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).

NoteIn the first test case, we can simply swap $$$31$$$ and $$$14$$$ ($$$31 + 14 = 45$$$ which is odd) and obtain the non-decreasing array $$$[1,6,14,31]$$$.In the second test case, the only way we could sort the array is by swapping $$$4$$$ and $$$2$$$, but this is impossible, since their sum $$$4 + 2 = 6$$$ is even.In the third test case, there is no way to make the array non-decreasing.In the fourth test case, the array is already non-decreasing.

import sun.management.counter.Counter

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

object Solution extends App {

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

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

  val testNumber = lines.next().toInt
  1.to(testNumber).foreach { _ =>
    val size = lines.next().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(lines.next(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

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

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

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

import sun.management.counter.Counter

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

object Solution extends App {

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

  val reader = new BufferedReader(new InputStreamReader(System.in))
  val writer = new BufferedWriter(new OutputStreamWriter(System.out))

  val testNumber = reader.readLine().toInt
  1.to(testNumber).foreach { _ =>
    val size = reader.readLine().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(reader.readLine(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

    val answer = if (findAnswer(0, -1, -1)) "YES" else "NO"
    writer.append(answer)
    writer.append("\n")
  }
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

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

  val reader = new BufferedReader(new InputStreamReader(System.in))
  val writer = new BufferedWriter(new OutputStreamWriter(System.out))

  val testNumber = reader.readLine().toInt
  1.to(testNumber).foreach { _ =>
    val size = reader.readLine().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(reader.readLine(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

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

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

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

import sun.management.counter.Counter

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

object Solution extends App {

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

  import java.nio.channels.Channels

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

  val testNumber = reader.readLine().toInt
  1.to(testNumber).foreach { _ =>
    val size = reader.readLine().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(reader.readLine(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

    val answer = if (findAnswer(0, -1, -1)) "YES" else "NO"
    writer.println(answer)
  }
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

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

  import java.nio.channels.Channels

  val buffer = java.nio.ByteBuffer.allocate(4096000)
  val channel = Channels.newChannel(System.in)
  channel.read(buffer)
  val inputTokenizer = new StringTokenizer(new String(buffer.array),"\r\n\0")

  val writer = new PrintWriter(System.out)

  val testNumber = inputTokenizer.nextToken().toInt
  1.to(testNumber).foreach { _ =>
    val size = inputTokenizer.nextToken().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(inputTokenizer.nextToken(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

    val answer = if (findAnswer(0, -1, -1)) "YES" else "NO"
    writer.println(answer)
  }
  channel.close()
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

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

  import java.nio.channels.Channels

  val buffer = java.nio.ByteBuffer.allocate(10240000)
  val channel = Channels.newChannel(System.in)
  channel.read(buffer)
  val inputTokenizer = new StringTokenizer(new String(buffer.array),"\r\n\0")

  val writer = new PrintWriter(System.out)

  val testNumber = inputTokenizer.nextToken().toInt
  1.to(testNumber).foreach { _ =>
    val size = inputTokenizer.nextToken().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(inputTokenizer.nextToken(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

    val answer = if (findAnswer(0, -1, -1)) "YES" else "NO"
    writer.println(answer)
  }
  channel.close()
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

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

  import java.nio.channels.Channels

  val buffer = java.nio.ByteBuffer.allocate(20480000)
  val channel = Channels.newChannel(System.in)
  channel.read(buffer)
  val inputTokenizer = new StringTokenizer(new String(buffer.array),"\r\n\0")

  val writer = new PrintWriter(System.out)

  val testNumber = inputTokenizer.nextToken().toInt
  1.to(testNumber).foreach { _ =>
    val size = inputTokenizer.nextToken().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(inputTokenizer.nextToken(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

    val answer = if (findAnswer(0, -1, -1)) "YES" else "NO"
    writer.println(answer)
  }
  channel.close()
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

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

  import java.nio.channels.Channels

  val buffer = java.nio.ByteBuffer.allocate(40960000)
  val channel = Channels.newChannel(System.in)
  channel.read(buffer)
  val inputTokenizer = new StringTokenizer(new String(buffer.array),"\r\n\0")

  val writer = new PrintWriter(System.out)

  val testNumber = inputTokenizer.nextToken().toInt
  1.to(testNumber).foreach { _ =>
    val size = inputTokenizer.nextToken().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(inputTokenizer.nextToken(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

    val answer = if (findAnswer(0, -1, -1)) "YES" else "NO"
    writer.println(answer)
  }
  channel.close()
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val reader = new BufferedReader(new InputStreamReader(System.in))
  val writer = new PrintWriter(System.out)

  val testNumber = reader.readLine().toInt
  1.to(testNumber).foreach { _ =>
    val size = reader.readLine().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(reader.readLine(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Int, previousOdd: Int): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven == -1 || previousEven <= a(index))
            findAnswer(index + 1, a(index), previousOdd) else false
          case 1 => if (previousOdd == -1 || previousOdd <= a(index))
            findAnswer(index + 1, previousEven, a(index)) else false
        }
      }

    val answer = if (findAnswer(0, -1, -1)) "YES" else "NO"
    writer.println(answer)
  }
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val reader = new BufferedReader(new InputStreamReader(System.in))
  val writer = new PrintWriter(System.out)

  val testNumber = reader.readLine().toInt
  1.to(testNumber).foreach { _ =>
    val size = reader.readLine().toInt
    val a = new Array[Int](size);
    {
      val tokenizer = new StringTokenizer(reader.readLine(), " ")
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    @tailrec
    def findAnswer(index: Int, previousEven: Option[Int], previousOdd: Option[Int]): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven.isEmpty || previousEven.get <= a(index))
            findAnswer(index + 1, Some(a(index)), previousOdd) else false
          case 1 => if (previousOdd.isEmpty || previousOdd.get <= a(index))
            findAnswer(index + 1, previousEven, Some(a(index))) else false
        }
      }

    val answer = if (findAnswer(0, None, None)) "YES" else "NO"
    writer.println(answer)
  }
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val writer = new PrintWriter(System.out)

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val size = readInt()
    val a = readInts()

    @tailrec
    def findAnswer(index: Int, previousEven: Option[Int], previousOdd: Option[Int]): Boolean =
      if (index == size) true else {
        a(index) % 2 match {
          case 0 => if (previousEven.isEmpty || previousEven.get <= a(index))
            findAnswer(index + 1, Some(a(index)), previousOdd) else false
          case 1 => if (previousOdd.isEmpty || previousOdd.get <= a(index))
            findAnswer(index + 1, previousEven, Some(a(index))) else false
        }
      }

    val answer = if (findAnswer(0, None, None)) "YES" else "NO"
    writer.println(answer)
  }
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val reader = new BufferedReader(new InputStreamReader(System.in))
  val writer = new PrintWriter(System.out)

  val testNumber = reader.readLine().toInt
  var testIndex = 0
  while( testIndex < testNumber) {
    testIndex += 1

    val size = reader.readLine().toInt
    val tokenizer = new StringTokenizer(reader.readLine(), " ")
    val a = new Array[Int](size);
    {
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    var index: Int = 0
    var previousEven: Int = -1
    var previousOdd: Int = -1
    var answer = "YES"
    while (index < size) {
      a(index) % 2 match {
        case 0 => if (previousEven == -1 || previousEven <= a(index)) {
          previousEven = a(index)
          index = index + 1
        } else {
          answer = "NO"
          index = size + 100
        }
        case 1 => if (previousOdd == -1 || previousOdd <= a(index)) {
          previousOdd = a(index)
          index = index + 1
        } else {
          answer = "NO"
          index = size + 100
        }
      }
    }

    writer.println(answer)
  }
  writer.close()

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val reader = new BufferedReader(new InputStreamReader(System.in))

  val testNumber = reader.readLine().toInt
  var testIndex = 0
  while( testIndex < testNumber) {
    testIndex += 1

    val size = reader.readLine().toInt
    val tokenizer = new StringTokenizer(reader.readLine(), " ")
    val a = new Array[Int](size);
    {
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    var index: Int = 0
    var previousEven: Int = -1
    var previousOdd: Int = -1
    var answer = "YES"
    while (index < size) {
      a(index) % 2 match {
        case 0 => if (previousEven == -1 || previousEven <= a(index)) {
          previousEven = a(index)
          index = index + 1
        } else {
          answer = "NO"
          index = size + 100
        }
        case 1 => if (previousOdd == -1 || previousOdd <= a(index)) {
          previousOdd = a(index)
          index = index + 1
        } else {
          answer = "NO"
          index = size + 100
        }
      }
    }

    System.out.println(answer)
  }

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val reader = new BufferedReader(new InputStreamReader(System.in))

  val testNumber = reader.readLine().toInt
  1.to(testNumber).foreach { _ =>
    val size = reader.readLine().toInt
    val tokenizer = new StringTokenizer(reader.readLine(), " ")
    val a = new Array[Int](size);
    {
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    var index: Int = 0
    var previousEven: Int = -1
    var previousOdd: Int = -1
    var answer = "YES"
    while (index < size) {
      a(index) % 2 match {
        case 0 => if (previousEven == -1 || previousEven <= a(index)) {
          previousEven = a(index)
          index = index + 1
        } else {
          answer = "NO"
          index = size + 100
        }
        case 1 => if (previousOdd == -1 || previousOdd <= a(index)) {
          previousOdd = a(index)
          index = index + 1
        } else {
          answer = "NO"
          index = size + 100
        }
      }
    }

    System.out.println(answer)
  }

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

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

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ListBuffer
import scala.io.Source
import scala.util.control.Breaks

object Main extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val res = new ArrayBuffer[String](t)
  for (i <- 0 until t) {
    input.next()
    val ch = new ListBuffer[Int]()
    val nch = new ListBuffer[Int]()
    input.next().split(' ').foreach(x => {
      val i = x.toInt
      if (i % 2 == 0) ch.append(i)
      else nch.append(i)
    })

    if (check(ch.toList) && check(nch.toList)) {
      res.append("YES")
    } else res.append("NO")
  }

  def check(arr: List[Int]): Boolean = {
    if (arr.isEmpty) true
    else {
      var res = true
      var max = arr.head
      Breaks.breakable {
        for (el <- arr.tail) {
          if (max > el) {
            res = false
            Breaks.break()
          } else max = el
        }
      }
      res
    }
  }

  println(res.mkString("\n"))
}

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val reader = new BufferedReader(new InputStreamReader(System.in))
  val writer = new PrintWriter(System.out);

  val testNumber = reader.readLine().toInt
  var testIndex = 0
  while( testIndex < testNumber) {
    testIndex += 1

    val size = reader.readLine().toInt
    val tokenizer = new StringTokenizer(reader.readLine(), " ")
    val a = new Array[Int](size);
    {
      var i = 0
      while (i < size) {
        a(i) = Integer.parseInt(tokenizer.nextToken())
        i += 1
      }
    }

    var index: Int = 0
    var previousEven: Int = -1
    var previousOdd: Int = -1
    var answer = "YES"
    while (index < size) {
      a(index) % 2 match {
        case 0 => if (previousEven == -1 || previousEven <= a(index)) {
          previousEven = a(index)
          index = index + 1
        } else {
          answer = "NO"
          index = size + 100
        }
        case 1 => if (previousOdd == -1 || previousOdd <= a(index)) {
          previousOdd = a(index)
          index = index + 1
        } else {
          answer = "NO"
          index = size + 100
        }
      }
    }

    writer.println(answer)
  }

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

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


Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li], a[li + 1], ..., a[ri].Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.The mex of a set S is a minimum possible non-negative integer that is not in S.

The first line contains two integers n and m (1 ≤ n, m ≤ 105). The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), that describe the subarray a[li], a[li + 1], ..., a[ri].

In the first line print single integer — the maximum possible minimum mex. In the second line print n integers — the array a. All the elements in a should be between 0 and 109. It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109. If there are multiple solutions, print any of them.

NoteThe first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val minLength = in.take(m).map(_.split(' ').map(_.toInt)).map(i => i.last - i.head).min + 1

  println(minLength)
  println((0 until n).map(i => i % minLength).mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val answer = Array.fill[Int](n){ -1 }
  val input = in.take(m).map(_.split(' ').map(_.toInt - 1)).toArray.sortBy(i => (i.last - i.head, i.head))

  var i = 0
  var stop = false
  var min = 0
  var max = Int.MaxValue
  while (i < input.length && !stop) {
    val Array(a, b) = input(i)
    val set = (a to b).map(answer).toSet
    min = set.min
    (a to b).foreach {
      i => if (answer(i) == -1) {
        min += 1
        while (set.contains(min))
          min += 1
        answer(i) = min
      }
    }
    if (min == set.min) {
      min = (0 to n).find(i => !set.contains(i)).get - 1
    }

    max = Math.min(min, max)
    stop = min != (b - a)

    i += 1
  }

  println(min)
  println(answer.map(i => if (i == -1) 0 else i).mkString(" "))

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val answer = Array.fill[Int](n){ -1 }
  val input = in.take(m).map(_.split(' ').map(_.toInt - 1)).toArray.sortBy(i => (i.last - i.head, i.head))

  var i = 0
  var stop = false
  var min = 0
  var max = Int.MaxValue
  while (i < input.length && !stop) {
    val Array(a, b) = input(i)
    val set = (a to b).map(answer).toSet
    min = set.min
    (a to b).foreach {
      i => if (answer(i) == -1) {
        min += 1
        while (set.contains(min))
          min += 1
        answer(i) = min
      }
    }
    if (min == set.min) {
      val x = (0 to (b - a)).find(i => !set.contains(i))
      if (x.nonEmpty)
        max = Math.min(x.get, max)
    } else {
      max = Math.min(min + 1, max)
    }

    stop = min != (b - a)

    i += 1
  }

  println(max)
  println(answer.map(i => if (i == -1) 0 else i).mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val answer = Array.fill[Int](n){ -1 }
  val input = in.take(m).map(_.split(' ').map(_.toInt - 1)).toArray.sortBy(i => (i.last - i.head, i.head))

  var i = 0
  var stop = false
  var min = 0
  var max = Int.MaxValue
  while (i < input.length && !stop) {
    val Array(a, b) = input(i)
    var set = (a to b).map(answer).toSet
    min = set.min
    (a to b).foreach {
      i => if (answer(i) == -1) {
        while (set.contains(min))
          min += 1
        answer(i) = min
        set += min
      }
    }
    val x = (0 to (b - a)).find(i => !set.contains(i))
    if (x.nonEmpty) {
      max = Math.min(x.get, max)
      stop = true
    }
    else
      max = Math.min(b - a + 1, max)

    i += 1
  }

  println(max)
  println(answer.map(i => if (i == -1) 0 else i).mkString(" "))
}


You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) — the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).

For each test case, print the answer — the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.

//package codeforces.contests._1353

/*
https://codeforces.com/contest/1353/problem/E

[Dynamic Programming]

dp(i) = cost of putting a 1 at ith index and afterwards
      = (cost of putting a 1 at ith index) + costZeroing(i + 1, i + k - 1) + (costOne(i + k) min costZeroing(i + k, n - 1))

final result will be min of (checking each sequence by putting 1 at each i or none at all)
 */
object KPeriodicGarland {
  def main(args: Array[String]): Unit = {
    println {
      {
        for (_ <- 1 to io.StdIn.readInt) yield {
          val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)
          val input = io.StdIn.readLine.map(_ - '0')

          val prefixSum = input.scanLeft(0)(_ + _)

          val dp = new Array[Int](n) // cost of putting a 1 at ith index

          def costOne(i: Int): Int = // cost of putting a 1 at ith index
            if (i >= n) 0 else dp(i)

          def costZeroing(l: Int, r: Int): Int = // cost of zeroing between l and r
            if (l >= n || l > r) 0 else prefixSum(n min (r + 1)) - prefixSum(l)

          for (i <- n - 1 to 0 by -1)
            dp(i) = (1 ^ input(i)) + costZeroing(i + 1, i + k - 1) + (costOne(i + k) min costZeroing(i + k, n - 1))

          val i = (0 until n).minBy(i => dp(i) + costZeroing(0, i - 1))
          (dp(i) + costZeroing(0, i - 1)) min costZeroing(0, n - 1)
        }
      }.mkString("\n")
    }
  }
}


You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai, bi). How many operations will be performed for each of them?

The first line contains the number of pairs n (1  ≤  n  ≤  1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1  ≤  ai,  bi  ≤  109).

Print the sought number of operations for each pair on a single line.

import java.util.Scanner

object Substr {

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

    val src = new Scanner(System.in)
    val n = src.nextInt()
    for (i <- 1 to n) {
      println(sub(src.nextInt(), src.nextInt()))
    }
    src.close()
  }

  def sub(a: Int, b: Int) = {
    def iter(a: Int, b: Int, k: Int): Int = {
      if (a < 1 || b < 1) k
      else if (a > b) iter(a % b, b, k + a / b)
      else if (a < b) iter(a, b % a, k + b / a)
      else if (a == b) k + 1
      else k
    }
    iter(a, b, 0)
  }
}

import scala.io.Source

object Hello {

  def computeCount(a: Int, b: Int): Int = { // a > b
    if (b == 0) return 0

    a/b + computeCount(b, a%b)
  }

  def main(args: Array[String]) {
    val lineIter = Source.stdin.getLines
    lineIter.next
    while (lineIter.hasNext)
    {
      var Array(ele1, ele2) = lineIter.next.split(" ").map(_.toInt)
      if (ele1 > ele2) {
        var ele = ele1
        ele1 = ele2
        ele2 = ele
      }
      println(computeCount(ele2, ele1))
    }
  }

}

// codeforces 267A
object Vichitania extends App {
  var ss = (Console.readLine.split(" ")) map (_.toInt)
  val n = ss(0)

  def countVich(a: Int, b: Int): Int =
    if (a < b) countVich(b, a)
    else if (b == 0) 0
    else {
      val d = a / b
      val o = a % b
      d + countVich(b, o)
    }

  for (i <- 0 until n) {
    ss = (Console.readLine.split(" ")) map (_.toInt)
    val a = ss(0)
    val b = ss(1)
    val cnt = countVich(a, b)
    println(cnt)
  }
}

import java.util.StringTokenizer

object A {
  var tokenizer = new StringTokenizer("");

  def nextToken(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(readLine);
    }
    tokenizer.nextToken();
  }

  def nextInt: Int = {
    nextToken().toInt;
  }

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

  def main(args: Array[String]) {
    val n = nextInt;
    for (i <- 1 to n) {
      println(gcd(nextInt, nextInt))
    }
  }
}

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

    val n =readLine.toInt

    (0 until n).foreach{i=>

      val sp=readLine.split(" ")

      println(
        count(sp(0).toInt,sp(1).toInt))

      def count(a:Int,b:Int):Int={
        if(b<a){
          count(b,a)
        }else if(a==0){
          0
        }else{
          val c:Int =b/a
          b/a + count(b%a,a)
        }
      }
    }
  }
}

import java.util.StringTokenizer

object A {
  var tokenizer = new StringTokenizer("");

  def nextToken(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(readLine);
    }
    tokenizer.nextToken();
  }

  def nextInt: Int = {
    nextToken().toInt;
  }

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

  def main(args: Array[String]) {
    val n = nextInt;
    for (i <- 1 to n) {
      print(gcd(nextInt, nextInt))
    }
  }
}


You are given an array consisting of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Initially $$$a_x = 1$$$, all other elements are equal to $$$0$$$.You have to perform $$$m$$$ operations. During the $$$i$$$-th operation, you choose two indices $$$c$$$ and $$$d$$$ such that $$$l_i \le c, d \le r_i$$$, and swap $$$a_c$$$ and $$$a_d$$$.Calculate the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the description of $$$t$$$ testcases follow. The first line of each test case contains three integers $$$n$$$, $$$x$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$). Each of next $$$m$$$ lines contains the descriptions of the operations; the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).

For each test case print one integer — the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

NoteIn the first test case, it is possible to achieve $$$a_k = 1$$$ for every $$$k$$$. To do so, you may use the following operations:  swap $$$a_k$$$ and $$$a_4$$$;  swap $$$a_2$$$ and $$$a_2$$$;  swap $$$a_5$$$ and $$$a_5$$$. In the second test case, only $$$k = 1$$$ and $$$k = 2$$$ are possible answers. To achieve $$$a_1 = 1$$$, you have to swap $$$a_1$$$ and $$$a_1$$$ during the second operation. To achieve $$$a_2 = 1$$$, you have to swap $$$a_1$$$ and $$$a_2$$$ during the second operation.

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nxm = readIntLine()
      val operations = (1 to nxm.last).map(_ => readIntLine()).toList
      println(calc(nxm(1), nxm(1) + 1, operations))
    }
  }

  def calc(l: Int, r: Int, operations: List[List[Int]]): Int = operations match {
    case Nil => r - l
    case op :: ops =>
      calc(if (op.last >= l) math.min(l, op.head) else l, if (op.head + 1 <= r) math.max(op.last + 1, r) else r, ops)
  }

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

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

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

}

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

  (0 until t).foreach { _ =>
    val Array(n, x, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val (l, r) = (0 until m).foldLeft((x, x)) {
      case ((l, r), i) =>
        val Array(li, ri) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        if (l <= ri && r >= li) (l min li, r max ri)
        else (l, r)
    }

    val ans = r - l + 1

    println(ans)
  }
}


Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.

Output the minimum length of the string that may remain after applying the described operations several times.

NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: .

object Program{
	def main(ins:Array[String]){
		val n = readInt()
		val s = readLine()
		val a = s.partition(_ == '1')
		def ln(x:String)= x.length
		def check() =
		if (ln(a._1) > ln(a._2)) ln(a._1) - ln(a._2)
			else ln(a._2) - ln(a._1)
		println(check())
	}
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream

import scala.util.Random

object CF556A {

  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]): Unit = {
    val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
    var in = new InputReader(System.in)
    var out = System.out
    if ( !isOnlineJudge ) {
      in = new InputReader(new FileInputStream("input.txt"))
      out = new PrintStream(new FileOutputStream("output.txt"))
    }
    solve(in,out)
  }

  def solve(in: InputReader, out: PrintStream) = {
    //Solution goes here
    in.nextInt();
    val s = in.next()
    val ch = s.toCharArray
    val cnt0 = ch.foldLeft(0)((cnt,c) => if (c=='0') cnt+1 else cnt )
    val cnt1 = ch.foldLeft(0)((cnt,c) => if (c=='1') cnt+1 else cnt )
    out.println(s.length - Math.min(cnt0,cnt1) * 2)
  }

}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream

import scala.util.Random

object CF556A {

  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]): Unit = {
    val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
    var in = new InputReader(System.in)
    var out = System.out
    if ( !isOnlineJudge ) {
      in = new InputReader(new FileInputStream("input.txt"))
      out = new PrintStream(new FileOutputStream("output.txt"))
    }
    solve(in,out)
  }

  def solve(in: InputReader, out: PrintStream) = {
    //Solution goes here
    in.nextInt();
    val s: String = in.next()
    val (z,o) = s.toCharArray.foldLeft((0,0))((p,c) => if (c=='0') (p._1+1,p._2) else (p._1,p._2+1))
    out.println(s.length - Math.min(z,o) * 2)
  }

}

object A556 {
  @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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = scala.io.StdIn.readLine.count(_ == '0')
    println(n - 2*math.min(n-input, input))
  }
}

object _556A extends CodeForcesApp {
  import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable

  override type Input = String
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    nextInt
    next
  }

  override def solve(input: Input) = {
    var s = List.empty[Boolean]
    for {
      c <- input
      i = c == '0'
    } {
      s = (i, s) match {
        case (x, y :: ys) if x != y => ys
        case _ => i :: s
      }
    }

    s.length
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  import CodeForcesApp._
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
/********************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
}
/**********************************[ lib ]************************************/
object CodeForcesApp {
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = collection.mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type ==>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None
/*******************************[ constants ]*********************************/
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
}

import scala.io.StdIn

object CaseOfTheZerosAndOnes {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val bits = StdIn.readLine()
    val (zeros, ones) = bits.foldLeft((0, 0)) { case ((zeros, ones), bit) =>
      if (bit == '0') (zeros + 1, ones)
      else if (bit == '1') (zeros, ones + 1)
      else (zeros, ones)
    }
    println(Math.abs(zeros - ones))
  }
}

import java.io.BufferedInputStream
import java.io.BufferedReader
import java.io.InputStreamReader

object A_Zeros_Ones {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val n = Integer.parseInt(br.readLine().trim());
//    val line = br.readLine()

    var counter = 0
    for (i <- 0 until n) {
      if (br.read().toChar == '1') counter += 1
      else counter -= 1
    }

    println(Math.abs(counter))
  }
}

object WaterMelon{
	def main(args : Array[String]){
		var a = readInt()
		if ( a > 2 && a % 2 == 0){
			println("YES")
		}	else{
			println("NO")
		}
	}
}


Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by hk - hk + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers h1, h2, ..., hn (1  ≤  hi  ≤  105) representing the heights of the pylons.

Print a single number representing the minimum number of dollars paid by Caisa.

NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.

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

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val hs = Array.fill(n + 1)(0L)
    for(i <- 1 to n) {
      hs(i) = nextLong
    }
    var min = 0L
    var e = 0L
    for(i <- 1 to n) {
      if(e + hs(i - 1) - hs(i) >= 0) {
         e += hs(i - 1) - hs(i)
      } else {
        min += -(hs(i - 1) - hs(i) + e)
        e = 0L
      }
    }
    out.print(min)
  }

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

import java.util.StringTokenizer

object _463 extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  println((1 to n).map(i => next.toInt).max)
}

  object Solution extends App {
    val in = scala.io.Source.stdin.getLines()
    val n = in.next()
    println(in.next().split(" ").map(_.toInt).max)
  }

object B463 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val h = readInts(n)
    var res = 0L
    var ret = h(0).toLong
    for(i <- 0 until n-1) {
      res += h(i) - h(i+1)
      if(res < 0) {
        ret += -res
        res = 0
      }
    }
    println(ret)
  }

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

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

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

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

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

}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-28.
 */
object B463 extends App{
  val sc = new Scanner(System.in)
  var n = sc.nextInt()
  var pay: Long = 0
  var curH = 0
  var e = 0

  while (n >= 1) {
    n -= 1
    val nextH = sc.nextInt()
    val decE = nextH - curH

    if (decE > e) {
      pay += nextH - curH - e
      e = 0
    } else {
      e -= decE
    }

    curH = nextH
  }

  println(pay)
}

  object Solution extends App {
    val in = scala.io.Source.stdin.getLines()
    val n = in.next()
    println(in.next().split(" ").max)
  }

object B463 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val h = readInts(n)
    var res = 0L-h(0)
    var ret = 0L
    for(i <- 0 until n-1) {
      res += h(i) - h(i+1)
      if(res < 0) {
        ret += -res
        res = 0
      }
    }
    println(ret)
  }

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

}


This problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string $$$s$$$ of length $$$n$$$, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of $$$s[l..r]$$$. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than $$$3$$$ queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed $$$(n+1)^2$$$.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.

First line contains number $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the picked string.

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Map

object Main extends App {
  val n = readInt()

  if (n < 2) {
    println("? 1 1"); Console.flush
    val c = readLine.trim.head
    println(f"! $c")

  } else {

    println(f"? 1 $n"); Console.flush
    val ssButOne = collection.mutable.Map[String, Int]()
    (1 to (n * (n + 1) / 2))
      .map(_ => readLine.trim.sorted)
      .foreach(s => ssButOne(s) = ssButOne.getOrElse(s, 0) + 1)

    println(f"? 1 ${n - 1}"); Console.flush
    (1 to (n * (n - 1) / 2))
      .map(_ => readLine.trim.sorted)
      .foreach(s =>
        ssButOne.getOrElse(s, -1) match {
          case 1    => ssButOne -= s
          case -1   => {}
          case _ @x => ssButOne(s) = x - 1
        }
      )

    val remains = ssButOne.keySet.toList.sortBy(_.length)
    /* remains.foreach(x => println(f"($x)")) */

    def extraChar(cArr: List[Char], s: String): Char = {
      if (cArr.isEmpty || s.length == 1) {
        /* println("<" + s + ">") */
        s(0)
      } else {
        val i = s.indexOf(cArr.head)
        val (pA, pB) = s.splitAt(i)
        extraChar(cArr.tail, pA ++ pB.tail)
      }
    }

    val hack = remains
      .foldLeft(List[Char]())((z, s) => {
        /* println("[" + z.mkString + "]") */
        extraChar(z, s) :: z
      })
      .mkString
    println(f"! $hack")
  }
}

/* aabc */
/*
xyz
yz
xy
z
x
y
zy
z
y
 */

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer

object Main extends App {
  val n = readInt()

  /* query the first */
  println("? 1 1")
  Console.flush
  val cHead = readLine.trim.head

  if (n < 2) {
    println(f"! $cHead")

  } else {

    /* query all... */
    println(f"? 1 $n")
    Console.flush

    var substr2 = ArrayBuffer[String]()
    var substrN = ""
    (1 to (n * (n + 1) / 2))
      .map(_ => readLine.trim)
      .foreach(x => {
        if (x.length == 2) substr2 += x
        if (x.length == n) substrN = x
      })

    /* println(f"substr2: $substr2, substrN: $substrN") */

    val edges = ArrayBuffer.fill(n) { ArrayBuffer[Int]() }

    def foreachUntil(
        arr: String,
        f: (Char, Int) => Boolean,
        idx: Int = 0
    ): Unit =
      if (!f(arr.head, idx))
        foreachUntil(arr.tail, f, idx + 1)

    substr2.foreach(x => {
      val (cA, cB) = (x(0), x(1))
      var iA, iB = -1
      foreachUntil(substrN, (c, i) => {
        if (iA == -1 && c == cA && edges(i).length < 2) {
          iA = i
        } else if (iB == -1 && c == cB && edges(i).length < 2) {
          iB = i
        }
        if (iA != -1 && iB != -1) true
        else false
      })
      edges(iA) += iB
      edges(iB) += iA
    })

    /* edges.foreach(x => {
    x.foreach(c => print(c.toString + " "))
    println
  }) */

    def printHack(curHead: Int): Unit =
      if (edges(curHead).isEmpty) {
        println(substrN(curHead))
      } else {
        print(substrN(curHead))
        val neighbor = edges(curHead)(0)
        edges(curHead).clear
        edges(neighbor) -= curHead
        printHack(neighbor)
      }

    var iHead = -1
    foreachUntil(
      substrN,
      (c, i) =>
        if (c == cHead && edges(i).length == 1) {
          iHead = i
          true
        } else false
    )
    /* println(f"iHead: $iHead") */

    print("! ")
    printHack(iHead)
    Console.flush
  }
}

/* aabc */
/*
cb
caba
a
cab
ba
a
aba
c
aa
b
 */

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Map

object Main extends App {
  val n = readInt()

  if (n < 2) {
    println("? 1 1"); Console.flush
    val c = readLine.trim.head
    println(f"! $c")

  } else {

    println(f"? 1 $n"); Console.flush
    val ssButOne = collection.mutable.Map[String, Int]()
    (1 to (n * (n + 1) / 2))
      .map(_ => readLine.trim)
      .foreach(s => ssButOne(s) = ssButOne.getOrElse(s, 0) + 1)

    println(f"? 1 ${n - 1}"); Console.flush
    (1 to (n * (n - 1) / 2))
      .map(_ => readLine.trim)
      .foreach(s =>
        ssButOne.getOrElse(s, -1) match {
          case 1    => ssButOne -= s
          case -1   => {}
          case _ @x => ssButOne(s) = x - 1
        }
      )

    val remains = ssButOne.keySet.toList.sortBy(_.length)

    def extraChar(cArr: List[Char], s: String): Char = {
      if (cArr.isEmpty || s.length == 1) s(0)
      else {
        val i = s.indexOf(cArr.head)
        val (pA, pB) = s.splitAt(i)
        extraChar(cArr.tail, pA ++ pB)
      }
    }

    val hack = remains
      .foldLeft(List[Char]())((cArr, s) => extraChar(cArr, s) :: cArr)
      .mkString
    println(f"! $hack")
  }
}

/* aabc */
/*
cb
caba
a
cab
ba
a
aba
c
aa
b
 */

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer

object Main extends App {
  val n = readInt()

  /* query the first */
  println(f"? 1 1")
  Console.flush()
  val cHead = readLine.trim.head

  /* query all... */
  println(f"? 1 $n")
  Console.flush()

  var substr2 = ArrayBuffer[String]()
  var substrN = ""
  (1 to (n * (n + 1) / 2))
    .map(_ => readLine.trim)
    .foreach(x => {
      if (x.length == 2) substr2 += x
      else if (x.length == n) substrN = x
    })

  val edges = ArrayBuffer.fill(n) { ArrayBuffer[Int]() }

  def foreachUntil(arr: String, f: (Char, Int) => Boolean, idx: Int = 0): Unit =
    if (!f(arr.head, idx))
      foreachUntil(arr.tail, f, idx + 1)

  substr2.foreach(x => {
    val (cA, cB) = (x(0), x(1))
    var iA, iB = -1
    foreachUntil(substrN, (c, i) => {
      if (iA == -1 && c == cA && edges(i).length < 2) {
        iA = i
      } else if (iB == -1 && c == cB && edges(i).length < 2) {
        iB = i
      }
      if (iA != -1 && iB != -1) true
      else false
    })
    edges(iA) += iB
    edges(iB) += iA
  })

  /* edges.foreach(x => {
    x.foreach(c => print(c.toString + " "))
    println
  }) */

  def printHack(curHead: Int): Unit =
    if (edges(curHead).isEmpty) {
      println("! " + substrN(curHead))
    } else {
      print(substrN(curHead))
      val neighbor = edges(curHead)(0)
      edges(curHead).clear
      edges(neighbor) -= curHead
      printHack(neighbor)
    }

  var iHead = -1
  foreachUntil(
    substrN,
    (c, i) =>
      if (c == cHead && edges(i).length == 1) {
        iHead = i
        true
      } else false
  )
  /* println(f"iHead: $iHead") */

  printHack(iHead)
}

/* aabc */
/*
cb
caba
a
cab
ba
a
aba
c
aa
b
 */

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Map

object Main extends App {
  val n = readInt()

  if (n < 2) {
    println("? 1 1"); Console.flush
    val c = readLine.trim.head
    println(f"! $c")

  } else {

    println(f"? 1 $n"); Console.flush
    val ssButOne = collection.mutable.Map[String, Int]()
    (1 to (n * (n + 1) / 2))
      .map(_ => readLine.trim.sorted)
      .foreach(s => ssButOne(s) = ssButOne.getOrElse(s, 0) + 1)

    println(f"? 1 ${n - 1}"); Console.flush
    (1 to (n * (n - 1) / 2))
      .map(_ => readLine.trim.sorted)
      .foreach(s =>
        ssButOne.getOrElse(s, -1) match {
          case 1    => ssButOne -= s
          case -1   => {}
          case _ @x => ssButOne(s) = x - 1
        }
      )

    val remains = ssButOne.keySet.toList.sortBy(_.length)

    def extraChar(cArr: List[Char], s: String): Char = {
      if (cArr.isEmpty || s.length == 1) s(0)
      else {
        val i = s.indexOf(cArr.head)
        val (pA, pB) = s.splitAt(i)
        extraChar(cArr.tail, pA ++ pB)
      }
    }

    val hack = remains
      .foldLeft(List[Char]())((cArr, s) => extraChar(cArr, s) :: cArr)
      .mkString
    println(f"! $hack")
  }
}

/* aabc */
/*
cb
caba
a
cab
ba
a
aba
c
aa
b
 */

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer

object Main extends App {
  val n = readInt()

  /* query the first */
  println("? 1 1")
  Console.flush
  val cHead = readLine.trim.head

  /* query all... */
  println(f"? 1 $n")
  Console.flush

  var substr2 = ArrayBuffer[String]()
  var substrN = ""
  (1 to (n * (n + 1) / 2))
    .map(_ => readLine.trim)
    .foreach(x => {
      if (x.length == 2) substr2 += x
      else if (x.length == n) substrN = x
    })

  val edges = ArrayBuffer.fill(n) { ArrayBuffer[Int]() }

  def foreachUntil(arr: String, f: (Char, Int) => Boolean, idx: Int = 0): Unit =
    if (!f(arr.head, idx))
      foreachUntil(arr.tail, f, idx + 1)

  substr2.foreach(x => {
    val (cA, cB) = (x(0), x(1))
    var iA, iB = -1
    foreachUntil(substrN, (c, i) => {
      if (iA == -1 && c == cA && edges(i).length < 2) {
        iA = i
      } else if (iB == -1 && c == cB && edges(i).length < 2) {
        iB = i
      }
      if (iA != -1 && iB != -1) true
      else false
    })
    edges(iA) += iB
    edges(iB) += iA
  })

  /* edges.foreach(x => {
    x.foreach(c => print(c.toString + " "))
    println
  }) */

  def printHack(curHead: Int): Unit =
    if (edges(curHead).isEmpty) {
      println(substrN(curHead))
    } else {
      print(substrN(curHead))
      val neighbor = edges(curHead)(0)
      edges(curHead).clear
      edges(neighbor) -= curHead
      printHack(neighbor)
    }

  var iHead = -1
  foreachUntil(
    substrN,
    (c, i) =>
      if (c == cHead && edges(i).length == 1) {
        iHead = i
        true
      } else false
  )
  /* println(f"iHead: $iHead") */

  print("! ")
  printHack(iHead)
  Console.flush
}

/* aabc */
/*
cb
caba
a
cab
ba
a
aba
c
aa
b
 */

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer

object Main extends App {
  val n = readInt()

  /* query the first */
  println("? 1 1")
  Console.flush
  val cHead = readLine.trim.head

  /* query all... */
  println(f"? 1 $n")
  Console.flush

  var substr2 = ArrayBuffer[String]()
  var substrN = ""
  (1 to (n * (n + 1) / 2))
    .map(_ => readLine.trim)
    .foreach(x => {
      if (x.length == 2) substr2 += x
      if (x.length == n) substrN = x
    })

  /* println(f"substr2: $substr2, substrN: $substrN") */

  val edges = ArrayBuffer.fill(n) { ArrayBuffer[Int]() }

  def foreachUntil(arr: String, f: (Char, Int) => Boolean, idx: Int = 0): Unit =
    if (!f(arr.head, idx))
      foreachUntil(arr.tail, f, idx + 1)

  substr2.foreach(x => {
    val (cA, cB) = (x(0), x(1))
    var iA, iB = -1
    foreachUntil(substrN, (c, i) => {
      if (iA == -1 && c == cA && edges(i).length < 2) {
        iA = i
      } else if (iB == -1 && c == cB && edges(i).length < 2) {
        iB = i
      }
      if (iA != -1 && iB != -1) true
      else false
    })
    edges(iA) += iB
    edges(iB) += iA
  })

  /* edges.foreach(x => {
    x.foreach(c => print(c.toString + " "))
    println
  }) */

  def printHack(curHead: Int): Unit =
    if (edges(curHead).isEmpty) {
      println(substrN(curHead))
    } else {
      print(substrN(curHead))
      val neighbor = edges(curHead)(0)
      edges(curHead).clear
      edges(neighbor) -= curHead
      printHack(neighbor)
    }

  var iHead = -1
  foreachUntil(
    substrN,
    (c, i) =>
      if (c == cHead && edges(i).length == 1) {
        iHead = i
        true
      } else false
  )
  /* println(f"iHead: $iHead") */

  print("! ")
  printHack(iHead)
  Console.flush
}

/* aabc */
/*
cb
caba
a
cab
ba
a
aba
c
aa
b
 */


The store sells $$$n$$$ items, the price of the $$$i$$$-th item is $$$p_i$$$. The store's management is going to hold a promotion: if a customer purchases at least $$$x$$$ items, $$$y$$$ cheapest of them are free.The management has not yet decided on the exact values of $$$x$$$ and $$$y$$$. Therefore, they ask you to process $$$q$$$ queries: for the given values of $$$x$$$ and $$$y$$$, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of items in the store and the number of queries, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^6$$$), where $$$p_i$$$ — the price of the $$$i$$$-th item. The following $$$q$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ each ($$$1 \le y_i \le x_i \le n$$$) — the values of the parameters $$$x$$$ and $$$y$$$ in the $$$i$$$-th query.

For each query, print a single integer — the maximum total value of items received for free for one purchase.

NoteIn the first query, a customer can buy three items worth $$$5, 3, 5$$$, the two cheapest of them are $$$3 + 5 = 8$$$.In the second query, a customer can buy two items worth $$$5$$$ and $$$5$$$, the cheapest of them is $$$5$$$.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is $$$1 + 2 + 3 = 6$$$.

import scala.collection.mutable.ListBuffer

object prob2 {
  def main(args: Array[String]) = {
    new Resolver1(Console.in, Console.out).run()
  }
}

class Resolver1(input: java.io.BufferedReader, output: java.io.PrintStream) {
  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val n = tokenizer.nextToken().toInt
    var q = tokenizer.nextToken().toInt
    val SS = ListBuffer.empty[Long]
    tokenizer = new StringTokenizer(input.readLine())
    for (i <- 0 until n) {
      SS+= tokenizer.nextToken().toLong
    }
    var S = SS.toArray.sorted.reverse
    S +:=0.toLong
    for (i <- 1 until S.length) {
      S(i) = S(i) + S(i - 1)
    }
    while (q > 0) {
      q -= 1
      tokenizer = new StringTokenizer(input.readLine())
      val x = tokenizer.nextToken().toInt
      val y = tokenizer.nextToken().toInt
      output.println(S(x) - S(x - y))
    }

  }
}

import scala.collection.mutable.ListBuffer

object prob {
  def main(args: Array[String]) = {
    new Resolver(Console.in, Console.out).run()
  }
}

class Resolver(input: java.io.BufferedReader, output: java.io.PrintStream) {
  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val n = tokenizer.nextToken().toInt
    var q = tokenizer.nextToken().toInt
    val SS = ListBuffer.empty[Long]
    tokenizer = new StringTokenizer(input.readLine())
    for (i <- 0 until n) {
      SS+= tokenizer.nextToken().toLong
    }
    var S = SS.toArray.sorted.reverse
    S +:=0.toLong
    for (i <- 1 until S.length) {
      S(i) = S(i) + S(i - 1)
    }
    while (q > 0) {
      q -= 1
      tokenizer = new StringTokenizer(input.readLine())
      val x = tokenizer.nextToken().toInt
      val y = tokenizer.nextToken().toInt
      println(S(x) - S(x - y))
    }

  }
}

object prob extends App {
  var L = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  var q = L(1)
  var S = scala.io.StdIn.readLine().split(" ").map(_.toLong).sorted
  val a = S.length-1
  for (i <- 1 until S.length) {
    S(a-i) = S(a-i)+S(a-i+1)
  }
  while (q>0) {
    q-=1
    val LL = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    if (LL(0) != LL(1)) {
      println(S(LL(0)-1) - S(LL(0) - LL(1)-1))
    }
    else {
      println(S(LL(0)-1))
    }
  }
}

import scala.util.Sorting.quickSort

object prob extends App {
  val L = readLine().split(" ").map(_.toInt)
  val q = L(1)
  var S = readLine().split(" ").map(_.toLong)
  quickSort(S)
  S.reverse
  S +:= 0.toLong
  for (i <- 1 until S.length) {
    S(i) = S(i)+S(i-1)
  }
  for (i <- 1 to q) {
    val LL = readLine().split(" ").map(_.toInt)
    println(S(LL(0)) - S(LL(0) - LL(1)))
  }
}

import scala.util.Sorting.quickSort

object prob extends App {
  val L = readLine().split(" ").map(_.toInt)
  val q = L(1)
  var S = readLine().split(" ").map(_.toLong)
  quickSort(S)
  S +:= 0.toLong
  S = S.reverse
  for (i <- 1 until S.length) {
    S(i) = S(i)+S(i-1)
  }
  for (i <- 1 to q) {
    val LL = readLine().split(" ").map(_.toInt)
    println(S(LL(0)) - S(LL(0) - LL(1)))
  }
}

import scala.util.Sorting.quickSort

object prob extends App {
  val L = readLine().split(" ").map(_.toInt)
  val q = L(1)
  var S = readLine().split(" ").map(_.toLong)
  quickSort(S)
  S +:= 0.toLong
  for (i <- 1 until S.length) {
    S(i) = S(i)+S(i-1)
  }
  for (i <- 1 to q) {
    val LL = readLine().split(" ").map(_.toInt)
    println(S(LL(0)) - S(LL(0) - LL(1)))
  }
}

import scala.collection.mutable

object prob extends App {
  import scala.collection.mutable.ArrayBuilder
  val L = readLine().split(" ").map(_.toInt)
  val q = L(1)
  var S = readLine().split(" ").map(_.toInt).sorted.reverse
  for (i <- 1 until S.length) {
    S(i) = S(i)+S(i-1)
  }
  for (i <- 1 to q) {
    val LL = readLine().split(" ").map(_.toInt)
    if (LL(0) != LL(1)) {
      println(S(LL(0)-1) - S(LL(0) - LL(1)-1))
    }
    else {
      println(S(LL(0)-1))
    }
  }
}

import scala.collection.mutable

object prob extends App {
  import scala.collection.mutable.ArrayBuilder
  val L = readLine().split(" ").map(_.toInt)
  val q = L(1)
  val S = readLine().split(" ").map(_.toInt).sorted.reverse
  var SS = new ArrayBuilder.ofInt
  var s: Int = 0
  SS += s
  for (i <- S) {
    s += i
    SS += s
  }
  val SSS = SS.result
  for (i <- 1 to q) {
    val LL = readLine().split(" ").map(_.toInt)
    println(SSS(LL(0)) - SSS(LL(0) - LL(1)))
  }
}

object prob extends App {

  import scala.io.StdIn
  import scala.math.{max, min, pow,abs}
  import scala.List
  import scala.util.Sorting.quickSort
  import scala.collection.mutable.{ArrayBuffer, ListBuffer}
  val L = readLine().split(" ").map(_.toInt)
  val q = L(1)
  val S = readLine().split(" ").map(_.toInt)
  quickSort(S)
  val SS = ListBuffer.empty[Long]
  var s: Long = 0
  SS +=s
  for (i <- S) {
    s+=i
    SS +=s
  }
  for (i <- 1 to q){
    val LL = readLine().split(" ").map(_.toInt)
    println(SS(LL(0)) - SS(LL(0) - LL(1)))
  }
}


Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.A string is 1-palindrome if and only if it reads the same backward as forward.A string is k-palindrome (k > 1) if and only if:   Its left half equals to its right half.  Its left and right halfs are non-empty (k - 1)-palindromes. The left half of string t is its prefix of length ⌊|t| / 2⌋, and right half — the suffix of the same length. ⌊|t| / 2⌋ denotes the length of string t divided by 2, rounded down.Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.

The first line contains the string s (1 ≤ |s| ≤ 5000) consisting of lowercase English letters.

Print |s| integers — palindromic characteristics of string s.

NoteIn the first example 1-palindromes are substring «a», «b», «b», «a», «bb», «abba», the substring «bb» is 2-palindrome. There are no 3- and 4-palindromes here.

object D 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 a = readLine.toCharArray.map(_ - 'a')
  val r = a.reverse
  val n = a.length

  val PRIME = 1303L
  val MOD = 1000000007L
  val MODB = BigInt(MOD)
  var pmul = 1L

  val ps, pinvs = Array.ofDim[Long](n + 1)
  val hs = Array.ofDim[Long](n + 1)

  var h = 0L
  for (i <- 0 to n) {
    ps(i) = pmul
    pinvs(i) = BigInt(pmul).modInverse(MODB).toLong
    hs(i) = h
    if (i < n) h = (h + a(i) * pmul) % MOD
    pmul = pmul * PRIME % MOD
  }

  val rps, rpinvs = Array.ofDim[Long](n + 1)
  val rhs = Array.ofDim[Long](n + 1)
  var rpmul = 1L

  var rh = 0L
  for (i <- 0 to n) {
    rps(i) = rpmul
    rpinvs(i) = BigInt(rpmul).modInverse(MODB).toLong
    rhs(i) = rh
    if (i < n) rh = (rh + r(i) * rpmul) % MOD
    rpmul = rpmul * PRIME % MOD
  }

  def hash(from: Int, to: Int) = (hs(to) - hs(from) + MOD) * pinvs(from) % MOD
  def hashR(from: Int, to: Int) = (rhs(n - from) - rhs(n - to) + MOD) * rpinvs(n - to) % MOD

  val pali = Array.fill(n, n){ 0 }
  for (i <- 0 until n) pali(i)(i) = 1
  val res = Array.fill(n){ 0L }
  res(0) = n
//println(hash(0, 2), hashR(2, 4))
  var len = 2
  while (len <= n) {
    var l = 0
    while (l + len <= n) {
      val half = len / 2
      val r = l + len - 1
      //val mid = l + half
      val hashLeft = hash(l, l + half)
      val hashRight = hashR(r - half + 1, r + 1)
      if (hashLeft == hashRight) {
        pali(l)(r) = pali(l)(l + half - 1) + 1
        //println(len, l, r, half, pali(l)(r))
        res(pali(l)(r) - 1) += 1
      }
      l += 1
    }

    len += 1
  }

  for (i <- res.indices.reverse) {
    if (i > 0) res(i - 1) += res(i)
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString(" "))
  Console.flush
}


Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.

The first line contains four integers n, k, a and b (1 ≤ k ≤ n ≤ 105, 0 ≤ a, b ≤ n) — the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n.

If it is impossible to drink n cups of tea, print "NO" (without quotes). Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them.

import java.util.StringTokenizer

import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val k = int()
  var gc = int()
  var bc = int()
  var failed = false

  val G = 'G'
  val B = 'B'

  def anti(c: Char): Char = {
    if (c == G) B else G
  }

  def s(prim: Char, fc: Int, sc: Int): String = {
    if ((fc == 0) && (sc == 0)) return ""
    val c = if (fc >= sc) Math.min(fc, k) else 1
    if (c <= 0) sys.error("")
    Array.fill(c)(prim).mkString + s(anti(prim), sc, fc - c)
  }

  val ans = Try {
    if (gc > bc) s(G, gc, bc) else s(B, bc, gc)
  }.getOrElse("NO")
  println(ans)
}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val k = int()
  var gc = int()
  var bc = int()
  var failed = false

  val G = 'G'
  val B = 'B'

  def anti(c: Char): Char = {
    if (c == G) B else G
  }

  @tailrec
  def s(start: String, prim: Char, fc: Int, sc: Int): String = {
    if ((fc == 0) && (sc == 0)) return start
    val c = if (fc >= sc) Math.min(fc, k) else 1
    if (c <= 0) sys.error("")
    s(start + Array.fill(c)(prim).mkString, anti(prim), sc, fc - c)
  }

  val ans = Try {
    if (gc > bc) s("", G, gc, bc) else s("", B, bc, gc)
  }.getOrElse("NO")
  println(ans)
}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val k = int()
  var gc = int()
  var bc = int()
  var failed = false

  val G = 'G'
  val B = 'B'

  def anti(c: Char): Char = {
    if (c == G) B else G
  }

  @tailrec
  def s(start: String, prim: Char, fc: Int, sc: Int): String = {
    if ((fc == 0) && (sc == 0)) return ""
    val c = if (fc >= sc) Math.min(fc, k) else 1
    if (c <= 0) sys.error("")
    s(Array.fill(c)(prim).mkString, anti(prim), sc, fc - c)
  }

  val ans = Try {
    if (gc > bc) s("", G, gc, bc) else s("", B, bc, gc)
  }.getOrElse("NO")
  println(ans)
}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val k = int()
  var gc = int()
  var bc = int()
  var failed = false

  val G = 'G'
  val B = 'B'

  def anti(c: Char): Char = {
    if (c == G) B else G
  }

  @tailrec
  def s(start: String, prim: Char, fc: Int, sc: Int): String = {
    if ((fc == 0) && (sc == 0)) return start
    val c = if (fc >= sc) Math.min(fc, k) else 1
    if (c <= 0) sys.error("")
    s(Array.fill(c)(prim).mkString, anti(prim), sc, fc - c)
  }

  val ans = Try {
    if (gc > bc) s("", G, gc, bc) else s("", B, bc, gc)
  }.getOrElse("NO")
  println(ans)
}


You are given two polynomials:  P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and  Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm.  Calculate limit .

The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly. The second line contains n + 1 space-separated integers — the factors of polynomial P(x): a0, a1, ..., an - 1, an ( - 100 ≤ ai ≤ 100, a0 ≠ 0). The third line contains m + 1 space-separated integers — the factors of polynomial Q(x): b0, b1, ..., bm - 1, bm ( - 100 ≤ bi ≤ 100, b0 ≠ 0).

If the limit equals  + ∞, print "Infinity" (without quotes). If the limit equals  - ∞, print "-Infinity" (without the quotes). If the value of the limit equals zero, print "0/1" (without the quotes). Otherwise, print an irreducible fraction — the value of limit , in the format "p/q" (without the quotes), where p is the — numerator, q (q > 0) is the denominator of the fraction.

NoteLet's consider all samples:           You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function

import java.util.Scanner

object Main {

   def main(args: Array[String]): Unit = {
      val scanner = new Scanner (System.in)
		val n, m = scanner nextInt ()
		val p = (for (i <- 0 to n) yield scanner nextInt ()) toList
		val q = (for (i <- 0 to m) yield scanner nextInt ()) toList

		if (n > m) {
			if (p(0) * q(0) < 0) print ("-")
			println ("Infinity")
		} else if (n < m) {
			println ("0/1")
		} else {
			val pp = math.abs (p(0))
			val qq = math.abs (q(0))
			val s = if (p(0) * q(0) > 0) 1 else -1
			val g = gcd (pp, qq)
			print (s * pp / g)
			print ("/")
			println (qq / g)
		}
   }

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

}

import java.util.Scanner

object Main {

   def main(args: Array[String]): Unit = {
      val scanner = new Scanner (System.in)
		val n, m = scanner nextInt ()
		val p = (for (i <- 0 to n) yield scanner nextInt ()) toList
		val q = (for (i <- 0 to m) yield scanner nextInt ()) toList

		if (n > m) {
			if (p(0) < 0) print ("-")
			println ("Infinity")
		} else if (n < m) {
			println ("0/1")
		} else {
			val pp = math.abs (p(0))
			val qq = math.abs (q(0))
			val s = if (p(0) * q(0) > 0) 1 else -1
			val g = gcd (pp, qq)
			print (s * pp / g)
			print ("/")
			println (qq / g)
		}
   }

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

}