A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?

The first line of the input contains integer n (3 ≤ n ≤ 105) — the initial number of compilation errors. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the errors the compiler displayed for the first time.  The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 — the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one.  The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 — the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.

Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.

NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.

import java.io._

object Main {

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

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val a = in.readLine().split(" +").map(_.toInt)
    val b = in.readLine().split(" +").map(_.toInt)
    val c = in.readLine().split(" +").map(_.toInt)

    out.println((a diff b)(0))
    out.println((b diff c)(0))

    out.close()
  }

}

import scala.io.StdIn

object Main extends App {
	StdIn.readLine()

	lazy val errors: Array[Int] = StdIn.readLine().split(" ").map(_.toInt)
	lazy val fix1 = StdIn.readLine().split(" ").map(_.toInt)
	lazy val fix2 = StdIn.readLine().split(" ").map(_.toInt)

	(errors.diff(fix1).head, fix1.diff(fix2).head) match {
		case (bug1, bug2) => println(s"$bug1\n$bug2")
	}
}

object B519 {
  @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 = readInts(n)
    val input1 = readInts(n-1)
    val input2 = readInts(n-2)
    println(input.diff(input1)(0))
    println(input1.diff(input2)(0))
  }
}

import scala.io.StdIn

object A extends App {

  val n = StdIn.readInt()
  val f = StdIn.readLine().split(" ").map(_.toInt)
  val s = StdIn.readLine().split(" ").map(_.toInt)
  val t = StdIn.readLine().split(" ").map(_.toInt)
  val e1 = f diff s
  val e2 = s diff t
  println(e1.head)
  println(e2.head)

}

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

import scala.collection.mutable

object B {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val a = new mutable.HashMap[Int, Int]()
    for (i <- 0 until n) {
      val int = nextInt
      val x = a.getOrElse(int, 0)
      a.put(int, x + 1)
    }
    val b = new mutable.HashMap[Int, Int]()
    for (i <- 0 until n - 1) {
      val int = nextInt
      val x = b.getOrElse(int, 0)
      b.put(int, x + 1)
    }
    val c = new mutable.HashMap[Int, Int]()
    for (i <- 0 until n - 2) {
      val int = nextInt
      val x = c.getOrElse(int, 0)
      c.put(int, x + 1)
    }
    val list1 = b.toIterator
    while(list1.hasNext) {
      val l1 = list1.next()
      val x = l1._1
      for (j <- 0 until l1._2) {
        val v = a.getOrElse(x, 0)
        a.remove(x)
        if (v - 1 > 0) {
          a.put(x, v - 1)
        }
      }
    }
    val list2 = c.toIterator
    while(list2.hasNext) {
      val l1 = list2.next()
      val x = l1._1
      for (j <- 0 until l1._2) {
        val v = b.getOrElse(x, 0)
        b.remove(x)
        if (v - 1 > 0) {
          b.put(x, v - 1)
        }
      }
    }
    out.println(a.toList.head._1)
    out.println(b.toList.head._1)
    return 1
  }

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

import scala.io.StdIn._

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

  val answer1 = A.diff(B)(0)
  val diff = A.diff(C)
  val answer2 = if (diff(0) !=  answer1) diff(0) else diff(1)

  println(answer1)
  println(answer2)
}

import scala.collection.mutable.HashMap

object CompilationErrors{
    def main(args : Array[String]){
        var n : String = readLine
        var one : Array[Int] = readLine.split(" ").map(_.toInt)
        var two : Array[Int] = readLine.split(" ").map(_.toInt)
        var three : Array[Int] = readLine.split(" ").map(_.toInt)
        (one diff two).foreach(println)
        (two diff three).foreach(print)
    }
}

object Main extends App {

   def diff(a: List[Long], b: List[Long]): Long = (a zip b :+ 0L).dropWhile({ case (a1, b1) => a1 == b1 }).head._1

   readLong
   val a = readLine.split(" ").filterNot(_ == "").map(_.toLong).toList.sorted
   val b = readLine.split(" ").filterNot(_ == "").map(_.toLong).toList.sorted
   val c = readLine.split(" ").filterNot(_ == "").map(_.toLong).toList.sorted

   println(diff(a,b))
   println(diff(b,c))

}

import scala.io.Source

/**
 * Created by kgribov on 05/03/15.
 */
object Problem519B {
  def main(args: Array[String]) {
    val lines = Source.stdin.getLines();
    lines.next()
    val linesNumber = 3
    val arr = new Array[Int](linesNumber)

    for (a <- 0 until linesNumber) {
      for (st <- lines.next().split(" ")) {
        arr(a) += Integer.parseInt(st)
      }
    }
    println(arr(0) - arr(1))
    println(arr(1) - arr(2))
  }
}

import scala.io.StdIn._

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

  val answer1 = A.diff(B) mkString " "
  val answer2 = A.diff(C) filterNot (_ == answer1.toInt) mkString " "
  println(answer1)
  println(answer2)
}


Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.

The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a1, a2, ..., an, where ai is 0 if the cow number i is facing left, and 1 if it is facing right.

Print a single integer, the minimum amount of lost milk. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost.

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) >> 1
		build(v << 1, tl, tm)
		build((v << 1) + 1, tm + 1, tr)
		t(v) = t(v << 1) + t((v << 1) + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) >> 1
    	  query(l, Math.min(r, tm), v << 1, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, (v << 1) + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) >> 1
		  if (pos <= tm) update(pos, newVal, v << 1, tl, tm)
		  else update(pos, newVal, (v << 1) + 1, tm + 1, tr)
		  t(v) = t(v << 1) + t((v << 1) + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree(as)
  val rightST = SegTree(as.map(a => 1 - a))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i - 1, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) / 2
		build(v * 2, tl, tm)
		build(v * 2 + 1, tm + 1, tr)
		t(v) = t(v * 2) + t(v * 2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) / 2
    	  query(l, Math.min(r, tm), v * 2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) / 2
		  if (pos <= tm) update(pos, newVal, v * 2, tl, tm)
		  else update(pos, newVal, v * 2 + 1, tm + 1, tr)
		  t(v) = t(v * 2) + t(v * 2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree((0 +: as).take(n))
  val rightST = SegTree(((as.map(a => (1 - a)) :+ 0)).take(n))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) / 2
		build(v * 2, tl, tm)
		build(v * 2 + 1, tm + 1, tr)
		t(v) = t(v * 2) + t(v * 2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) / 2
    	  query(l, Math.min(r, tm), v * 2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) / 2
		  if (pos <= tm) update(pos, newVal, v * 2, tl, tm)
		  else update(pos, newVal, v * 2 + 1, tm + 1, tr)
		  t(v) = t(v * 2) + t(v * 2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree(as)
  val rightST = SegTree(as.map(a => 1 - a))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i - 1, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) >> 1
		val v2 = v << 1
		build(v2, tl, tm)
		build(v2 + 1, tm + 1, tr)
		t(v) = t(v2) + t(v2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) >> 1
    	  val v2 = v << 1
    	  query(l, Math.min(r, tm), v2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) >> 1
		  val v2 = v << 1
		  if (pos <= tm) update(pos, newVal, v2, tl, tm)
		  else update(pos, newVal, v2 + 1, tm + 1, tr)
		  t(v) = t(v2) + t(v2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree(as)
  val rightST = SegTree(as.map(a => 1 - a))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i - 1, -1)
  }

  println(sum)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Please hack me if you can!
 */
import scala.collection._

object A extends App {

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

  object BIT {

    def query(t: Array[Int], r: Int, acc: Int = 0): Int =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def update(t: Array[Int], i: Int, delta: Int): Unit =
      if (i < t.length && i >= 0) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Int]): Array[Int] = {
      val t = Array.fill(src.length) { 0 }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftBIT = BIT((0 +: as).take(n))
  val rightBIT = BIT((0 +: (as.map(a => (1 - a)).reverse)).take(n))

  var sum = 0L
  for (i <- order) {
    sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)
    if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)
    else BIT.update(leftBIT, i, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) >> 1
		val v2 = v << 1
		build(v2, tl, tm)
		build(v2 + 1, tm + 1, tr)
		t(v) = t(v2) + t(v2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) >> 1
    	  val v2 = v << 1
    	  query(l, Math.min(r, tm), v2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) >> 1
		  val v2 = v << 1
		  if (pos <= tm) update(pos, newVal, v2, tl, tm)
		  else update(pos, newVal, v2 + 1, tm + 1, tr)
		  t(v) = t(v2) + t(v2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree(as)
  val rightST = SegTree(as.map(a => 1 - a))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i - 1) + rightST.query(i + 1, n - 1)
    if (as(i) == 0) rightST.update(i + 1, -1)
    else leftST.update(i - 1, -1)
  }

  println(sum)
}

import scala.collection._

object A extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * as.length)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) / 2
		build(v * 2, tl, tm)
		build(v * 2 + 1, tm + 1, tr)
		t(v) = t(v * 2) + t(v * 2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
    	if (l > r) 0
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) / 2
    	  query(l, Math.min(r, tm), v * 2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v * 2 + 1, tm + 1, tr)
    	}
    }

    def update(pos: Int, newVal: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
    	if (tl == tr) t(v) += newVal
        else {
		  val tm = (tl + tr) / 2
		  if (pos <= tm) update(pos, newVal, v * 2, tl, tm)
		  else update(pos, newVal, v * 2 + 1, tm + 1, tr)
		  t(v) = t(v * 2) + t(v * 2 + 1)
        }
	}

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftST = SegTree((0 +: as).take(n))
  val rightST = SegTree((0 +: (as.map(a => (1 - a)).reverse)).take(n))

  var sum = 0L
  for (i <- order) {
    sum = sum + leftST.query(0, i) + rightST.query(0, n - i - 1)
    if (as(i) == 0) rightST.update(n - i - 1, -1)
    else leftST.update(i, -1)
  }

  println(sum)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Please hack me if you can!
 */
import scala.collection._

object A extends App {

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

  object BIT {

    def query(t: Array[Int], r: Int, acc: Int = 0): Int =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def update(t: Array[Int], i: Int, delta: Int): Unit =
      if (i < t.length && i >= 0) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Byte]): Array[Int] = {
      val t = Array.fill(src.length) { 0 }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftBIT = BIT((0.toByte +: as).take(n))
  val rightBIT = BIT((0.toByte +: (as.map(a => (1 - a).toByte).reverse)).take(n))

  var sum = 0
  for (i <- order) {
    sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)
    if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)
    else BIT.update(leftBIT, i, -1)
  }

  println(sum)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Please hack me if you can!
 */
import scala.collection._

object A extends App {

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

  object BIT {

    def query(t: Array[Int], r: Int, acc: Int = 0): Int =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def update(t: Array[Int], i: Int, delta: Int): Unit =
      if (i < t.length && i >= 0) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(src: Array[Int]): Array[Int] = {
      val t = Array.fill(src.length) { 0 }
      for (i <- src.indices) update(t, i, src(i))
      t
    }

  }

  val n = readInt
  val as = readInts(n)

  val sees = Array.tabulate(n){ i => (if (as(i) == 0) i else n - i - 1, i) }

  val order = sees.sortBy(- _._1).map(_._2)

  val leftBIT = BIT((0 +: as).take(n))
  val rightBIT = BIT((0 +: (as.map(a => (1 - a)).reverse)).take(n))

  var sum = 0
  for (i <- order) {
    sum = sum + BIT.query(leftBIT, i) + BIT.query(rightBIT, n - i - 1)
    if (as(i) == 0) BIT.update(rightBIT, n - i - 1, -1)
    else BIT.update(leftBIT, i, -1)
  }

  println(sum)
}


Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.

The first line contains three integers n, m, k (1 ≤ n, m ≤ 500, 0 ≤ k < s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze. Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall.

Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#"). It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.

object A extends App {

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

  val Array(n, m, k) = readInts(3)
  val as = Array.fill(n)(readLine.toCharArray)
  val color = Array.fill(n, m)(0.toByte)

  def dfs(i: Int, j: Int, _toAdd: Int): Int = {

    if (color(i)(j) == 1 || _toAdd == 0 || as(i)(j) != '.') {
      _toAdd
    } else {
      color(i)(j) = 1
      var toAdd = _toAdd
      if (i > 0) toAdd = dfs(i - 1, j, toAdd)
      if (i < n - 1) toAdd = dfs(i + 1, j, toAdd)
      if (j > 0) toAdd = dfs(i, j - 1, toAdd)
      if (j < m - 1) toAdd = dfs(i, j + 1, toAdd)
      color(i)(j) = 2
      if (toAdd > 0) {
        as(i)(j) = 'X'
        toAdd -= 1
      }
      toAdd
    }
  }

  var i0, j0 = -1

  for (i <- 0 until n; j <- 0 until m) if (as(i)(j) == '.') {
    i0 = i; j0 = j
  }

  if (i0 >= 0) dfs(i0, j0, k)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  for (a <- as) println(a.mkString(""))
  Console.flush
}


William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet.

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$.

Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions.

NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people.

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 a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * b.compareTo(that.b)
        }
    }

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

    val t = 1//readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val k = readInt()
        val sz = new Array[Int](n+1)
        val par = new Array[Int](n+1)
        val mark = new Array[Boolean](n+1)

        def father(v: Int): Int = {
            if (par(v) == 0)
                return v
            par(v) = father(par(v))
            return par(v)
        }
        def merge(a: Int, b:Int): Unit = {
            val v = father(a)
            val u = father(b)
            if (v == u)
                return
            if (sz(v) >= sz(u)) {
                par(u) = v
                sz(v) += sz(u)
            } else {
                par(v) = u
                sz(u) += sz(v)
            }
        }

        var sum = 0
        var ans = 0
        for (i <- 1 to n)
            sz(i) = 1
        var a = 0
        var b = 0
        for (i <- 1 to k) {
            sum = 0
            for (j <- 1 to n)
                mark(j) = false
            a = readInt()
            b = readInt()
            merge(a, b)
            a = father(a)
            var comp = Vector[pair]()
            for (j <- 1 to n) {
                b = father(j)
                if (!mark(b)) {
                    mark(b) = true
                    comp :+= pair(b, sz(b))
                    sum += sz(b) - 1
                }
            }
            comp = comp.sorted
            ans = sz(comp(0).a) - 1
            for (i <- 1 to i-sum) {
                ans += sz(comp(i).a)
            }
            writer.println(ans)
        }

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


Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c1 + c2·(x - 1)2 (in particular, if the group consists of one person, then the price is c1). All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group.

The first line contains three integers n, c1 and c2 (1 ≤ n ≤ 200 000, 1 ≤ c1, c2 ≤ 107) — the number of visitors and parameters for determining the ticket prices for a group. The second line contains the string of length n, which consists of zeros and ones. If the i-th symbol of the string is zero, then the i-th visitor is a pupil, otherwise the i-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils.

Print the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once.

NoteIn the first test one group of three people should go to the attraction. Then they have to pay 4 + 1 * (3 - 1)2 = 8.In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7 + 2 * (2 - 1)2 = 9. Thus, the total price for two groups is 18.

object Main extends App {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    val a, b = sc.nextLong()
    val s = sc.next()
    var cnt = 0
    for (i <- 0 to n - 1) {
        if (s.charAt(i) == '1') cnt = cnt + 1
    }

    var ans = 1e18.toLong
    for (i <- 1 to cnt) {
        var t1 = (n / i).toLong
        var t2 = (n % i).toLong
        // println(t1 + " " + t2)
        var x1 = (a + b * (t1 - 1) * (t1 - 1)) * (i - t2)
        var x2 = (a + b * t1 * t1) * t2
        if (ans > x1 + x2) ans = x1 + x2
    }
    print(ans)
}

object Main extends App {
    val sc = new java.util.Scanner(System.in)
    val n, a, b = sc.nextInt()
    val s = sc.next()
    var cnt = 0
    for (i <- 0 to n - 1) {
        if (s.charAt(i) == '1') cnt = cnt + 1
    }

    var ans = 1e18.toLong
    for (i <- 1 to cnt) {
        var t1 = n / i
        var t2 = n % i
        // println(t1 + " " + t2)
        var x1 = (a + b * (t1 - 1) * (t1 - 1)).toLong * (i - t2)
        var x2 = (a + b * t1 * t1).toLong * t2
        if (ans > x1 + x2) ans = x1 + x2
    }
    print(ans)
}


Andrew has $$$n$$$ piles with stones. The $$$i$$$-th pile contains $$$a_i$$$ stones. He wants to make his table clean so he decided to put every stone either to the $$$1$$$-st or the $$$n$$$-th pile.Andrew can perform the following operation any number of times: choose $$$3$$$ indices $$$1 \le i < j < k \le n$$$, such that the $$$j$$$-th pile contains at least $$$2$$$ stones, then he takes $$$2$$$ stones from the pile $$$j$$$ and puts one stone into pile $$$i$$$ and one stone into pile $$$k$$$. Tell Andrew what is the minimum number of operations needed to move all the stones to piles $$$1$$$ and $$$n$$$, or determine if it's impossible.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 10^5$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the minimum number of operations needed to move stones to piles $$$1$$$ and $$$n$$$, or print $$$-1$$$ if it's impossible.

NoteIn the first test case, it is optimal to do the following:   Select $$$(i, j, k) = (1, 2, 5)$$$. The array becomes equal to $$$[2, 0, 2, 3, 7]$$$.  Select $$$(i, j, k) = (1, 3, 4)$$$. The array becomes equal to $$$[3, 0, 0, 4, 7]$$$.  Twice select $$$(i, j, k) = (1, 4, 5)$$$. The array becomes equal to $$$[5, 0, 0, 0, 9]$$$. This array satisfy the statement, because every stone is moved to piles $$$1$$$ and $$$5$$$.  There are $$$4$$$ operations in total.In the second test case, it's impossible to put all stones into piles with numbers $$$1$$$ and $$$3$$$:   At the beginning there's only one possible operation with $$$(i, j, k) = (1, 2, 3)$$$. The array becomes equal to $$$[2, 1, 2]$$$.  Now there is no possible operation and the array doesn't satisfy the statement, so the answer is $$$-1$$$. In the third test case, it's optimal to do the following:   Select $$$(i, j, k) = (1, 2, 3)$$$. The array becomes equal to $$$[2, 0, 2]$$$. This array satisfies the statement, because every stone is moved to piles $$$1$$$ and $$$3$$$.  The is $$$1$$$ operation in total.In the fourth test case, it's impossible to do any operation, and the array doesn't satisfy the statement, so the answer is $$$-1$$$.

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
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 testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val size = readInt()
    val a = readLongs()
    val medium = a.slice(1, size - 1)
    val answer: Long = if (medium.count(_ == 1) == medium.length ||
      (medium.length == 1 && medium.head % 2 == 1)) {
      -1
    } else {
      val removeOneCount = medium.count(_ % 2 == 1)
      (medium.sum + removeOneCount) / 2
    }
    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 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
    }
  }
}


Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 ≤ p < |s|) and perform one of the following actions:   either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it;  or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it. Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed.Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations.Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7).

The input data contains several tests. The first line contains the only integer t (1 ≤ t ≤ 104) — the number of tests. Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ.

For each word you should print the number of different other words that coincide with it in their meaning — not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7).

NoteSome explanations about the operation:  Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y".  Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b".  Note that the operation never changes a word's length. In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0.Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b"  →  "c"), and the fifth one — with the preceding one ("f"  →  "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb". Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants — there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 — the number 3320092814 modulo 109 + 7

//package round110.div1

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 03.03.12
 * Time: 12:16
 * To change this template use File | Settings | File Templates.
 */

object C {

  import math.{min, max}

  val mod = 1000000007

  def count(s: String): Int =
    (nums(s.length - 1)(s map (c => c - 'a') sum) - 1) % mod toInt

  val nums = Array.ofDim[Array[Long]](101)
  nums(0) = Array.fill(26)(1L)
  for (i <- 1 to 100) nums(i) = nums(i - 1) next

  def main(args: Array[String]) = (1 to readInt) foreach (_ => println(count(readLine)))

  class Result(val data: Array[Long]) {
    override def toString = "Result(" + data.mkString(",") + ")"

    def next = {
      val result = Array.ofDim[Long](data.length + 25)
      for (i <- 0 until result.length) {
        for (j <- max(0, i - 25) to min(data.length - 1, i)
        ) result(i) += data(j)
        result(i) %= mod
      }
      result
    }
  }

  implicit def toResult(array: Array[Long]): Result = new Result(array)

}


Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.

The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ min(100 000, n2)) — the size of the board and the number of rooks.  Each of the next m lines contains integers xi and yi (1 ≤ xi, yi ≤ n) — the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.

Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.

NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val Array(n, m) = lines.next().split(' ').map(_.toInt)
  val xaxis = Array.ofDim[Boolean](n)
  val yaxis = Array.ofDim[Boolean](n)
  var xLeft: Long = n
  var yLeft: Long = n

  println(lines.take(m).map { _.split(' ').map(_.toInt - 1)}.map {
    case Array(x, y) =>
      if (!xaxis(x)) xLeft -= 1
      if (!yaxis(y)) yLeft -= 1
      xaxis(x) = true
      yaxis(y) = true
      xLeft * yLeft
  }.mkString(" "))

}

object B701 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val row = Array.fill(n)(false)
    val col = Array.fill(n)(false)
    val res = Array.fill(m)(0L)
    var R = 0L
    var C = 0L
    for(q <- 0 until m ) {
      val Array(r, c)= readInts(2)
      if(!row(r-1)) {
        row(r-1) = true
        R += 1
      }
      if(!col(c-1)) {
        col(c-1) = true
        C += 1
      }
      res(q) = (n-R)*(n-C)
    }

    println(res.mkString(" "))
  }

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

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

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

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

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

}

import scala.collection.mutable.BitSet

//package b

object B extends App {

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

  val Array(n, m) = readInts(2)

  var freeCols, freeRows = n
  var remain = n.toLong * n
  val res = Array.ofDim[Long](m)

  val row, col = new BitSet(n)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    if (!row(y) && !col(x)) {
      remain -= (freeCols + freeRows - 1)
      freeCols -= 1
      freeRows -= 1
    } else if (!row(y)) {
      remain -= freeCols
      freeRows -= 1
    } else if (!col(x)) {
      remain -= freeRows
      freeCols -= 1
    }

    res(i) = remain
    row += y
    col += x
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}

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

object _701B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val (n, m) = read[(Long, Int)]
    val rows, cols = mutable.Set.empty[Int]
    repeat(m) {
      val r, c = read[Int]
      rows += r
      cols += c
      val ans: Long = (n - rows.size)*(n - cols.size)
      write(ans, "")
    }
    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def until(until: Int): Range = 0 until until
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt(); val m = sc.nextInt()

    val dpx = new Array[Boolean](n+1)
    val dpy = new Array[Boolean](n+1)

    var xw = n
    var yw = n

    for(k <- 1 to m){
      val y = sc.nextInt(); val x = sc.nextInt()

      if(!dpx(x)){
        dpx(x) = true
        xw -= 1
      }

      if(!dpy(y)){
        dpy(y) = true
        yw -= 1
      }

      if(k == m)
        println(xw * yw.toLong)
      else
        print(xw * yw.toLong + " ")
    }
  }
}

import scala.collection.mutable.BitSet

//package b

object B extends App {

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

  val Array(n, m) = readInts(2)

  var freeCols, freeRows = n
  var remain = n.toLong * n
  val res = Array.ofDim[Long](m)

  val row, col = new BitSet(n)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    if (!row(y) && !col(y)) {
      remain -= (freeCols + freeRows - 1)
      freeCols -= 1
      freeRows -= 1
    } else if (!row(y)) {
      remain -= freeCols
      freeRows -= 1
    } else if (!col(x)) {
      remain -= freeRows
      freeCols -= 1
    }

    res(i) = remain
    row += y
    col += x
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}

import scala.collection.mutable.BitSet

//package b

object B extends App {

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

  val Array(n, m) = readInts(2)

  var freeCols, freeRows = n
  var remain = n.toLong * n
  val res = Array.ofDim[Long](m)

  val row, col = new BitSet(n)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    if (!row(y) && !col(y)) {
      remain -= (freeCols + freeRows - 1)
      freeCols -= 1
      freeRows -= 1
    } else if (!row(y)) {
      remain -= freeCols
      freeRows -= 1
    } else if (!col(x)) {
      remain -= freeRows
      freeCols -= 1
    }

    res(i) = remain
    row += y
    col += y
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}


Tomorrow is a difficult day for Polycarp: he has to attend $$$a$$$ lectures and $$$b$$$ practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down $$$c$$$ lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during $$$d$$$ practical classes, after which it is unusable.Polycarp's pencilcase can hold no more than $$$k$$$ writing implements, so if Polycarp wants to take $$$x$$$ pens and $$$y$$$ pencils, they will fit in the pencilcase if and only if $$$x + y \le k$$$.Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!Note that you don't have to minimize the number of writing implements (though their total number must not exceed $$$k$$$).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow. Each test case is described by one line containing five integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ and $$$k$$$, separated by spaces ($$$1 \le a, b, c, d, k \le 100$$$) — the number of lectures Polycarp has to attend, the number of practical classes Polycarp has to attend, the number of lectures which can be written down using one pen, the number of practical classes for which one pencil is enough, and the number of writing implements that can fit into Polycarp's pencilcase, respectively. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.

For each test case, print the answer as follows: If the pencilcase can't hold enough writing implements to use them during all lectures and practical classes, print one integer $$$-1$$$. Otherwise, print two non-negative integers $$$x$$$ and $$$y$$$ — the number of pens and pencils Polycarp should put in his pencilcase. If there are multiple answers, print any of them. Note that you don't have to minimize the number of writing implements (though their total number must not exceed $$$k$$$).

NoteThere are many different answers for the first test case; $$$x = 7$$$, $$$y = 1$$$ is only one of them. For example, $$$x = 3$$$, $$$y = 1$$$ is also correct.$$$x = 1$$$, $$$y = 3$$$ is the only correct answer for the third test case.

//package codeforces.contest1244

object PensAndPencils {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val Array(lectures, practicals, lRate, pRate, limit) =
        io.StdIn.readLine.split(" ").map(_.toInt)

      val pensRequired = (lectures + (if (lectures % lRate == 0) 0 else lRate)) / lRate
      val pencilsRequired = (practicals + (if (practicals % pRate == 0) 0 else pRate)) / pRate

      if (pensRequired + pencilsRequired <= limit)
        println(s"$pensRequired $pencilsRequired")
      else
        println(-1)

    }
  }

}

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

  val t = nextInt

  for (_ <- 1 to t) {
    val a, b, c, d, k = nextInt
    val aa = (a + c - 1) / c
    val bb = (b + d - 1) / d
    if (aa + bb <= k) out.println(s"$aa $bb")
    else out.println(-1)
    out.flush()
  }

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


Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers $$$(a, b)$$$ exist, where $$$1 \leq a, b \leq n$$$, for which $$$\frac{\operatorname{lcm}(a, b)}{\operatorname{gcd}(a, b)} \leq 3$$$.In this problem, $$$\operatorname{gcd}(a, b)$$$ denotes the greatest common divisor of the numbers $$$a$$$ and $$$b$$$, and $$$\operatorname{lcm}(a, b)$$$ denotes the smallest common multiple of the numbers $$$a$$$ and $$$b$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $$$n$$$ ($$$1 \le n \le 10^8$$$).

For each test case output a single integer — the number of pairs of integers satisfying the condition.

NoteFor $$$n = 1$$$ there is exactly one pair of numbers — $$$(1, 1)$$$ and it fits.For $$$n = 2$$$, there are only $$$4$$$ pairs — $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$ and they all fit.For $$$n = 3$$$, all $$$9$$$ pair are suitable, except $$$(2, 3)$$$ and $$$(3, 2)$$$, since their $$$\operatorname{lcm}$$$ is $$$6$$$, and $$$\operatorname{gcd}$$$ is $$$1$$$, which doesn't fit the condition.

object _1717A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int]
    val ans = n + 2*(n/2) + 2*(n/3)
    io.writeLine(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Utils]****************************************/
object Utils {
  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


You are given a string $$$s$$$. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ lines follow, each representing a test case. Each line contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$); each character of $$$s$$$ is either 0 or 1.

Print $$$t$$$ integers, where the $$$i$$$-th integer is the answer to the $$$i$$$-th testcase (the minimum number of 0's that you have to erase from $$$s$$$).

NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

import scala.io.StdIn

object Zeros extends App {

  private val operate: String => Int =
    str => {
      val from = str.indexOf('1')
      val to = str.lastIndexOf('1')
      getCount(str.substring(from, to))
    }

  private val getCount: String => Int =
    str => str count (_ == '0')

  var n: Int = StdIn.readLine().toInt

  while (n != 0) {
    val line: String = StdIn.readLine()
    if (line.contains('1')) println(operate(line)) else println(0)
    n -= 1
  }

}

object _1303A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val t = io.read[String]
    val ans = for {
      i <- Option(t.indexOf('1')) if i >= 0
      j <- Option(t.lastIndexOf('1')) if j > i
      o = t.substring(i, j)
    } yield o.count(_ == '0')
    io.write(ans.getOrElse(0))
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import java.io.PrintWriter
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString(): String = reader.readLine()

    def multiTest(f: () => Unit): Unit = {
        var t = readInt()
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        val s = readString()
        var l = 0
        while (l < s.length && s(l) == '0') l += 1

        var r = s.length - 1
        while (r > 0 && s(r) == '0') r -= 1

        var rs = 0
        while (l <= r) {
            if (s(l) == '0') rs += 1
            l += 1
        }
        println(rs)
    }

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


Nastia has $$$2$$$ positive integers $$$A$$$ and $$$B$$$. She defines that:  The integer is good if it is divisible by $$$A \cdot B$$$;  Otherwise, the integer is nearly good, if it is divisible by $$$A$$$. For example, if $$$A = 6$$$ and $$$B = 4$$$, the integers $$$24$$$ and $$$72$$$ are good, the integers $$$6$$$, $$$660$$$ and $$$12$$$ are nearly good, the integers $$$16$$$, $$$7$$$ are neither good nor nearly good.Find $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains two integers $$$A$$$ and $$$B$$$ ($$$1 \le A \le 10^6$$$, $$$1 \le B \le 10^6$$$) — numbers that Nastia has.

For each test case print:    "YES" and $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$.  "NO" if no answer exists.  YES NO If there are multiple answers, print any.

NoteIn the first test case: $$$60$$$ — good number; $$$10$$$ and $$$50$$$ — nearly good numbers.In the second test case: $$$208$$$ — good number; $$$169$$$ and $$$39$$$ — nearly good numbers.In the third test case: $$$154$$$ — good number; $$$28$$$ and $$$182$$$ — nearly good numbers.

object testing {
  def main(args: Array[String]): Unit = {
    val T = readLine().toInt;
    for(i <- 1 to T){
      val s = readLine().split(" ");
      val A = s(0).toLong;
      val B = s(1).toLong;
      if(B == 1){
        println("NO");
      }else {
        println("YES");
        println(A + " " + A * (2 * B - 1) + " " + (2 * A * B));
      }
    }
  }
}

object testing {
  def main(args: Array[String]): Unit = {
    val T = readLine().toInt;
    for(i <- 1 to T){
      val s = readLine().split(" ");
      val A = s(0).toInt;
      val B = s(1).toInt;
      if(B == 1){
        println("NO");
      }else {
        println("YES");
        println(A + " " + A * (2 * B - 1) + " " + (2 * A * B));
      }
    }
  }
}

object testing {
  def main(args: Array[String]): Unit = {
    val T = readLine().toInt;
    for(i <- 1 to T){
      val s = readLine().split(" ");
      val A = s(0).toInt;
      val B = s(1).toInt;
      if(B == 1){
        println("NO");
      }else {
        println("YES");
        println(A + " " + A * (B - 1) + " " + (A * B));
      }
    }
  }
}

object testing {
  def main(args: Array[String]): Unit = {
    val T = readLine().toInt;
    for(i <- 1 to T){
      val s = readLine().split(" ");
      val A = s(0).toInt;
      val B = s(1).toInt;
      if(B == 1){
        println("NO");
      }else {
        println("YES");
        println((A * B) + " " + A + " " + A * (B - 1));
      }
    }
  }
}


You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step:  either you can select any blue element and decrease its value by $$$1$$$;  or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).

NoteIn the first test case of the example, the following sequence of moves can be performed:  choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$;  choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$;  choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$;  choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.

object _1607D extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val values = io.read[Vector[Int]]
    val colors = io.read[String]

    val arr = colors.zip(values).toMultiMap.mapValues(_.sorted).withDefaultValue(Vector.empty)

    val blues = arr('B')
    var bi = -1

    val reds = arr('R')
    var ri = -1

    def findRed(x: Int) =
      ((ri + 1) until reds.length)
        .find(i => reds(i) <= x)
        .map({i => ri = i; i})

    def findBlue(x: Int) =
      ((bi + 1) until blues.length)
        .find(i => x <= blues(i))
        .map({i => bi = i; i})

    def find(x: Int) = findBlue(x).orElse(findRed(x)).nonEmpty

    val ans = (1 to values.length).forall(find)

    io.write(ans.toEnglish.toUpperCase)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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(var value: Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return value.compareTo(that.value)
        }
    }

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

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n)
        for (i <- 0 until n)
            arr(i) = readInt()
        val s = readString()
        var r = Vector[Int]()
        var b = Vector[Int]()
        for (i <- 0 until n) {
           if (s(i) == 'B')
               b :+= arr(i)
           else
               r :+= arr(i)
        }
        b = b.sorted
        r = r.sorted.reverse
        var ans = "YES"
        for (i <- r.indices) {
            if (r(i) > n-i)
                ans = "NO"
        }
        for (i <- b.indices) {
            if (b(i) < i+1)
                ans = "NO"
        }
        writer.println(ans)
    }
    writer.flush()
}