A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?

Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.

Output the maximum possible length of a regular bracket sequence.

object P026B {
  def main(args: Array[String]) = {
    val s = readLine.map(x => -(x.toInt)*2 + 81)
    val n = s.size
    var l = n
    var sum = 0
    for (i <- 0 to n-1) {
      if (sum + s(i) >= 0) {
        sum += s(i)
      }
      else {
        l -= 1;
      }
    }
    println(l-sum)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val res = str.foldLeft(0, 0) {
    case ((sum, open), ')') if open == 0 => (sum + 1, open)
    case ((sum, open), ')')  => (sum, open - 1)
    case ((sum, open), '(')  => (sum, open + 1)
  }
  println(str.length - res._1 - res._2)
}

object Main26B {

  def main(args: Array[String]) {
    def processChar(r: (Int, Int), c: Char): (Int, Int) = {
      val (a, b) = r
      if (c == '(')
        (a+1, b+1)
      else
        if (b > 0)
          (a+1, b-1)
        else
          (a, b)
    }
    val str = readLine
    val (result_a, result_b) = str.foldLeft(0, 0)(processChar)
    println(result_a - result_b)
  }

}


Consider a table of size $$$n \times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 115$$$) — the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.

Output two integers $$$r$$$ and $$$c$$$ ($$$1 \le r \le n$$$, $$$1 \le c \le m$$$) separated by a space — the row and column numbers of the center of the black square.

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, M = sc.nextInt()
    var l, r, t, b = -1
    rep(N) { i =>
      val line = sc.next()
      rep(M) { j =>
         if (line(j) == 'B') {
           if (l == -1) l = j
           r = j
           if (t == -1) t = i
           b = i
         }
      }
    }

    out.println(s"${(t + b) / 2 + 1} ${(l + r) / 2 + 1}")
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object Test extends App {
  import java.io.PrintWriter
  import java.util.Scanner

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

  def nextInt = in.nextInt
  def nextDouble = in.nextDouble
  def nextString = in.next
  def stuff: Unit = {
    val n = nextInt
    val m = nextInt
    for (i <- 1 to n) {
      val cur = nextString
      if (cur.contains('B')) {
        val fst = cur.indexOf('B')
        val lst = cur.lastIndexOf('B')
        val (x, y) =
          if (fst == lst)
            i.toDouble -> (fst + 1).toDouble
          else {
            Math.ceil(i + (lst - fst) / 2) -> Math.ceil(((fst + lst) / 2) + 1)
          }
        out.println(x.toInt + " " + y.toInt)
        return
      }
    }
  }

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

import scala.io._

object a5 {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().drop(1).toArray
    val rows = lines.zipWithIndex.dropWhile(! _._1.contains("B")).takeWhile(_._1.contains("B"))
    val firstrow = rows.head._2+1
    val lastrow = rows.last._2+1
    val firstcol = rows.head._1.indexOf("B")+1
    val lastcol = rows.head._1.lastIndexOf("B")+1
    val (centerrow, centercol) = (firstrow + ((lastrow-firstrow)/2), firstcol + ((lastcol-firstcol)/2))
    println(s"$centerrow $centercol")
  }
}

/**
  * @author ShankarShastri
  *         Algorithm: Problem1 (http://codeforces.com/contest/1028/problem/A)
  */

import scala.io.StdIn._
import scala.annotation.tailrec

object FindSquares {

  def findSquare(ls: List[String]): (Int, Int) = {
    val l = ls.zipWithIndex.map(l => (l._2, l._1.indexOf('B'),
      l._1.lastIndexOf('B')))
      .filter(t => t._2 != -1 && t._3 != -1).map(e => (e._1 + 1, e._2 + 1, e._3 + 1))
    val le = l(l.length / 2)
    (le._1, (le._2 + le._3) / 2)
  }

  def main(args: Array[String]): Unit = {
    val List(r,_) = readLine.replaceAll("\\s+$", "").split(" ").map(_.trim.toInt).toList
    val strList = (1 to r).map(_ => readLine).toList
    val res = findSquare(strList.map(_.trim))
    println(s"${res._1} ${res._2}")
  }
}


Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.

The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000).

On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.

NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana".

object A extends App {

  def readString = Console.readLine

  val s = readString
  val n = readString.toInt

  def check(m: Int) : String = {
    val sb = new StringBuilder()
    var len = 0
    for (c <- chars) {
      val need = counts(c)
      val add = (need - 1) / m + 1
      len += add
      sb ++= (c.toString * add)
    }
    if (len <= n) {
      if (len < n) {
        sb ++= ("a" * (n - len))
      }
      sb.toString
    } else ""
  }

  val chars = s.distinct
  val groups = s.groupBy(identity)
  val counts = groups.map(cs => (cs._1, cs._2.length))

  if (chars.size > n) {
    println(-1)
  } else {
    var lo = 1
    var hi = 1000
    var best = ""
    var bestM = 0
    while (lo <= hi) {
      val mid = lo + (hi - lo) / 2
      val str = check(mid)
      //println(lo, hi, mid, str)
      if (str == "") {
        lo = mid + 1
      } else {
        hi = mid - 1
        best = str
        bestM = mid
      }
    }
    println(bestM)
	println(best)
  }
}


Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:  on both diagonals of the square paper all letters are the same;  all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.

The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.

Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.

import java.util.StringTokenizer

object _404A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (0 until n).map(i => next).toArray
  val ch = a(0)(0)
  val dish = a(0)(1)

  val cb = for {
      i <- 0 until n
      j <- 0 until n
    } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish

  if (ch != dish && cb.forall(i => i)) println("YES")
  else println("NO")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val k = in.next().toInt
  val data = Range(0, k).map { i => (i, in.next())}
  val symbols = data.head._2.toSet
  val symbol =  data.head._2.head
  if (symbols.size != 2) println("NO")
  else {
    val r = data.forall{
      case(i, str) =>
        val count = str.count(_ == symbol)
        str.forall(symbols) && count < 3 && str.charAt(i) == symbol && str.charAt(str.length - i - 1) == symbol && {
          i != str.length - i - 1 || count == 1
        }
    }
    if (r)
      println("YES")
    else
      println("NO")
  }

}

object A404 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(read.toCharArray)
    var xChar = in(0)(0)
    var diffChar = in(1)(0)
    var ifX = true
    var ifDiff = true
    for(i <- 0 until n; j <- 0 until n) {
      if(i == j) {// diagonal 1
        ifX &= in(i)(j) == xChar
      } else if(i + j == n-1) {// diagonal 2
        ifX &= in(i)(j) == xChar
      } else {
        ifDiff &= in(i)(j) == diffChar
      }
    }

    if (xChar != diffChar && ifDiff && ifX) {
      println("YES")
    } else {
      println("NO")
    }
  }

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

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

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

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

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

}

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

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

  type Row = List[Char]

  val N = sc.nextInt
  sc.nextLine
  val P: List[Row] = List.fill(N)(sc.nextLine.toList)

  def solve(): String = {

    P(0) match {

      case x :: y :: _ if x != y => {

          def row(n: Int): Row = {
            List.range(0, N).map { i =>
              if (i == n || i == N - n - 1) x
              else y
            }
          }

          if (P == List.range(0, N).map(row)) "YES"
          else "NO"
        }
      case _ => "NO"
    }
  }

  out.println(solve)
  out.close
}

object A extends App {
  val n = readInt();
  val in = Array.fill(n)(readLine())
  var sa = Set[Char]()
  var sb = Set[Char]()
  for (i <- 0 until n; j <- 0 until n)
    if (i==j || n-i-1==j || i==n-j-1 || n-j-1==n-i-1) sa += in(i)(j);
    else sb += in(i)(j)

  if (sa.size == 1 && sb.size == 1 && sa.head != sb.head)
    println("YES");
  else
    println("NO")
}

import java.util.StringTokenizer

object _404A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (0 until n).map(i => next).toArray
  val ch = a(0)(0)
  val dish = a(0)(1)

  val cb = for {
      i <- 0 until n
      j <- 0 until n
    } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish

  if (cb.forall(i => i)) println("YES")
  else println("NO")
}

import java.util.StringTokenizer

object _404A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (0 until n).map(i => next).toArray
  val ch = a(0)(0)
  val dish = a(0)(1)

  val cb = for {
      i <- 0 until n
      j <- 0 until n
    } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish

  if (cb != dish && cb.forall(i => i)) println("YES")
  else println("NO")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val k = in.next().toInt
  val data = Range(0, k).map { i => (i, in.next())}
  val symbols = data.head._2.toSet
  val symbol =  data.head._2.head
  if (symbols.size != 2) println("NO")
  else {
    val r = data.forall{
      case(i, str) =>
        val count = str.count(_ == symbol)
        str.forall(symbols) &&  count < 3 && str.charAt(i) == symbol && str.charAt(str.length - i - 1) == symbol
    }
    if (r)
      println("YES")
    else
      println("NO")
  }

}

object A404 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(read.toCharArray)
    var xChar = in(0)(0)
    var diffChar = in(1)(0)
    var ifX = true
    var ifDiff = true
    for(i <- 0 until n; j <- 0 until n) {
      if(i == j) {// diagonal 1
        ifX &= in(i)(j) == xChar
      } else if(i + j == n-1) {// diagonal 2
        ifX &= in(i)(j) == xChar
      } else {
        ifDiff &= in(i)(j) == diffChar
      }
    }

    if (ifDiff && ifX) {
      println("YES")
    } else {
      println("NO")
    }
  }

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

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

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

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

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

}

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

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

  type Row = List[Char]

  val N = sc.nextInt
  sc.nextLine
  val P: List[Row] = List.fill(N)(sc.nextLine.toList)

  def solve(): String = {
    val (x, y) = (P(0)(0), P(0)(1))

    def row(n: Int): Row = {
      List.range(0, N).map { i =>
        if (i == n || i == N - n - 1) x
        else y
      }
    }

    if (P == List.range(0, N).map(row)) "YES"
    else "NO"
  }

  out.println(solve)
  out.close
}


Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.

For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.

NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.

object Main {
    def main(args: Array[String]) {
        val t = readInt
        Stream.fill(t)(f1).foldLeft(()){ case _ => () }
    }

    def f1() {
        val Array(n, s, k) = readLine.split(" ").map(_.toLong)
        val a = readLine.split(" ").map(_.toLong)
        val x = Array.ofDim[Int](2000)
        a.foreach((z) => {
            val i = math.abs(s - z)
            if (i <  2000) {
                x(i.toInt) = x(i.toInt) + 1
            }
        })
        val ans = if (x(0) == 0) 0 else x.zipWithIndex.indexWhere{
            case (v, i) => i != 0 && (if (s - i <= 0 || s + i > n) v < 1 else v < 2)
        }
        println(ans)
    }
}

object Main {
    def main(args: Array[String]) {
        val t = readInt
        Stream.fill(t)(f1).foldLeft(()){ case _ => () }
    }

    def f1() {
        val Array(n, s, k) = readLine.split(" ").map(_.toLong)
        val a = readLine.split(" ").map(_.toLong)
        val x = Array.ofDim[Int](2000)
        a.foreach((z) => {
            val i = math.abs(s - z)
            if (i <  2000) {
                x(i.toInt) = x(i.toInt) + 1
            }
        })
        val ans = if (x(0) == 0) 0 else x.zipWithIndex.indexWhere{
            case (v, i) => i != 0 && (if (s - i <= 0) v < 1 else v < 2)
        }
        println(ans)
    }
}

object Main {
    def main(args: Array[String]) {
        val t = readInt
        Stream.fill(t)(f1).foldLeft(()){ case _ => () }
    }

    def f1() {
        val Array(n, s, k) = readLine.split(" ").map(_.toLong)
        val a = readLine.split(" ").map(_.toLong)
        val x = (List.tabulate(1000)((x) => s + x) ++ List.tabulate(1000)((x) => s - x).filter((i) => i > 0)).toSet
        val eset = a.foldLeft(x){
            case (set, i) => if (-1000 <= s - i && s - i < 1000) {
                set - i.toInt
            } else set
        }.map((x) => math.abs(s - x))
        println(eset.min)
    }
}

object Main {
    def main(args: Array[String]) {
        val t = readInt
        Stream.fill(t)(f1).foldLeft(()){ case _ => () }
    }

    def f1() {
        val Array(n, s, k) = readLine.split(" ").map(_.toLong)
        val a = readLine.split(" ").map(_.toLong)
        val x = (List.tabulate(1000)((x) => s + x.toLong) ++ List.tabulate(1000)((x) => s - x.toLong).filter((i) => i > 0)).toSet
        val eset = a.foldLeft(x){
            case (set, i) => if (-1000 <= s - i && s - i < 1000) {
                set - i
            } else set
        }.map((x) => math.abs(s - x))
        println(eset.min)
    }
}


You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $$$t$$$, then for each $$$i, j$$$ such that $$$t_i = t_j$$$ should be satisfied $$$|i-j|~ mod~ 3 = 0$$$. The value $$$|x|$$$ means absolute value of $$$x$$$, the operation $$$x~ mod~ y$$$ means remainder of $$$x$$$ when divided by $$$y$$$.For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' — colors of lamps in the garland.

In the first line of the output print one integer $$$r$$$ — the minimum number of recolors needed to obtain a nice garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ — a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

//package codeforces.contest1108

/*
http://codeforces.com/contest/1108/problem/C
 */
object NiceGarland {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val str = io.StdIn.readLine()

    val maxZeroes = n / 3 + (if (n % 3 >= 1) 1 else 0)
    val maxOnes = n / 3 + (if (n % 3 == 2) 1 else 0) // 1 2 3, 4 5 6, 7 8 9
    val maxTwos = n / 3

    def count(c: Char): Array[Int] = {
      Array(maxZeroes - (0 until n by 3).count(str(_) == c), maxOnes - (1 until n by 3).count(str(_) == c), maxTwos - (2 until n by 3).count(str(_) == c))
    }

    val redCost = count('R')
    val blueCost = count('B')
    val greenCost = count('G')

    val (optimalPermutation: String, cost: Int) = Set[String]("RGB", "RBG", "BGR", "BRG", "GRB", "GBR")
      .map(s =>
        (s, s.zipWithIndex.foldLeft(0) {
            case (acc: Int, (c: Char, i: Int)) =>
              acc + (c match {
                case 'R' => redCost(i)
                case 'B' => blueCost(i)
                case 'G' => greenCost(i)
              })
          })).minBy(_._2)

    val result = str.toCharArray

    optimalPermutation.zipWithIndex.foreach { case (c, i) => fix(i, c) }

    def fix(startingFrom: Int, withColor: Char): Unit = {
      (startingFrom until n by 3).foreach(result(_) = withColor)
    }

    println(cost + " " + result.mkString(""))
  }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = ns(N)
    val COLOR = "RGB"

    var best = 1e9.toInt + 10
    var ans: (Int, Int, Int) = null

    def calc(i: Int, j: Int, k: Int): Int = {
      var changed = 0
      val c = Array(i, j, k)
      REP(N) { l =>
        if (S(l) != COLOR(c(l % 3))) changed += 1
      }
      changed
    }

    REP(3) { i =>
      REP(3) { j =>
        REP(3) { k =>
          if (i != j && j != k && i != k) {
            val v = calc(i, j, k)
            if (v < best) {
              best = v
              ans = (i, j, k)
            }
          }
        }
      }
    }

    out.println(best)
    val c = Array(ans._1, ans._2, ans._3)
    REP(N) { i =>
      out.print(COLOR(c(i % 3)))
    }
    out.println()
  }

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

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

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

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

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

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

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

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

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

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

object CF_535_3_C {
// date: 25/01/2019

  type In  = (Int, String)
  type Out = String

  def solve(in: In): Out = {
    val (n, s) = in
    // Assume starts with each of R G B
    val cs1 = Vector('R','G','B')
    val cs2 = Vector('R','B','G')
    val ss1 = Stream.iterate(0)(i => (i + 1)%3).map(cs1)
    val ss2 = Stream.iterate(0)(i => (i + 1)%3).map(cs2)

   def differences(xs: Seq[Char], ys: Seq[Char]) = (xs, ys).zipped.count(i => i._1 != i._2)

    val results = for {
      order: Stream[Char] <- Vector(ss1, ss2)
      start <- Seq(order, order.drop(1), order.drop(2))
      seq = start.take(n)
    } yield (seq, differences(seq, s))

    val res = results.minBy(_._2)
    res._2.toString + "\n" +
       res._1.mkString

  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.nextLine})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.

The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.  The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world. The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi. It is guaranteed that the graph described by the input is stable.

Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.

NoteFor the first sample test, the graph looks like this:    Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this:    We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.

import java.util.StringTokenizer

import scala.collection.mutable

object A extends App {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }

  read()
  val n = st.nextToken().toInt
  val m = st.nextToken().toInt
  val k = st.nextToken().toInt

  read()
  val capitals = Array.fill(k)(st.nextToken().toInt - 1)

  var links = Array.fill(n)(List.empty[Int])
  var a = 0
  var b = 0
  (1 to m).foreach { _ =>
    read()
    a = st.nextToken().toInt - 1
    b = st.nextToken().toInt - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  var visited = Array.fill(n)(false)

  var stack = new mutable.Stack[Int]
  def count(capital: Int): Int = {
    b = 0
    stack.push(capital)
    while (stack.nonEmpty) {
      a = stack.pop()
      if (!visited(a)) {
        b += 1
        visited(a) = true
        links(a).foreach(stack.push)
      }
    }
    b
  }

  var groups = capitals.map(count)
  val total = groups.sum
  val free = n - total
  val max = groups.max

  def maxForGroup(c: Int) = c * (c-1) / 2

  val maxLinks = groups.map(maxForGroup).sum + maxForGroup(max + free) - maxForGroup(max)
  val ans = maxLinks - m

  println(ans)

}

import scala.collection._
import scala.collection.mutable.ListBuffer

object HongcowBS2 extends App {

  val tokens = scala.io.Source.stdin.getLines
    .flatMap( _ split ' ' filter (_.nonEmpty))

  def nextInt() = tokens.next().toInt

  def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2

  val n, m, k = nextInt()

  if (k == 1) {
    println(getLinksNum(n) - m)
  } else if (m == 0) {
    println(getLinksNum(n - k + 1))
  } else {

    val governments = (0 until k).map{ _ =>
      val k = nextInt()
      k -> mutable.BitSet(k)
    }.toMap

    var freeLinks = ListBuffer[Array[Int]]()
    for (_ <- 0 until m) {
      val link = Array(nextInt(), nextInt())
      if (governments.contains(link(0))) {
        governments.get(link(0)).get += link(1)
      } else if (governments.contains(link(1))) {
        governments.get(link(1)).get += link(0)
      } else {
        freeLinks += link
      }
    }

    var continue = true
    while (continue) {
      val remainingLinks = ListBuffer[Array[Int]]()
      for (link <- freeLinks) {
        val entry = governments.find { p =>
          (p._2.contains(link(0))
            || p._2.contains(link(1)))
        }
        if (entry.isEmpty) remainingLinks += link
        else entry.get._2 += (link(0), link(1))
      }
      if (remainingLinks.size == freeLinks.size) continue = false
      else freeLinks = remainingLinks
    }

    val govCounts = governments.values.map(_.size).toArray
    val maxIndex = govCounts.indexOf(govCounts.max)
    val freeCount = n - govCounts.sum
    govCounts(maxIndex) = govCounts(maxIndex) + freeCount
    val result = govCounts.map(getLinksNum).sum - m
    println(result)
  }
}

import scala.collection._
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLine

object HongcowBS extends App {

  def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2

  val Array(n, m, k) = readLine.split(" ").map(_.toInt)

  if (k == 1) {
    println(getLinksNum(n) - m)
  } else if (m == 0) {
    println(getLinksNum(n - k + 1))
  } else {
    val governments = readLine.split(" ").map { e =>
      val k = e.toInt
      k -> mutable.BitSet(k)
    }.toMap

    var freeLinks = ListBuffer[Array[Int]]()
    for (_ <- 0 until m) {
      val link = readLine.split(" ").map(_.toInt)
      val Array(a, b) = link
      if (governments.contains(link(0))) {
        governments.get(link(0)).get += link(1)
      } else if (governments.contains(link(1))) {
        governments.get(link(1)).get += link(0)
      } else {
        freeLinks += link
      }
    }

    var continue = true
    while (continue) {
      val remainingLinks = ListBuffer[Array[Int]]()
      for (link <- freeLinks) {
        val entry = governments.find { p =>
          (p._2.contains(link(0))
            || p._2.contains(link(1)))
        }
        if (entry.isEmpty) remainingLinks += link
        else entry.get._2 += (link(0), link(1))
      }
      if (remainingLinks.size == freeLinks.size) continue = false
      else freeLinks = remainingLinks
    }

    val govCounts = governments.values.map(_.size).toArray
    val maxIndex = govCounts.indexOf(govCounts.max)
    val freeCount = n - govCounts.sum
    govCounts(maxIndex) = govCounts(maxIndex) + freeCount
    val result = govCounts.map(getLinksNum).sum - m
    println(result)
  }
}

import scala.io.StdIn.readLine

object HongCowBuild extends App {

  def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2

  def readLinksAndGetLinkedNodes(m: Int)  = {
    var linkedNodes = 0
    (0 until m).foreach { _ =>
      val Array(s, d) = readLine.split(" ").map(_.toInt)
      if (govNodes.contains(s)) {
        govNodes.put(s, govNodes.get(s).get + 1)
        linkedNodes += 1
      }else if (govNodes.contains(d)){
        govNodes.put(d, govNodes.get(d).get + 1)
        linkedNodes += 1
      }
    }
    linkedNodes
  }

  val Array(n, m, k) = readLine.split(" ").map(_.toInt)
  val governments = readLine.split(" ").map(_.toInt)
  val govNodes = collection.mutable.HashMap[Int, Int]()

  governments.foreach(govNodes.put(_, 1))
  var linkedNodes = readLinksAndGetLinkedNodes(m)
  val maxGov = govNodes.maxBy(_._2)
  val remained = n - k - linkedNodes
  val maxGovSum = getLinksNum(govNodes.remove(maxGov._1).get + remained)
  val allSum = govNodes.map(e => getLinksNum(e._2)).sum
  val result = allSum + maxGovSum - m
  println(result)
}

import scala.io.StdIn.readLine

object Hongcow extends App {

  def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2

  def readLinks(m: Int)  = {
    var freeLinks = 0
    (0 until m).foreach { _ =>
      val Array(s, d) = readLine.split(" ").map(_.toInt)
      if (govNodes.contains(s))
        govNodes.put(s, govNodes.get(s).get + 1)
      else if (govNodes.contains(d))
        govNodes.put(d, govNodes.get(d).get + 1)
      else freeLinks += 1
    }
    freeLinks
  }

  val Array(n, m, k) = readLine.split(" ").map(_.toInt)
  val governments = readLine.split(" ").map(_.toInt)
  val govNodes = collection.mutable.HashMap[Int, Int]()
  governments.foreach(govNodes.put(_, 0))
  var freeLinks = readLinks(m)
  val maxGov = govNodes.maxBy(_._2)
  val maxGovSum = getLinksNum(govNodes.remove(maxGov._2).get)
  val allSum = govNodes.map(e => getLinksNum(e._2)).sum
  val result = allSum + maxGovSum - m
  println(result)
}


You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p / q?

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Each of the next t lines contains four integers x, y, p and q (0 ≤ x ≤ y ≤ 109; 0 ≤ p ≤ q ≤ 109; y > 0; q > 0). It is guaranteed that p / q is an irreducible fraction. Hacks. For hacks, an additional constraint of t ≤ 5 must be met.

For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.

NoteIn the first example, you have to make 4 successful submissions. Your success rate will be equal to 7 / 14, or 1 / 2.In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9 / 24, or 3 / 8.In the third example, there is no need to make any new submissions. Your success rate is already equal to 20 / 70, or 2 / 7.In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.

import scala.math.BigDecimal.RoundingMode

object Solution {
  val pattern = """(\d+) (\d+) (\d+) (\d+)""".r

  def main(args: Array[String]): Unit = {
    val t = readLine().toLong

    (1L to t)
      .map(i => readLine())
      .map(findSolution)
      .foreach(println)
  }

  def findSolution(line: String): Long = {
    val pattern(x, y, p, q) = line
    val suc = x.toLong
    val total = y.toLong
    val denom = p.toLong
    val numer = q.toLong

    if (denom == 0 && suc == 0)
      0 else
    if (denom == 0 && suc != 0)
      -1 else
    if (denom == numer && suc == total)
      0 else
    if (denom == numer && suc != total)
      -1
    else {
      val k = ((BigDecimal(suc) / denom) setScale(0, RoundingMode.CEILING)).toLong max
        ((BigDecimal(total) / numer) setScale(0, RoundingMode.CEILING)).toLong max
        ((BigDecimal(total - suc) / (numer - denom)) setScale(0, RoundingMode.CEILING)).toLong
      val toSolveSuc = denom * k - suc
      val toSolveUnsuc = numer * k - total - toSolveSuc

      toSolveSuc + toSolveUnsuc
    }
  }
}

object C extends App {

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

  val Array(n) = readInts(1)

  for (_ <- 0 until n) {
    val Array(x, y, p, q) = readLongs(4)

    if ((p == q && x < y) || (p == 0 && x > 0)) {
      println(-1)
    } else {

      def can(n: Long): Boolean = {
        val b = q * n - y
        val a = p * n - x
        a >= 0 && a <= b
      }

      @annotation.tailrec
      def binSearch(low: Long, hi: Long): Long = {
        if (hi < low) low
        else {
          val mid = (low + hi) / 2
          if (can(mid)) binSearch(low, mid - 1)
          else binSearch(mid + 1, hi)
        }
      }

      val n = binSearch(1, Int.MaxValue)

      val b = q * n - y

      println(b)
    }
  }
}

//package p807

/**
  * Created by velizar on 16/05/17.
  */
object C extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toLong))
  val Array(t) = input(0)

  val maxValue = 2000000000000000000l

  def search(from: Long, to: Long, x: Long, y: Long, p: Long, q: Long): Long = {
    val current = (from + to) / 2
//    println((from, current, to))
    val currentLB = x
    val currentUB = current * q - y + x
    val currentDesired = current * p
    val inBounds = currentLB <= currentDesired && currentDesired <= currentUB
    if (inBounds && from == to)
      current * q - y
    else if (inBounds)
      search(from, current, x, y, p, q)
    else
      search(current + 1, to, x, y, p, q)
  }

  val output = input.drop(1).map {
    case Array(x, y, p, q) if y % q == 0 && p * (y / q) == x => 0
    case Array(_, _, 0, 1) => -1
    case Array(_, _, 1, 1) => -1
    case Array(x, y, p, q) =>
//      println((x, y, p, q))
      search(y / q + 1, maxValue / q, x, y, p, q)
  }.mkString("\n")
  print(output)
}

//package p807

/**
  * Created by velizar on 16/05/17.
  */
object C extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(t) = input(0)

//  def succ(x: Int, y: Int) = x
//  def failed(x: Int, y: Int) = y - x

  def search(from: Int, to: Int, x: Int, y: Int, p: Int, q: Int): Int = {
    val currentD = (from + to) / 2.0
    val current = (if (scala.util.Random.nextBoolean()) currentD.floor else currentD.ceil).toInt
    val currentLB = x
    val currentUB = current * q - y + x
    val currentDesired = current * p
    val inBounds = currentLB <= currentDesired && currentDesired <= currentUB
    if (inBounds && from == to)
      current * q - y
    else if (inBounds)
      search(from, current, x, y, p, q)
    else
      search(current + 1, to, x, y, p, q)
  }

  val maxValue = 2000000000
  def solve(x: Int, y: Int, p: Int, q: Int): Int = {
    if (y % q == 0 && p * (y / q) == x)
      0
    else
      search(y / q + 1, maxValue / q, x, y, p, q)
  }

  val output = input.drop(1).map {
    case Array(_, _, 0, 1) => -1
    case Array(_, _, 1, 1) => -1
    case Array(x, y, p, q) => solve(x, y, p, q)
  }.mkString("\n")
  print(output)
}

//package p807

/**
  * Created by velizar on 16/05/17.
  */
object C extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(t) = input(0)

//  def succ(x: Int, y: Int) = x
//  def failed(x: Int, y: Int) = y - x

  def search(from: Int, to: Int, x: Int, y: Int, p: Int, q: Int): Int = {
    val currentD = (from + to) / 2.0
    val current = (if (scala.util.Random.nextBoolean()) currentD.floor else currentD.ceil).toInt
    val currentLB = x
    val currentUB = current * q - y + x
    val currentDesired = current * p
    val inBounds = currentLB <= currentDesired && currentDesired <= currentUB
    if (inBounds && from == to)
      current * q - y
    else if (inBounds)
      search(from, current, x, y, p, q)
    else
      search(current + 1, to, x, y, p, q)
  }

  val maxValue = 2000000000
  def solve(x: Int, y: Int, p: Int, q: Int): Int = {
    if (y % q == 0 && p * (y / q) == x)
      0
    else
      search(y / q + 1, maxValue / q, x, y, p, q)
  }

  val output = input.drop(1).map {
    case Array(x, y, p, q) if x == p && y == q => 0
    case Array(_, _, 0, 1) => -1
    case Array(_, _, 1, 1) => -1
    case Array(x, y, p, q) => solve(x, y, p, q)
  }.mkString("\n")
  print(output)
}


You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $$$n$$$ bosses in this tower, numbered from $$$1$$$ to $$$n$$$. The type of the $$$i$$$-th boss is $$$a_i$$$. If the $$$i$$$-th boss is easy then its type is $$$a_i = 0$$$, otherwise this boss is hard and its type is $$$a_i = 1$$$.During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session.Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.For example: suppose $$$n = 8$$$, $$$a = [1, 0, 1, 1, 0, 1, 1, 1]$$$. Then the best course of action is the following:  your friend kills two first bosses, using one skip point for the first boss;  you kill the third and the fourth bosses;  your friend kills the fifth boss;  you kill the sixth and the seventh bosses;  your friend kills the last boss, using one skip point, so the tower is completed using two skip points. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of bosses. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th boss. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.

import scala.io.StdIn._
import scala.math._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach { u =>
      val n = readInt
      val a = readLine.split(" ").map(_.toInt)
      val dp = Array.ofDim[Int](n+1, 2)
      dp(1)(0) = a(0)
      dp(1)(1) = a(0)
      if(n >= 2) {
        dp(2)(0) = dp(1)(0) + a(1)
        dp(2)(1) = dp(1)(0)
      }
      for(k <- 3 to n) {
        dp(k)(0) = min(dp(k-1)(1) + a(k - 1), dp(k-2)(1) + a(k-1) + a(k-2))
        dp(k)(1) = min(dp(k-1)(0), dp(k-2)(0))
      }
      println(min(dp(n)(0), dp(n)(1)))
    }
  }
}


There is a chessboard of size $$$n$$$ by $$$n$$$. The square in the $$$i$$$-th row from top and $$$j$$$-th column from the left is labelled $$$(i,j)$$$.Currently, Gregor has some pawns in the $$$n$$$-th row. There are also enemy pawns in the $$$1$$$-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from $$$(i,j)$$$ to $$$(i-1,j)$$$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $$$(i,j)$$$ to either $$$(i-1,j-1)$$$ or $$$(i-1,j+1)$$$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.Gregor wants to know what is the maximum number of his pawns that can reach row $$$1$$$?Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row $$$1$$$, it is stuck and cannot make any further moves.

The first line of the input contains one integer $$$t$$$ ($$$1\le t\le 2\cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot{10}^{5}$$$) — the size of the chessboard. The second line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to an enemy pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. The third line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to a Gregor's pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. It is guaranteed that the sum of $$$n$$$ across all test cases is less than $$$2\cdot{10}^{5}$$$.

For each test case, print one integer: the maximum number of Gregor's pawns which can reach the $$$1$$$-st row.

NoteIn the first example, Gregor can simply advance all $$$3$$$ of his pawns forward. Thus, the answer is $$$3$$$.In the second example, Gregor can guarantee that all $$$4$$$ of his pawns reach the enemy row, by following the colored paths as demonstrated in the diagram below. Remember, only Gregor takes turns in this "game"!  In the third example, Gregor's only pawn is stuck behind the enemy pawn, and cannot reach the end.In the fourth example, Gregor has no pawns, so the answer is clearly $$$0$$$.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (1, 1))   => (count + 2, 0, 0)
      case ((count, 1, 1), (1, 0))   => (count + 1, 0, 0)
      case ((count, 1, 0), (1, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (0, 1))   => (count + 1, 0, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

import java.io._
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new BufferedReader(new java.io.InputStreamReader(System.in))
    val writer =  new PrintWriter(System.out)
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readString().split("").map(_.toInt)
        val b = readString().split("").map(_.toInt)

        var count = 0
        for (i <- 0 until n) {
            if (a(i) == 0) {
                if (b(i) == 1) {
                    count += 1
                    b(i) = 0
                }
            } else {
                if (i - 1 >= 0 && b(i - 1) == 1)
                    count += 1
                else if (i + 1 < n && b(i + 1) == 1) {
                    count += 1
                    b(i + 1) = 0
                }
            }
        }

        writer.println(count)

    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (tm, bm) = (tn zip bn).map {
      case (0, 1) => (1, 0)
      case (t, b) => (t, b)
    }.unzip

    val (ans, _, _) = (tm zip bm).foldLeft((tm.count(_ == 1) - tn.count(_ == 1), 0, 0)) {
      case ((c, 1, 1), (1, 1)) => (c + 2, 1, 0)
      case ((c, 1, 1), (1, 0)) => (c + 1, 1, 0)
      case ((c, 1, 0), (1, 1)) => (c + 1, 1, 0)
      case ((c, _, _), (x, y)) => (c, x, y)
    }

    println(ans)

  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (1, 1)) => (count + 2, 1, 0)
      case ((count, 1, 1), (1, 0)) => (count + 1, 1, 0)
      case ((count, 1, 1), (0, 1)) => (count + 2, 1, 0)
      case ((count, 1, 1), (0, 0)) => (count, 0, 0)

      case ((count, 1, 0), (1, 1)) => (count + 1, 1, 0)
      case ((count, 1, 0), (1, 0)) => (count, 1, 0)
      case ((count, 1, 0), (0, 1)) => (count + 1, 1, 0)
      case ((count, 1, 0), (0, 0)) => (count, 0, 0)

      case ((count, _, _), (0, 1)) => (count + 1, 1, 0)

      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, 1, 1), (1, _))   => (count + 1, 1, 0)
      case ((count, 1, 0), (_, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, 1, 0), (_, 1))   => (count + 1, 1, 0)
      case ((count, 0, 0), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, 1, _), (1, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, _, _), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, 1, _), (ti, 1))  => (count + 1, ti, 0)
      case ((count, _, 1), (1, bi))  => (count + 1, 1, bi)
      case ((count, _, _), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)

    }

    println(ans)
  }
}


You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.

The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.   In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.  In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.  In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.

Output the answer with absolute or relative error no more than 1e - 9.

NoteConsider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability  we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability  the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to .

import scala.collection._

object G extends App {

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

  val Array(n, k) = readInts(2)
  val ps = readInts(n)
  var inversions = 0d
  var combinations = 0d

  def solve(arr0: Array[Int], depth: Int): Unit = {
    if (depth == 0) {
      combinations += 1d
      for (i <- 0 until n) {
        for (j <- 0 until i) if (arr0(j) > arr0(i)) inversions += 1d
      }
    } else {
      for (l <- 0 until n) {
        for (r <- l until n) {
          val arr = arr0.clone
          val mid = (r - l) / 2
          for (i <- 0 to mid) {
            val tmp = arr(l + i)
            arr(l + i) = arr(r - i)
            arr(r - i) = tmp
          }
          solve(arr, depth - 1)
        }
      }
    }
  }

  solve(ps, k)
  println(inversions / combinations)
}


Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.

Same as the easy version, but the limits have changed: 1 ≤ n, k ≤ 400 000.

import java.util.StringTokenizer

import scala.collection.mutable

object A 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()
  read()
  val a = (1 to n).map(_ => int()).toArray
  val ab = Array.fill(n+1)(mutable.ArrayBuilder.make[Int])
  for {
    i <- 0 until n
  } ab(a(i)) += i
  val pos = ab.map(_.result().iterator)

  val set = new mutable.HashSet[Int]()
  val pq = new mutable.PriorityQueue[(Int, Int)]

  def addToPQ(i : Int, v: Int) = {
    val it = pos(v)
    var q = -1
    while (it.hasNext && q <= i) q = it.next
    if (q == -1 || q <= i) q = INF
    pq += ((q, v))
  }

  var ans = 0
  (0 until n).foreach { i =>
    val v = a(i)
    if (!set.contains(v)) {
      if (set.size == k)
        set.remove(pq.dequeue._2)
      set.add(v)
      ans += 1
    }
    addToPQ(i, v)
  }

  println(ans)
}


Given two integers $$$n$$$ and $$$x$$$, construct an array that satisfies the following conditions:   for any element $$$a_i$$$ in the array, $$$1 \le a_i<2^n$$$;  there is no non-empty subsegment with bitwise XOR equal to $$$0$$$ or $$$x$$$,  its length $$$l$$$ should be maximized. A sequence $$$b$$$ is a subsegment of a sequence $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The only line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 18$$$, $$$1 \le x<2^{18}$$$).

The first line should contain the length of the array $$$l$$$. If $$$l$$$ is positive, the second line should contain $$$l$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\dots$$$, $$$a_l$$$ ($$$1 \le a_i < 2^n$$$) — the elements of the array $$$a$$$. If there are multiple solutions, print any of them.

NoteIn the first example, the bitwise XOR of the subsegments are $$$\{6,7,4,1,2,3\}$$$.

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

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

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

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

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

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

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, X = ni()
    val cum = ArrayBuffer[Int]()
    cum += 0
    val used = Array.ofDim[Boolean](1 << 18)
    TO(1, (1 << N) - 1) { i =>
      if (!used(X^i) && i != X) {
        used(i) = true
        cum += i
      }
    }
    debug(cum.mkString(" "))

    val ans = Array.ofDim[Int](cum.length - 1)
    REP(ans.length) { i =>
      ans(i) = cum(i + 1) ^ cum(i)
    }
    out.println(ans.length)
    out.println(ans.mkString(" "))
  }
}


Phoenix has collected $$$n$$$ pieces of gold, and he wants to weigh them together so he can feel rich. The $$$i$$$-th piece of gold has weight $$$w_i$$$. All weights are distinct. He will put his $$$n$$$ pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly $$$x$$$, it will explode. Can he put all $$$n$$$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array $$$w$$$ so that for each $$$i$$$ $$$(1 \le i \le n)$$$, $$$\sum\limits_{j = 1}^{i}w_j \ne x$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$; $$$1 \le x \le 10^4$$$) — the number of gold pieces that Phoenix has and the weight to avoid, respectively.  The second line of each test case contains $$$n$$$ space-separated integers $$$(1 \le w_i \le 100)$$$ — the weights of the gold pieces. It is guaranteed that the weights are pairwise distinct.

For each test case, if Phoenix cannot place all $$$n$$$ pieces without the scale exploding, print NO. Otherwise, print YES followed by the rearranged array $$$w$$$. If there are multiple solutions, print any.

NoteIn the first test case, Phoenix puts the gold piece with weight $$$3$$$ on the scale first, then the piece with weight $$$2$$$, and finally the piece with weight $$$1$$$. The total weight on the scale is $$$3$$$, then $$$5$$$, then $$$6$$$. The scale does not explode because the total weight on the scale is never $$$2$$$.In the second test case, the total weight on the scale is $$$8$$$, $$$9$$$, $$$11$$$, $$$14$$$, then $$$18$$$. It is never $$$3$$$.In the third test case, Phoenix must put the gold piece with weight $$$5$$$ on the scale, and the scale will always explode.

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

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val ws = nextInts(n)

      var sum = 0
      val res = Array.ofDim[Int](n)
      var ok = true
      var i = 0
      while (i < n) {
        if (sum + ws(i) == x) {
          if (i == n - 1) {
            ok = false
            i = n
          } else {
            res(i) = i + 1
            res(i + 1) = i
            sum += ws(i)
            sum += ws(i + 1)
            i += 2
          }
        } else {
          res(i) = i
          sum += ws(i)
          i += 1
        }
      }

      if (ok) {
        out.println("YES")
        out.println(res.map(ws).mkString(" "))
      } else {
        out.println("NO")
      }
    }

    out.flush()
  }

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


Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly $$$\ell$$$ letters long. So, the scientists decided to write each word of this language as an integer from $$$0$$$ to $$$2^{\ell} - 1$$$ inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.The same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.Denote the distance between two words as the amount of positions, in which these words differ. For example, the distance between $$$1001_2$$$ and $$$1100_2$$$ (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words $$$x$$$ and $$$y$$$ as $$$d(x, y)$$$.Let the word have $$$n$$$ forms, the $$$i$$$-th of which is described with an integer $$$x_i$$$. All the $$$x_i$$$ are not necessarily different, as two various forms of the word can be written the same. Consider some word $$$y$$$. Then, closeness of the word $$$y$$$ is equal to the sum of distances to each of the word forms, i. e. the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$.The initial form is the word $$$y$$$ with minimal possible nearness.You need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is not necessarily equal to any of the $$$n$$$ given forms.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following are descriptions of the test cases. The first line contains two integers $$$n$$$ and $$$\ell$$$ ($$$1 \le n \le 100$$$, $$$1 \le \ell \le 30$$$) — the amount of word forms, and the number of letters in one word. The second line contains $$$n$$$ integers $$$x_i$$$ ($$$0 \le x_i \le 2^\ell - 1$$$) — word forms. The integers are not necessarily different.

For each test, print a single integer, the initial form of the word, i. e. such $$$y$$$ ($$$0 \le y \le 2^\ell - 1$$$) that the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$ is minimal possible. Note that $$$y$$$ can differ from all the integers $$$x_i$$$. If there are multiple ways to restore the initial form, print any.

NoteIn the first test case, the words can be written as $$$x_1 = 10010_2$$$, $$$x_2 = 01001_2$$$ and $$$x_3 = 10101_2$$$ in binary. Let $$$y = 10001_2$$$. Then, $$$d(x_1, y) = 2$$$ (the difference is in the fourth and the fifth positions), $$$d(x_2, y) = 2$$$ (the difference is in the first and the second positions), $$$d(x_3, y) = 1$$$ (the difference is in the third position). So, the closeness is $$$2 + 2 + 1 = 5$$$. It can be shown that you cannot achieve smaller closeness.In the second test case, all the forms are equal to $$$18$$$ ($$$10010_2$$$ in binary), so the initial form is also $$$18$$$. It's easy to see that closeness is equal to zero in this case.

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val l: Int, val r: Int, val c: Long)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (r-l).compareTo(that.r-that.l)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val k = readInt()
        val arr = new Array[Int](n+1)
        val cnt = new Array[Int](35)
        for (i <-  0 to 30) {
            cnt(i) = 0
        }
        for (i <- 1 to n) {
            arr(i) = readInt()
            var po = 0
            while (arr(i) > 0) {
                if (arr(i) % 2 == 1) {
                    cnt(po) += 1
                }
                arr(i) /= 2
                po += 1
            }
        }
        var ans = 0L
        for (i <- (0 to 29).reverse) {
            if (cnt(i) >= n-cnt(i)) {
                ans += 1L
            }
            if (i > 0)
                ans *= 2L
        }
        writer.println(ans)

        def check(kk: Long): Boolean = {
            return true
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}