Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≤ xi ≤ yi ≤ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.

The first line contains integers n, m, k (1 ≤ n, m, k ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the initial array. Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≤ li ≤ ri ≤ n), (0 ≤ di ≤ 105). Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≤ xi ≤ yi ≤ m). The numbers in the lines are separated by single spaces.

On a single line print n integers a1, a2, ..., an — the array after executing all the queries. Separate the printed numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val increase = Array.ofDim[Long](n)
  val operations: Array[Int] = Array.ofDim[Int](m)
  val op = (1 to m).map { _ =>
    val Array(l, r, d) = in.next().split(' ').map(_.toInt)
    (l, r, d)
  }
  (1 to k).foreach { _ =>
    val Array(x, y) = in.next().split(' ').map(_.toInt - 1)
    operations(x) += 1
    if (y != m - 1)
      operations(y + 1) -= 1
  }
  operations.indices.foldLeft(0l) {
    case (balance, el) =>
      val (l, r, d) = op(el)
      val newBalance = balance + operations(el)
      increase(l - 1) += d * newBalance
      if (r != n)
        increase(r) -= d * newBalance
      newBalance
  }
  val r = increase.indices.foldLeft((0l, List.empty[Long])) {
    case ((open, list), i) =>
      val newBalance = open + increase(i)
      (newBalance, (newBalance + data(i)) :: list)
  }
  println(r._2.reverse.mkString(" "))
}

object A {
  def main(a: Array[String]) {
    def readArray = readLine.split(" ")
    val Array(n, m, k) = readArray.map(_.toInt)
    val initial = readArray.map(_.toLong)
    val operations = for (i <- 0 until m) yield readArray.map(_.toInt)
    val queries = for (i <- 0 until k) yield readArray.map(_.toInt)
    val opUsed = new Array[Long](m + 1)
    for (Array(qbegin, qend) <- queries) {
      opUsed(qbegin - 1) += 1
      opUsed(qend) -= 1
    }
    for (i <- 1 to m) opUsed(i) += opUsed(i - 1)
    val changes = new Array[Long](n + 1)
    for (i <- 0 until m) {
      val Array(from, to, d) = operations(i)
      val u = opUsed(i)
      changes(from - 1) += d * u
      changes(to) -= d * u
    }
    for (i <- 1 to n) changes(i) += changes(i - 1)
    val result = for (i <- 0 until n) yield initial(i) + changes(i)
    println(result.mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val increase = Array.ofDim[Int](n)
  val operations: Array[Int] = Array.ofDim[Int](m)
  val op = (1 to m).map { _ =>
    val Array(l, r, d) = in.next().split(' ').map(_.toInt)
    (l, r, d)
  }
  (1 to k).foreach { _ =>
    val Array(x, y) = in.next().split(' ').map(_.toInt - 1)
    operations(x) += 1
    if (y != m - 1)
      operations(y + 1) -= 1
  }
  operations.indices.foldLeft(0) {
    case (balance, el) =>
      val (l, r, d) = op(el)
      val newBalance = balance + operations(el)
      increase(l - 1) += d * newBalance
      if (r != n)
        increase(r) -= d * newBalance
      newBalance
  }
  val r = increase.indices.foldLeft((0, List.empty[Long])) {
    case ((open, list), i) =>
      val newBalance = open + increase(i)
      (newBalance, (newBalance + data(i)) :: list)
  }
  println(r._2.reverse.mkString(" "))
}

object A {
  def main(a: Array[String]) {
    def readArray = readLine.split(" ").map(_.toInt)
    val Array(n, m, k) = readArray
    val initial = readArray
    val operations = for (i <- 0 until m) yield readArray
    val queries = for (i <- 0 until k) yield readArray
    val opUsed = new Array[Int](m + 1)
    for (Array(qbegin, qend) <- queries) {
      opUsed(qbegin - 1) += 1
      opUsed(qend) -= 1
    }
    for (i <- 1 to m) opUsed(i) += opUsed(i - 1)
    val changes = new Array[Int](n + 1)
    for (i <- 0 until m) {
      val Array(from, to, d) = operations(i)
      val u = opUsed(i)
      changes(from - 1) += d * u
      changes(to) -= d * u
    }
    for (i <- 1 to n) changes(i) += changes(i - 1)
    val result = for (i <- 0 until n) yield initial(i) + changes(i)
    println(result.mkString(" "))
  }
}


Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $$$7$$$ segments, which can be turned on or off to display different numbers. The picture shows how all $$$10$$$ decimal digits are displayed:   After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly $$$k$$$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $$$k$$$ sticks (which are off now)? It is allowed that the number includes leading zeros.

The first line contains integer $$$n$$$ $$$(1 \leq n \leq 2000)$$$  — the number of digits on scoreboard and $$$k$$$ $$$(0 \leq k \leq 2000)$$$  — the number of segments that stopped working. The next $$$n$$$ lines contain one binary string of length $$$7$$$, the $$$i$$$-th of which encodes the $$$i$$$-th digit of the scoreboard. Each digit on the scoreboard consists of $$$7$$$ segments. We number them, as in the picture below, and let the $$$i$$$-th place of the binary string be $$$0$$$ if the $$$i$$$-th stick is not glowing and $$$1$$$ if it is glowing. Then a binary string of length $$$7$$$ will specify which segments are glowing now.    Thus, the sequences "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" encode in sequence all digits from $$$0$$$ to $$$9$$$ inclusive.

Output a single number consisting of $$$n$$$ digits  — the maximum number that can be obtained if you turn on exactly $$$k$$$ sticks or $$$-1$$$, if it is impossible to turn on exactly $$$k$$$ sticks so that a correct number appears on the scoreboard digits.

NoteIn the first test, we are obliged to include all $$$7$$$ sticks and get one $$$8$$$ digit on the scoreboard.In the second test, we have sticks turned on so that units are formed. For $$$5$$$ of additionally included sticks, you can get the numbers $$$07$$$, $$$18$$$, $$$34$$$, $$$43$$$, $$$70$$$, $$$79$$$, $$$81$$$ and $$$97$$$, of which we choose the maximum  — $$$97$$$.In the third test, it is impossible to turn on exactly $$$5$$$ sticks so that a sequence of numbers appears on the scoreboard.

object B {

  import InOut._

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

  val digits = Array(
    "1110111",
    "0010010",
    "1011101",
    "1011011",
    "0111010",
    "1101011",
    "1101111",
    "1010010",
    "1111111",
    "1111011"
  ).map(Integer.parseInt(_, 2))

  val n, k = nextInt
  val after = Array.fill(n)(Integer.parseInt(nextLine, 2))

  val dp = Array.fill(n + 1, k + 1)(-1)
  dp(n)(0) = 0
  for (i <- n - 1 to 0 by -1) {
    for (j <- 0 to k) {
      if (dp(i + 1)(j) != -1) {
        var d = 0
        while (d < 10) {
          if ((after(i) & digits(d)) == after(i)) {
            val need = Integer.bitCount(after(i) ^ digits(d))
            if (j + need <= k) {
              if (d > dp(i)(j + need)) dp(i)(j + need) = d
            }
          }
          d += 1
        }
      }
    }
  }

  if (dp(0)(k) == -1) {
    out.println(-1)
  } else {
    val res = Array.ofDim[Int](n)
    var j = k
    for (i <- 0 until n) {
      val d = dp(i)(j)
      res(i) = d
      j -= Integer.bitCount(after(i) ^ digits(d))
    }
    out.println(res.mkString)
  }

  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
  }

}

object B {

  import InOut._

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

  val digits = Array(
    "1110111",
    "0010010",
    "1011101",
    "1011011",
    "0111010",
    "1101011",
    "1101111",
    "1010010",
    "1111111",
    "1111011"
  ).map(Integer.parseInt(_, 2))

  val n, k = nextInt
  val after = Array.fill(n)(Integer.parseInt(nextLine, 2))

  val dp = Array.fill(n + 1, k + 1)(-1)
  dp(n)(0) = 0
  for (i <- n - 1 to 0 by -1) {
    var j = 0
    while (j <= k) {
      if (dp(i + 1)(j) != -1) {
        var d = 0
        while (d < 10) {
          if ((after(i) & digits(d)) == after(i)) {
            val need = Integer.bitCount(after(i) ^ digits(d))
            if (j + need <= k) {
              if (d > dp(i)(j + need)) dp(i)(j + need) = d
            }
          }
          d += 1
        }
      }
      j += 1
    }
  }

  if (dp(0)(k) == -1) {
    out.println(-1)
  } else {
    val res = Array.ofDim[Int](n)
    var j = k
    for (i <- 0 until n) {
      val d = dp(i)(j)
      res(i) = d
      j -= Integer.bitCount(after(i) ^ digits(d))
    }
    out.println(res.mkString)
  }

  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
  }

}

object B {

  import InOut._

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

  val digits = Array(
    "1110111",
    "0010010",
    "1011101",
    "1011011",
    "0111010",
    "1101011",
    "1101111",
    "1010010",
    "1111111",
    "1111011"
  ).map(Integer.parseInt(_, 2))

  val n, k = nextInt
  val after = Array.fill(n)(Integer.parseInt(nextLine, 2))

  var dp0 = Array.fill(k + 1)(-1)
  dp0(0) = 0
  for (i <- 0 until n) {
    val dp = Array.fill(k + 1)(-1)
    var j = 0
    while (j <= k) {
      if (dp0(j) >= -1) {
        var d = 0
        while (d < 10) {
          if ((after(i) & digits(d)) == after(i)) {
            val need = Integer.bitCount(after(i) ^ digits(d))
            if (j + need <= k) {
              val sum = dp0(j) * 10 + d
              if (sum > dp(j + need)) dp(j + need) = sum
            }
          }
          d += 1
        }
      }
      j += 1
    }
    dp0 = dp
  }

  out.println(dp0(k))

  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
  }

}

object B {

  import InOut._

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

  val digits = Array(
    "1110111",
    "0010010",
    "1011101",
    "1011011",
    "0111010",
    "1101011",
    "1101111",
    "1010010",
    "1111111",
    "1111011"
  ).map(Integer.parseInt(_, 2))

  val n, k = nextInt
  val after = Array.fill(n)(Integer.parseInt(nextLine, 2))

  var dp0 = Array.fill(k + 1)(BigInt(-1))
  dp0(0) = 0
  for (i <- 0 until n) {
    val dp = Array.fill(k + 1)(BigInt(-1))
    var j = 0
    while (j <= k) {
      if (dp0(j) >= -1) {
        var d = 0
        while (d < 10) {
          if ((after(i) & digits(d)) == after(i)) {
            val need = Integer.bitCount(after(i) ^ digits(d))
            if (j + need <= k) {
              val sum = dp0(j) * 10 + d
              if (sum > dp(j + need)) dp(j + need) = sum
            }
          }
          d += 1
        }
      }
      j += 1
    }
    dp0 = dp
    //println(dp0.mkString(" "))
  }

  val res = dp0(k).toString
  out.println("0" * (n - res.length) + res)

  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
  }

}

object B {

  import InOut._

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

  val digits = Array(
    "1110111", //0
    "0010010", //1
    "1011101", //2
    "1011011", //3
    "0111010", //4
    "1101011", //5
    "1101111", //6
    "1010010", //7
    "1111111", //8
    "1111011", //9
  ).map(Integer.parseInt(_, 2))

  val n, k = nextInt
  val after = Array.fill(n)(Integer.parseInt(nextLine, 2))

  var dp0 = Array.fill(k + 1)(-1)
  dp0(0) = 0
  for (i <- 0 until n) {
    val dp = Array.fill(k + 1)(-1)
    var j = 0
    while (j <= k) {
      if (dp0(j) >= -1) {
        var d = 0
        while (d < 10)  {
          if ((after(i) & digits(d)) == after(i)) {
            val need = Integer.bitCount(after(i) ^ digits(d))
            if (j + need <= k) {
              val sum = dp0(j) * 10 + d
              if (sum > dp(j + need)) dp(j + need) = sum
            }
          }
          d += 1
        }
      }
      j += 1
    }
    dp0 = dp
  }

  out.println(dp0(k))

  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
  }

}


In the Bus of Characters there are $$$n$$$ rows of seat, each having $$$2$$$ seats. The width of both seats in the $$$i$$$-th row is $$$w_i$$$ centimeters. All integers $$$w_i$$$ are distinct.Initially the bus is empty. On each of $$$2n$$$ stops one passenger enters the bus. There are two types of passengers:   an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it;  an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of rows in the bus. The second line contains the sequence of integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^{9}$$$), where $$$w_i$$$ is the width of each of the seats in the $$$i$$$-th row. It is guaranteed that all $$$w_i$$$ are distinct. The third line contains a string of length $$$2n$$$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $$$j$$$-th character is '0', then the passenger that enters the bus on the $$$j$$$-th stop is an introvert. If the $$$j$$$-th character is '1', the the passenger that enters the bus on the $$$j$$$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $$$n$$$), and for each extrovert there always is a suitable row.

Print $$$2n$$$ integers — the rows the passengers will take. The order of passengers should be the same as in input.

NoteIn the first example the first passenger (introvert) chooses the row $$$2$$$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $$$1$$$, because it is the only empty row now. The third passenger (extrovert) chooses the row $$$1$$$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $$$2$$$, because it is the only row with an empty place.

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_484_B {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa2)
//    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    val rows = new Array[(Int, Int)](n)
    val rowLine = readLine
    (1 to n).foreach(x => rows(x-1) = x -> rowLine.int)
    val rowsSort = rows.sortBy(_._2)
    var indIntro = 0
    var emptyInros = List[Int]()

//    var resList = List[Int]()
    var resList = new Array[Int](n*2)
    var resListInt = 0
    val pLine = readLine.string
    for (p <- 1 to 2*n) {
      val pt = pLine(p-1)
      if (pt == '0') {
        val rowTaken = rowsSort(indIntro)._1
        resList(resListInt) = rowTaken
        emptyInros ::= rowTaken
        indIntro += 1
      } else {
        val rowTaken = emptyInros.head
        emptyInros = emptyInros.tail
        resList(resListInt) = rowTaken
      }
      resListInt += 1
    }
//    resList = resList.reverse

    //---------------------------- parameters reading :end

    val res = new StringBuffer()
    resList.foreach(x => res.append(x+" "))
//      resList.foldLeft("")((a, b) => a + b + " ")

    outLn(res.toString())
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
2
3 1
0011
"""

val sa2 = """
6
10 8 9 11 13 5
010010011101
"""

val sa3 = """
"""
}

}

import scala.io.StdIn

object Codeforces982B {
  def main(args: Array[String]): Unit = {
    val codeforces982B = new Codeforces982B()

    val n = StdIn.readInt()
    val w = StdIn.readLine().split(" ").map(_.toInt)

    val passengers = StdIn.readLine()

    val seatNumbers = codeforces982B.getPassengersSeatNumbers(n, w, passengers)

    println(seatNumbers.mkString(" "))
  }
}

class Codeforces982B {
  def getPassengersSeatNumbers(n: Int, w: Array[Int], passengers: String): Array[Int] = {
    val seats = w.zipWithIndex.map(z => new Seat(weight = z._1, number = z._2 + 1)).sortBy(s => s.weight)

    val dummyHead = new Node(null)
    var cursor = dummyHead
    for (seat <- seats) {
      cursor.next = new Node(seat, prev = cursor)
      cursor = cursor.next
    }
    val dummyTail = new Node(null, prev = cursor)
    cursor.next = dummyTail

    var introvertCursor = dummyHead.next
    var extrovertCursor: Node = null

    val seatNumbers = passengers.map(passenger => {
      if (passenger == '0') {
        val seatNumber = introvertCursor.seat.number
        extrovertCursor = introvertCursor
        introvertCursor = introvertCursor.next
        seatNumber
      } else {
        val seatNumber = extrovertCursor.seat.number
        extrovertCursor.prev.next = extrovertCursor.next
        extrovertCursor.next.prev = extrovertCursor.prev
        extrovertCursor = extrovertCursor.prev
        seatNumber
      }
    }).toArray

    return seatNumbers

  }

  class Seat(val weight: Int, val number: Int) {}

  class Node(val seat: Seat, var prev: Node = null, var next: Node = null) {}

}


Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has $$$n$$$ supports arranged in a line, the $$$i$$$-th of which has height $$$a_i$$$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $$$1$$$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $$$1$$$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array $$$b$$$ is a subsegment of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array $$$b_1, b_2, \dots, b_n$$$ is called nondecreasing if $$$b_i\le b_{i+1}$$$ for every $$$i$$$ from $$$1$$$ to $$$n-1$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of supports Omkar has. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \leq a_{i} \leq 10^9)$$$ — the heights of the supports. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.

NoteThe subarray with which Omkar performs the operation is bolded.In the first test case:First operation:$$$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$$$Second operation:$$$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$$$Third operation:$$$[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$$$In the third test case, the array is already nondecreasing, so Omkar does $$$0$$$ operations.

object CodeforcesRound1392C {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  // 5 3 5 3 5 3 5
  // 5 5 5 5 5 5 5
  //   2   2   2

  // 5 4 3 2 1 3 2 5
  //      ld=1
  // 5 3 3 2 2 3 2 2 5
  // 5 3 3 2 2 3 3 3 5
  // 5 3 3 2 2 3 2 2 5

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val n = rl_int
    val a = rll_int
    val res: Long = if (n == 0) {
      0L
    } else {
      val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)
      val maxai = aisorted.last
      val maxa = a(maxai)
      var increases: Long = 0L
      for (i <- 1 until n - 1) {
        val j = if (i >= maxai) i + 1 else i - 1
        if (a(i) < a(j)) {
          increases += a(j) - a(i)
        }
      }
      increases += maxa - a(n-1)
      increases
    }
    writer.println(res)
  }

//  def equalize0(a: Array[Int]): Long = {
//    val n = a.length
//    val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)
//    val maxai = aisorted.last
//    val maxa = a(maxai)
//    var curAiSortedI = 0
//    var curAi = aisorted(curAiSortedI)
//    var increases: Long = 0L
//    while (a(curAi) != maxa) {
//      val ld =
//        if ((curAi == 0) || (a(curAi - 1) - a(curAi)) <= 0) {
//          Integer.MAX_VALUE
//        } else {
//          a(curAi - 1) - a(curAi) // >= 0
//        }
//      val rd =
//        if ((curAi + 1 == n) || (a(curAi + 1) - a(curAi)) <= 0) {
//          Integer.MAX_VALUE
//        } else {
//          a(curAi + 1) - a(curAi) // >= 0
//        }
//      val d = Integer.min(ld, rd)
//      //        println(s"a[$curAi]=${a(curAi)}, ld=$ld, rd=$rd, d=$d, increases0=$increases")
//      if (d != Integer.MAX_VALUE) {
//        increases += d
//        a(curAi) += d // Not necessary?
//      }
//      curAiSortedI += 1
//      curAi = aisorted(curAiSortedI)
//    }
//    increases
//  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextLongs(n)
      var res = 0L
      for (i <- 1 until n) {
        val d = as(i) - as(i - 1)
        if (d < 0) {
          res -= d
        }
      }

      out.println(res)
    }

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

object CodeforcesRound1392C {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  // 5 3 5 3 5 3 5
  // 5 5 5 5 5 5 5
  //   2   2   2

  // 5 4 3 2 1 3 2 5
  //      ld=1
  // 5 3 3 2 2 3 2 2 5
  // 5 3 3 2 2 3 3 3 5
  // 5 3 3 2 2 3 2 2 5

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val n = rl_int
    val a = rll_int
    val res: Long = if (n == 0) {
      0L
    } else {
      val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)
      val maxai = aisorted.last
      val maxa = a(maxai)
      var increases = 0
      for (i <- 1 until n - 1) {
        val j = if (i >= maxai) i + 1 else i - 1
        if (a(i) < a(j)) {
          increases += a(j) - a(i)
        }
      }
      increases += maxa - a(n-1)
      increases
    }
    writer.println(res)
  }

//  def equalize0(a: Array[Int]): Long = {
//    val n = a.length
//    val aisorted: Array[Int] = a.zipWithIndex.sortBy(_._1).map(_._2)
//    val maxai = aisorted.last
//    val maxa = a(maxai)
//    var curAiSortedI = 0
//    var curAi = aisorted(curAiSortedI)
//    var increases: Long = 0L
//    while (a(curAi) != maxa) {
//      val ld =
//        if ((curAi == 0) || (a(curAi - 1) - a(curAi)) <= 0) {
//          Integer.MAX_VALUE
//        } else {
//          a(curAi - 1) - a(curAi) // >= 0
//        }
//      val rd =
//        if ((curAi + 1 == n) || (a(curAi + 1) - a(curAi)) <= 0) {
//          Integer.MAX_VALUE
//        } else {
//          a(curAi + 1) - a(curAi) // >= 0
//        }
//      val d = Integer.min(ld, rd)
//      //        println(s"a[$curAi]=${a(curAi)}, ld=$ld, rd=$rd, d=$d, increases0=$increases")
//      if (d != Integer.MAX_VALUE) {
//        increases += d
//        a(curAi) += d // Not necessary?
//      }
//      curAiSortedI += 1
//      curAi = aisorted(curAiSortedI)
//    }
//    increases
//  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}


Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.

The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.

Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.

NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.

object Main extends App {

  import scala.io.StdIn

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
  val c = StdIn.readLine().split(" ").map(_.toInt)
  val g = new Array[List[Int]](n)
  for (i <- 0 until n) g(i) = List()
  val used = new Array[Boolean](n)
  for (i <- 0 until m) {
    var Array(x, y) = StdIn.readLine().split(" ").map(_.toInt-1)
    g(x) = y :: g(x)
    g(y) = x :: g(y)
  }

  var ans = 0l
  for (i <- 0 until n) {
    if (!used(i)) ans += dfs(i)
  }

  println(ans)

  def dfs(v: Int): Int = {
    used(v) = true
    var res = c(v)
    for (u <- g(v))
      if (!used(u))
        res = Math.min(res, dfs(u))
    res
  }

}

import scala.collection.mutable._

//https://codeforces.com/problemset/problem/893/C
object Rumor {
   def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    var arr = in.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val m = arr(1)

    val bribe = in.readLine().split(" ").map(_.toInt)
    val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for (i <- 0 until m) {
      arr = in.readLine().split(" ").map(_.toInt - 1)
      graph(arr(0)) += arr(1)
      graph(arr(1)) += arr(0)
    }
    var minCost = 0L
    val vis = Array.fill[Boolean](n)(false)
    for (i <- 0 until n) {
      if (!vis(i)) {
        val cost = new ArrayBuffer[Int]()
        cost += Int.MaxValue
        //dfs(graph,i,vis,bribe, cost)
        bfs(graph,i,vis,bribe, cost)
        minCost += cost(0)
      }
    }
    println(minCost)

  }

  def bfs(graph:Array[ArrayBuffer[Int]],n: Int,vis:Array[Boolean],bribe:Array[Int],minCost: ArrayBuffer[Int]): Unit = {
    val queue = Queue[Int]()
    queue.enqueue(n)
    while (!queue.isEmpty) {
      val u = queue.dequeue()
      vis(u) = true
      minCost(0) = math.min(minCost(0), bribe(u))
      for (v <- 0 until graph(u).length if (!vis(graph(u)(v)))) {
        queue.enqueue(graph(u)(v))
      }
    }
  }

  //DFS is throwing Memory limit exceed
  def dfs(graph:Array[ArrayBuffer[Int]],n: Int,vis:Array[Boolean],bribe:Array[Int],minCost: ArrayBuffer[Int]): Unit = {
    if (!vis(n)) {
      vis(n) = true
      minCost(0) = math.min(minCost(0), bribe(n))
      for (i <- 0 until graph(n).length if (!vis(graph(n)(i)))) {
        dfs(graph,graph(n)(i),vis,bribe, minCost)
      }
    }
  }
}

import scala.collection.mutable._

//https://codeforces.com/problemset/problem/893/C
object Rumor {
  var graph: Array[ArrayBuffer[Int]] = null
  var bribe: Array[Int] = null
  var vis: Array[Boolean] = null

  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    var arr = in.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val m = arr(1)
    if (m > 1) {
      bribe = in.readLine().split(" ").map(_.toInt)
      graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
      for (i <- 0 until m) {
        arr = in.readLine().split(" ").map(_.toInt - 1)
        graph(arr(0)) += arr(1)
        graph(arr(1)) += arr(0)
      }
      var minCost = 0L
      vis = Array.fill[Boolean](n)(false)
      for (i <- 0 until n) {
        if (!vis(i)) {
          val cost = new ArrayBuffer[Int]()
          cost += Int.MaxValue
          //dfs( i, cost)
          bfs(i, cost)
          minCost += cost(0)
        }
      }
      println(minCost)
    } else {
      var minCost = 0L
      println(in.readLine().split(" ").map(_.toLong).reduce(_ + _))
    }
  }

  def bfs(n: Int, minCost: ArrayBuffer[Int]): Unit = {
    val queue = Queue[Int]()
    queue.enqueue(n)
    while (!queue.isEmpty) {
      val u = queue.dequeue()
      vis(u) = true
      minCost(0) = math.min(minCost(0), bribe(u))
      for (v <- 0 until graph(u).length if (!vis(graph(u)(v)))) {
        queue.enqueue(graph(u)(v))
      }
    }
  }

  def dfs(n: Int, minCost: ArrayBuffer[Int]): Unit = {
    if (!vis(n)) {
      vis(n) = true
      minCost(0) = math.min(minCost(0), bribe(n))
      for (i <- 0 until graph(n).length if (!vis(graph(n)(i)))) {
        dfs(graph(n)(i), minCost)
      }
    }
  }
}

import java.io.FileReader
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable

object Solution {
  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  class UnionFind(var size : Int){
    var parents = Array.ofDim[Int](size)
    var sizes = Array.ofDim[Int](size)

    for (i <- 0 until size) {
      parents(i) = i
      sizes(i) = 1
    }

    def findParent(node : Int): Int = {
      var p = node
      while (parents(p) != p) {
        parents(p) = parents(parents(p))
        p = parents(p)
      }
      parents(node) = p
      p
    }

    def merge(a : Int, b : Int): Unit = {
      var pA = findParent(a)
      var pB = findParent(b)

      if (pA == pB) {
        return
      }

      if (sizes(pA) < sizes(pB)) {
        parents(pB) = pA
        sizes(pA) += sizes(pB)
      } else {
        parents(pA) = pB
        sizes(pB) += sizes(pA)
      }
    }
  }

  def doCase() : Unit = {
    val Array(n, m) = readIntLine()
    val costs = readIntLine()

    val uf = new UnionFind(n + 1)
    for (_ <- 0 until m) {
      val Array(f, t) = readIntLine()
      uf.merge(f, t)
    }

    var totalCost = 0L
    for ((cost, idx) <- costs.zipWithIndex.map{case (cost, idx) => (cost, idx + 1)}.sorted) {
      if (uf.findParent(idx) != uf.findParent(0)) {
        uf.merge(idx, 0)
        totalCost += cost
      }
    }

    println(totalCost)

  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

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

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

  def readBigIntLine(): Array[BigInt] = {
    readLine().split(" ").map(BigInt.apply)
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/893/C
object Rumor {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val bribe=in.readLine().split(" ").map(_.toInt)
    val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for(i<- 0 until m){
      arr=in.readLine().split(" ").map(_.toInt-1)
      graph(arr(0))+=arr(1)
      graph(arr(1))+=arr(0)
    }
    var minCost=0
    val vis=Array.fill[Boolean](n)(false)
    for(i<-0 until n){
      if(!vis(i)){
        val cost=new ArrayBuffer[Int]()
        cost+=Int.MaxValue
        dfs(graph,i,vis,bribe,cost)
        minCost+=cost(0)
      }
    }
    println(minCost)
  }
  def dfs(graph:Array[ArrayBuffer[Int]],n:Int,vis:Array[Boolean],bribe:Array[Int],minCost:ArrayBuffer[Int]):Unit={
    if(!vis(n)){
      vis(n)=true
      minCost(0)=math.min(minCost(0),bribe(n))
      for(i<- 0 until graph(n).length if(!vis(graph(n)(i)))){
        dfs(graph,graph(n)(i),vis,bribe,minCost)
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer

//https://codeforces.com/problemset/problem/893/C
object Rumor {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    if(m>1) {
      val bribe = in.readLine().split(" ").map(_.toInt)
      val graph = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
      for (i <- 0 until m) {
        arr = in.readLine().split(" ").map(_.toInt - 1)
        graph(arr(0)) += arr(1)
        graph(arr(1)) += arr(0)
      }
      var minCost = 0L
      val vis = Array.fill[Boolean](n)(false)
      for (i <- 0 until n) {
        if (!vis(i)) {
          val cost = new ArrayBuffer[Int]()
          cost += Int.MaxValue
          dfs(graph, i, vis, bribe, cost)
          minCost += cost(0)
        }
      }
      println(minCost)
    }else{
      var minCost = 0L
      println(in.readLine().split(" ").map(_.toInt).reduce(_+_))
    }
  }
  def dfs(graph:Array[ArrayBuffer[Int]],n:Int,vis:Array[Boolean],bribe:Array[Int],minCost:ArrayBuffer[Int]):Unit={
    if(!vis(n)){
      vis(n)=true
      minCost(0)=math.min(minCost(0),bribe(n))
      for(i<- 0 until graph(n).length if(!vis(graph(n)(i)))){
        dfs(graph,graph(n)(i),vis,bribe,minCost)
      }
    }
  }
}


You have an axis-aligned rectangle room with width $$$W$$$ and height $$$H$$$, so the lower left corner is in point $$$(0, 0)$$$ and the upper right corner is in $$$(W, H)$$$.There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $$$(x_1, y_1)$$$, and the upper right corner in $$$(x_2, y_2)$$$.You want to place another rectangular table in this room with width $$$w$$$ and height $$$h$$$ with the width of the table parallel to the width of the room.The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).You can't rotate any of the tables, but you can move the first table inside the room.   Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of the test cases. The first line of each test case contains two integers $$$W$$$ and $$$H$$$ ($$$1 \le W, H \le 10^8$$$) — the width and the height of the room. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$0 \le x_1 < x_2 \le W$$$; $$$0 \le y_1 < y_2 \le H$$$) — the coordinates of the corners of the first table. The third line contains two integers $$$w$$$ and $$$h$$$ ($$$1 \le w \le W$$$; $$$1 \le h \le H$$$) — the width and the height of the second table.

For each test case, print the minimum distance you should move the first table, or $$$-1$$$ if there is no way to free enough space for the second table. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

NoteThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by $$$(0, -1)$$$, so the lower left corner will move from $$$(2, 1)$$$ to $$$(2, 0)$$$. Then you can place the second table at $$$(0, 3)-(4, 5)$$$.In the second test case, there is no way to fit both tables in the room without intersecting.In the third test case, you can move the first table by $$$(0, 2)$$$, so the lower left corner will move from $$$(0, 3)$$$ to $$$(0, 5)$$$.

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

case class InputB(W: Int, H: Int, x1: Int, y1: Int, x2: Int, y2: Int, w: Int, h: Int)

object Solution {
  def solve(input: InputB): Int = {
    // result is gonna be either: (0 0, w h) or (W 0, W-w h) or (0 H, w, H-h) or (W H, W-w, H-h)
    // to avoid intersection you can move either to the left or to the right or up or down

    var ans = Int.MaxValue

    // move to the right
    {
      val toMove = if (input.x1 < input.w) input.w - input.x1 else 0
      val newEnd = input.x2 + toMove
      if (newEnd <= input.W) ans = Math.min(ans, toMove)
    }

    // move up
    {
      val toMove = if (input.y1 < input.h) input.h - input.y1 else 0
      val newEnd = input.y2 + toMove
      if (newEnd <= input.H) ans = Math.min(ans, toMove)
    }

    // move to the left
    {
      val toMove = if (input.x2 > input.W - input.w) input.x2 - (input.W - input.w) else 0
      val newEnd = input.x1 - toMove
      if (newEnd >= 0) ans = Math.min(ans, toMove)
    }

    // move down
    {
      val toMove = if (input.y2 > input.H - input.h) input.y2 - (input.H-input.h) else 0
      val newEnd = input.y1 - toMove
      if (newEnd >= 0) ans = Math.min(ans, toMove)
    }

    if (ans == Int.MaxValue) -1 else ans
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    val inputB = InputB(input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt())
    output.println(solve(inputB))
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}


We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array:  The array consists of $$$n$$$ distinct positive (greater than $$$0$$$) integers.  The array contains two elements $$$x$$$ and $$$y$$$ (these elements are known for you) such that $$$x < y$$$.  If you sort the array in increasing order (such that $$$a_1 < a_2 < \ldots < a_n$$$), differences between all adjacent (consecutive) elements are equal (i.e. $$$a_2 - a_1 = a_3 - a_2 = \ldots = a_n - a_{n-1})$$$. It can be proven that such an array always exists under the constraints given below.Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize $$$\max(a_1, a_2, \dots, a_n)$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$2 \le n \le 50$$$; $$$1 \le x < y \le 50$$$) — the length of the array and two elements that are present in the array, respectively.

For each test case, print the answer: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of the required array. If there are several answers, you can print any (it also means that the order of elements doesn't matter). It can be proven that such an array always exists under the given constraints.

//package codeforces.contests._1409

object YetAnotherArrayRestoration {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val Array(n, x, y) = io.StdIn.readLine.split(" ").map(_.toInt)

      val (first, last, diff) = (0 to n - 2).map { i =>
        if ((y - x) % (i + 1) == 0) {
          val d = (y - x) / (i + 1)

          @scala.annotation.tailrec
          def loop(j: Int, r: Int = n - 2 - i): Int = if (j <= 0) j + d else if (r == 0) j else loop(j - d, r - 1)

          val f = loop(x)
          (f, f + (n - 1) * d, d)
        } else (Int.MaxValue, Int.MaxValue, Int.MaxValue)
      }.minBy(_._2)

      println {
        (first to last by diff).mkString(" ")
      }
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine.toInt
    for (_ <- 0 until t) {
      val arr = StdIn.readLine.split(" ").map(_.toInt)
      val (n, x, y) = (arr(0), arr(1), arr(2))

      def dmax(a: Int, b: Int, d: Int): (Int, Int) = {
        val n1 = (b-a) / d + 1
        if (n1 > n) (Int.MaxValue, d)
        else if (n1 == n) (b, d)
        else {
          val n2 =  (a-1) / d
          if (n1 + n2 >= n) (b, d) else {
            ((n-n1-n2) * d + b, d)
          }
        }

      }

      val (max, d) = (for (i <- 1 to y-x if (y-x) % i == 0) yield dmax(x, y, i)).minBy(_._1)

      val r = (max - (n-1)*d to max by d).mkString(" ")
      println(r)
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, x, y) = readLine().split(" ").map(_.toInt)

    val ans = (1 to (y - x))
      .collectFirst {
        case d if (y - x) % d == 0 && (y - x + d) / d <= n => d
      }
      .map { d =>
        val ms = x.to(y, d)
        val ls = (x - d).until(0, -d).take(n - ms.length)
        val rs = (y + d).to(n * d, d).take(n - ms.length - ls.length)
        ls ++ ms ++ rs
      }
      .get

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


Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...Most of the young explorers are inexperienced, and sending them alone would be a mistake. Even Russell himself became senior explorer not long ago. Each of young explorers has a positive integer parameter $$$e_i$$$ — his inexperience. Russell decided that an explorer with inexperience $$$e$$$ can only join the group of $$$e$$$ or more people.Now Russell needs to figure out how many groups he can organize. It's not necessary to include every explorer in one of the groups: some can stay in the camp. Russell is worried about this expedition, so he asked you to help him.

The first line contains the number of independent test cases $$$T$$$($$$1 \leq T \leq 2 \cdot 10^5$$$). Next $$$2T$$$ lines contain description of test cases. The first line of description of each test case contains the number of young explorers $$$N$$$ ($$$1 \leq N \leq 2 \cdot 10^5$$$). The second line contains $$$N$$$ integers $$$e_1, e_2, \ldots, e_N$$$ ($$$1 \leq e_i \leq N$$$), where $$$e_i$$$ is the inexperience of the $$$i$$$-th explorer. It's guaranteed that sum of all $$$N$$$ doesn't exceed $$$3 \cdot 10^5$$$.

Print $$$T$$$ numbers, each number on a separate line. In $$$i$$$-th line print the maximum number of groups Russell can form in $$$i$$$-th test case.

NoteIn the first example we can organize three groups. There will be only one explorer in each group. It's correct because inexperience of each explorer equals to $$$1$$$, so it's not less than the size of his group.In the second example we can organize two groups. Explorers with inexperience $$$1$$$, $$$2$$$ and $$$3$$$ will form the first group, and the other two explorers with inexperience equal to $$$2$$$ will form the second group.This solution is not unique. For example, we can form the first group using the three explorers with inexperience equal to $$$2$$$, and the second group using only one explorer with inexperience equal to $$$1$$$. In this case the young explorer with inexperience equal to $$$3$$$ will not be included in any group.

import java.util.Scanner

object Main extends App {

  val s = new Scanner(System.in)

  var t = s.nextInt()

  for(_ <- 0 until t) {

    val n = s.nextInt()
    val es = Array.fill(n)(s.nextInt())
    scala.util.Sorting.quickSort(es)

    var i = 0
    var groups = 0

    while(i < n) {
      var gs = es(i) // requested group size
      var formed = false // did we formed the group?
      var j = i + gs - 1 // index pointing to last member of considered group

      while(j < n && !formed) {
        if (es(j) == gs) {
          formed = true
          i = j + 1
        } else {
          gs = es(j)
          j = i + gs - 1
        }
      }

      if(formed) {
        groups += 1
      } else {
        i = n
      }
    }

    println(groups)
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C643B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C643B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val T = ni()
    REP(T) { _ =>
      val N = ni()
      val cnt = Array.fill[Int](N+1)(0)
      REP(N) { i =>
        cnt(ni()) += 1
      }

      var ans = 0L
      var rm = 0L
      REP(N+1) { i =>
        if(i > 0) {
          val x = cnt(i) + rm
          ans += (x / i)
          rm = x % i
        }
      }
      out.println(ans)
    }
  }
}

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

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val en = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val c = en.sorted
      .foldLeft((0L, 0L)) {
        case ((c, r), i) =>
          (c + (r + 1) / i, (r + 1) % i)
      }
      ._1

    println(c)
  }
}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

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

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val arr = new Array[Int](n + 1)
    for (i <- 0 until n) {
      val ei = in.nextInt()
      arr(ei) = arr(ei) + 1
    }
    var result = 0

    var currentSum = 0

    for (i <- 1 to n) {
      currentSum = currentSum + arr(i)
      val newGroupCount = currentSum / i
      currentSum = currentSum - newGroupCount * i
      result = result + newGroupCount
    }

    println(result)
  }

}

import java.util.Scanner

object Main extends App {

  val s = new Scanner(System.in)

  var t = s.nextInt()

  for(_ <- 0 until t) {

    val n = s.nextInt()

    val es = Array.fill(n)(s.nextInt())
    val ess = es.sorted(Ordering[Int].reverse)

    var i = 0
    var groups = 0

    while(i < n) {
      i += ess(i)
      groups += 1
    }

    println(groups)
  }
}

import java.util.Scanner

object Main extends App {

  val s = new Scanner(System.in)

  var t = s.nextInt()

  for(_ <- 0 until t) {

    val n = s.nextInt()

    val es = Array.fill(n)(s.nextInt())
    val ess = es.sorted(Ordering[Int].reverse)

    var i = 0
    var groups = 0

    while(i < n) {
      i += ess(i)
      groups += 1
    }

    print(groups)
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C643B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C643B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val T = ni()
    REP(T) { _ =>
      val N = ni()
      val cnt = Array.fill[Int](N+1)(0)
      REP(N) { i =>
        cnt(ni()) += 1
      }

      var ans = 0L
      REP(N) { i =>
        if(i > 0) ans += (cnt(i) / i)
      }
      out.println(ans)
    }
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C643B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C643B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val T = ni()
    REP(T) { _ =>
      val N = ni()
      val cnt = Array.fill[Int](N+1)(0)
      REP(N) { i =>
        cnt(ni()) += 1
      }

      var ans = 0L
      var rm = 0L
      REP(N) { i =>
        if(i > 0) {
          ans += (cnt(i) / i)
          val x = cnt(i) % i
          if(x + rm >= i) {
            ans +=1
            rm = x + rm - i
          } else rm += x
        }
      }
      out.println(ans)
    }
  }
}


In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road.Check if is it possible that after roaming there will be exactly bi soldiers in the i-th city.

First line of input consists of two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 200). Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 100). Next line contains n integers b1, b2, ..., bn (0 ≤ bi ≤ 100). Then m lines follow, each of them consists of two integers p and q (1 ≤ p, q ≤ n, p ≠ q) denoting that there is an undirected road between cities p and q.  It is guaranteed that there is at most one road between each pair of cities.

If the conditions can not be met output single word "NO". Otherwise output word "YES" and then n lines, each of them consisting of n integers. Number in the i-th line in the j-th column should denote how many soldiers should road from city i to city j (if i ≠ j) or how many soldiers should stay in city i (if i = j). If there are several possible answers you may output any of them.

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    val A=Array.fill(n)(0)
    val B=Array.fill(n)(0)
    for(i<-0 until n){
      A(i)=nextInt
    }
    for(i<-0 until n){
      B(i)=nextInt
    }
    val nE=2*n+2
    val c=Array.ofDim[Int](nE,nE)

    val inf=Int.MaxValue
    //source
    for(i<-0 until n){
      if(A(i)>B(i)){
        //source
        c(2*n)(2*i)=A(i)-B(i)
      }
      else{
        c(2*i)(2*n+1)=B(i)-A(i)
      }
      c(2*i)(2*i+1)=A(i)
    }
    for(_<-0 until m){
      val i=nextInt-1
      val j=nextInt-1
      c(2*i+1)(2*j)=inf
      c(2*j+1)(2*i)=inf
    }
    def maximumFlow(c:Array[Array[Int]],source:Int,sink:Int):Array[Array[Int]]={
      val n=c.size
      val cr=Array.ofDim[Int](n,n)
      val f=Array.ofDim[Int](n,n)
      def shortestPath():Array[Int]={
        val s=Array.fill(n)(-1)

        val q=Queue[Int]()
        q+=source
        breakable{
          while(!q.isEmpty){

            val p=q.dequeue
            for(i<-0 until n){
              if(cr(p)(i)>0&&s(i)== -1){
                s(i)=p
                if(i==sink){
                  break
                }
                q+=i
              }
            }
          }
        }
        if(s(sink)== -1){
          return Array[Int]()
        }
        else{
          return s
        }
      }
      for(i<-0 until n){
        for(j<-0 until n){
          if(c(i)(j)>0){
            cr(i)(j)=c(i)(j)
          }
        }
      }
      var s=shortestPath
      while(s.size>0){

        var p=sink
        var min=Int.MaxValue
        while(p!=source){
          min=Math.min(min,cr(s(p))(p))
          p=s(p)

        }
        p=sink
        while(p!=source){
          if(c(s(p))(p)>0){
            f(s(p))(p)+=min
          }else{
            f(p)(s(p))-=min
          }
          //out.println(s"${s(p)->p}")
          cr(s(p))(p)-=min
          cr(p)(s(p))+=min
          p=s(p)
        }
//        out.println(min)
        s=shortestPath
      }
      return f
    }
    val f=maximumFlow(c,2*n,2*n+1)
//    for(i<-f){for(j<-i){out.print(j+" ")};out.println()}
    var solve=true
    for(i<-0 until n){
      if(f(2*n)(2*i)<c(2*n)(2*i)){
        solve=false
      }
      if(f(2*i)(2*n+1)<c(2*i)(2*n+1)){
        solve=false
      }
    }
    if(solve){
      out.println("YES")
      for(i<-0 until n){
        for(j<-0 until n){
          if(i==j){
            out.print((A(i)-f(2*i)(2*i+1))+" ")
          }else{
            out.print(f(2*i+1)(2*j)+" ")
          }

        }
        out.println()
      }
    }
    else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    val A=Array.fill(n)(0)
    val B=Array.fill(n)(0)
    for(i<-0 until n){
      A(i)=nextInt
    }
    for(i<-0 until n){
      B(i)=nextInt
    }
    val nE=2*n+2
    val c=Array.ofDim[Int](nE,nE)

    val inf=Int.MaxValue
    //source
    for(i<-0 until n){
      if(A(i)>B(i)){
        //source
        c(2*n)(2*i)=A(i)-B(i)
      }
      else{
        c(2*i)(2*n+1)=B(i)-A(i)
      }
      c(2*i)(2*i+1)=A(i)
    }
    for(_<-0 until m){
      val i=nextInt-1
      val j=nextInt-1
      c(2*i+1)(2*j)=inf
      c(2*j+1)(2*i)=inf
    }
    def maximumFlow(c:Array[Array[Int]],source:Int,sink:Int):Array[Array[Int]]={
      val n=c.size
      val cr=Array.ofDim[Int](n,n)
      val f=Array.ofDim[Int](n,n)
      def shortestPath():Array[Int]={
        val s=Array.fill(n)(-1)

        val q=Queue[Int]()
        q+=source
        breakable{
          while(!q.isEmpty){

            val p=q.dequeue
            for(i<-0 until n){
              if(cr(p)(i)>0&&s(i)== -1){
                s(i)=p
                if(i==sink){
                  break
                }
                q+=i
              }
            }
          }
        }
        if(s(sink)== -1){
          return Array[Int]()
        }
        else{
          return s
        }
      }
      for(i<-0 until n){
        for(j<-0 until n){
          if(c(i)(j)>0){
            cr(i)(j)=c(i)(j)
          }
        }
      }
      var s=shortestPath
      while(s.size>0){

        var p=sink
        var min=Int.MaxValue
        while(p!=source){
          min=Math.min(min,cr(s(p))(p))
          p=s(p)

        }
        p=sink
        while(p!=source){
          if(c(s(p))(p)>0){
            f(s(p))(p)+=min
          }else{
            f(p)(s(p))-=min
          }
          //out.println(s"${s(p)->p}")
          cr(s(p))(p)-=min
          cr(p)(s(p))+=min
          p=s(p)
        }
//        out.println(min)
        s=shortestPath
      }
      return f
    }
    val f=maximumFlow(c,2*n,2*n+1)
//    for(i<-f){for(j<-i){out.print(j+" ")};out.println()}
    var solve=true
    for(i<-0 until n){
      if(f(2*n)(2*i)<c(2*n)(2*i)){
        solve=false
      }
      if(f(2*i)(2*n+1)<c(2*i)(2*n+1)){
        solve=false
      }
    }
    if(solve){
      out.println("YES")
      for(i<-0 until n){
        for(j<-0 until n){
          out.print(f(2*i+1)(2*j)+" ")

        }
        out.println()
      }
    }
    else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}


Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given in two lines. The first line contains two integers $$$a_1$$$ and $$$b_1$$$ ($$$1 \le a_1, b_1 \le 100$$$) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers $$$a_2$$$ and $$$b_2$$$ ($$$1 \le a_2, b_2 \le 100$$$) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).

Print $$$t$$$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).

import scala.io.StdIn.readLine

object B {

  def solution0(a1: Int, b1: Int, a2: Int, b2: Int): Boolean = {
    (a1 == a2 && (b1+b2 == a1)) || ((b1 == b2 && (a1+a2 == b1)))
  }

  def solution(a1: Int, b1: Int, a2: Int, b2: Int): Boolean = {
    solution0(a1, b1, a2, b2) || solution0(a1, b1, b2, a2)
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(a1, b1) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a2, b2) = readLine.split(" ").toSeq.map(_.toInt)
      println(if (solution(a1, b1, a2, b2)) "Yes" else "No")
    }
  }
}


You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries.  Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.

Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.

NoteIn the first example here are how teams are formed:  the only team of 1 coder, 1 mathematician and 1 without specialization;  all three teams consist of 1 coder and 2 mathematicians;  no teams can be formed;  no teams can be formed;  one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team;  one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.

object zashikhin extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.io.Codec
  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))
    def this(reader: Reader) = this(new BufferedReader(reader))
    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None   // reset
      reader.readLine()
    }
    def lineNumber: Int = reader.getLineNumber
    def line(): String = tokenizer().get.nextToken("\n\r")
    def nextString(): String = next()
    def nextChar(): Char = next().ensuring(_.length == 1).head
    def nextBoolean(): Boolean = next().toBoolean
    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
    def nextFloat(): Float = next().toFloat
    def nextDouble(): Double = next().toDouble
    def nextBigDecimal(): BigDecimal = BigDecimal(next())
    override def next() = tokenizer().get.nextToken()
    override def hasNext = tokenizer().nonEmpty
    override def close() = reader.close()
  }
  val in = new Scanner(System.in)
  val q = in.nextInt()
  1 to q foreach {
      _ => {
          var a = in.nextInt()
          var b = in.nextInt()
          var c = in.nextInt()
          if (a>b) {
              c+=a-b
              a=b
          } else {
              c+=b-a
              b=a
          }
          var ans = 0
          if (a<=c){
              ans+=a
          } else {
              ans+=c
              a-=c
              ans+=(a+a)/3
          }
          println(ans)
      }
  }

}


Recall that a permutation of length $$$n$$$ is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once.For a fixed positive integer $$$d$$$, let's define the cost of the permutation $$$p$$$ of length $$$n$$$ as the number of indices $$$i$$$ $$$(1 \le i < n)$$$ such that $$$p_i \cdot d = p_{i + 1}$$$.For example, if $$$d = 3$$$ and $$$p = [5, 2, 6, 7, 1, 3, 4]$$$, then the cost of such a permutation is $$$2$$$, because $$$p_2 \cdot 3 = p_3$$$ and $$$p_5 \cdot 3 = p_6$$$.Your task is the following one: for a given value $$$n$$$, find the permutation of length $$$n$$$ and the value $$$d$$$ with maximum possible cost (over all ways to choose the permutation and $$$d$$$). If there are multiple answers, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The single line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the value $$$d$$$ in the first line, and $$$n$$$ integers in the second line — the permutation itself. If there are multiple answers, then print any of them.

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

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val A = ListBuffer.empty[Int]
      for {i <- 1 to n
        if ((i % 2 != 0) && (i <= n/2))} {
        var t = i
        while (t <= n){
          A+=t
          t = t*2
        }
      }
      for {i <- 1 to n
           if ((i % 2 != 0) && (i > n/2))} {
          A+=i
      }
      val B = A.toList
      val C = A.mkString(" ")
      output.println(2)
      output.println(C)
    }
  }
}

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

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val A = ListBuffer.empty[Int]
      for {i <- 1 to n
        if ((i % 2 != 0) && (i <= n/2))} {
        var t = i
        while (t <= n){
          A+=t
          t = t*2
        }
      }
      for {i <- 1 to n
           if ((i % 2 != 0) && (i > n/2))} {
          A+=i
      }
      val B = A.toList
      val C = A.mkString(" ")
      output.println(C)
    }
  }
}


Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?

The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).

For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.

NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.

import scala.io.StdIn

object Solution_D extends App {
  val T = StdIn.readInt()

  def getCurrent(a0: Array[Long], a1: Array[Long], a2: Array[Long], positions: Array[Int]): Long = {
    val x = a0(positions(0)) - a1(positions(1))
    val y = a0(positions(0)) - a2(positions(2))
    val z = a1(positions(1)) - a2(positions(2))
    x * x + y * y + z * z
  }

  def findBestMove(a0: Array[Long], a1: Array[Long], a2: Array[Long], positions: Array[Int]): Int = {
    val current = getCurrent(a0, a1, a2, positions)
    var bestIdx = -1
    var bestSoFar = Long.MaxValue
    val sizes = Array(a0.size, a1.size, a2.size)
    for (pos <- 0 until 3) {
      if (positions(pos) < sizes(pos) - 1) {
        positions(pos) += 1
        val move = getCurrent(a0, a1, a2, positions)
        if (move - current < bestSoFar) {
          bestSoFar = move - current
          bestIdx = pos
        }
        positions(pos) -= 1
      }
    }
    bestIdx
  }
  for (t <- 1 to T) {
    val input = StdIn.readLine().split(' ').map{_.toInt}
    val Nr = input(0)
    val Ng = input(1)
    val Nb = input(2)
    val a0 = StdIn.readLine().split(' ').map{_.toLong}.sorted
    val a1 = StdIn.readLine().split(' ').map{_.toLong}.sorted
    val a2 = StdIn.readLine().split(' ').map{_.toLong}.sorted
    val positions = Array(0, 0, 0)
    var stop = false
    var result = getCurrent(a0, a1, a2, positions)
    while (!stop) {
      val best = findBestMove(a0, a1, a2, positions)
      if (best == -1) {
        stop = true
      } else {
        positions(best) += 1
        result = Math.min(result, getCurrent(a0, a1, a2, positions))
      }
    }
    println(result)
  }
}

//18:45 - 21:55
import scala.io.StdIn.readLine
object C1336 {

  //it can return a.length if nothing is found
  def moveToNext(a:Array[(Int,String)],letter:String,currIndex:Int):Int ={
    assert(currIndex<a.length && currIndex>=0,"currIndex out of bounds")
    var j = currIndex + 1
    while(j < a.length && a(j)._2 != letter){
      j = j+1
    }
    j
  }
  //which letter didn't show up in the sequence yet?
  def returnMissing(s:String) ={
    assert(s.length ==2)
    if(!s.contains("A")){"A"}else
      if(!s.contains("B")){"B"}else{"C"}
  }

  def currAndPrevSymbol(a:Array[(Int,String)],j:Int,prevState:String)={

    (a(j)._2, prevState) match {
      case (_,"") => a(j)._2
      case (_,s2) if s2.length == 1 => s2+a(j)._2
      case (s1,s2) if s1==s2(1).toString => prevState//A BA-> BA
      case (s1,s2) if s1!=s2(1).toString => s2(1)+a(j)._2
    }
  }

  def mainFun(a:Array[(Int,String)],f:(Long,Long,Long)=>Long):Long={
    var mainCounter = 0 //main counter

    var lastA = -1
    var lastB = -1
    var lastC = -1

    var nextZ = -1

    var currentBlockPrefix = "" //first  two letters eg AB
    var nextSymbol = "" // eg if current block AB then C is missing

    var minVal = Long.MaxValue
    var currentVal = Long.MaxValue

    def lastX(letter:Char)={
      letter match{
        case 'A' => lastA
        case 'B' => lastB
        case 'C' => lastC
      }
    }

    while(mainCounter<a.length-1){

      //println(mainCounter)
      if(a(mainCounter)._2 == "A"){lastA=a(mainCounter)._1; currentBlockPrefix = currAndPrevSymbol(a, mainCounter,currentBlockPrefix)}
      if(a(mainCounter)._2 == "B"){lastB=a(mainCounter)._1; currentBlockPrefix = currAndPrevSymbol(a, mainCounter,currentBlockPrefix)}
      if(a(mainCounter)._2 == "C"){lastC=a(mainCounter)._1; currentBlockPrefix = currAndPrevSymbol(a, mainCounter,currentBlockPrefix)}

      //println(s"lastABC ${lastA},${lastB},${lastC}")

      if(mainCounter>=1 && mainCounter<a.length) {
        currentBlockPrefix = currAndPrevSymbol(a, mainCounter,currentBlockPrefix) //eg "AB"
        nextSymbol = returnMissing(currentBlockPrefix)
        nextZ = if(mainCounter==1 || mainCounter==nextZ){moveToNext(a, nextSymbol, mainCounter)}else{nextZ}

        //if((moveToNext(a, nextSymbol, mainCounter)<a.length)) {
          currentVal =if((nextZ<a.length) && Array("AB","BC","CA","BA","AC","CB").contains(currentBlockPrefix)  ) {
            //println(s"${lastX(currentBlockPrefix(0))}, ${a(mainCounter)._1}, ${a(moveToNext(a, nextSymbol, mainCounter))._1}")
            f(lastX(currentBlockPrefix(0)), a(mainCounter)._1, a(nextZ)._1)}else{currentVal} //      println(currentVal)
          //println(s"current value ${currentVal}")
          if (currentVal < minVal) {
            minVal = currentVal
          }
        //}

      }
      mainCounter = mainCounter+1
      //println(minVal)
    }
    minVal
  }

  def CalcFromInput(str:String)={

    val lines = str.split("\n")
    val t = lines(0).trim.toInt
    //println(t) //1<= t <100
    def f(x:Long,y:Long,z:Long):Long = (x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x)
    for(i <-(0 to t-1)){
      val Array(nA,nB,nC) = lines(1+4*i).trim.split(" ")
      //println(s"${nA} ${nB} ${nC}")
      val a0 = lines(1+4*i+1).trim.split(" ").map(_.toInt)
      val b0 = lines(1+4*i+2).trim.split(" ").map(_.toInt)
      val c0 = lines(1+4*i+3).trim.split(" ").map(_.toInt)
      //println(a0.mkString(","))
      //println(b0.mkString(","))
      //println(c0.mkString(","))
      val a = a0.map(x=>(x,"A"))
      val b = b0.map(x=>(x,"B"))
      val c = c0.map(x=>(x,"C"))

      val concat = (a++b++c).sortBy(_._1)
      //println(concat.map(x=>s"${x._1} ${x._2}").mkString(","))
      println(mainFun(concat,f))
    }
    //val Array(nA,nB,nC) = lines(1).split(' ')

    //val a = line()
    //println(s"${nA} ${nB} ${nC}")
  }

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

    //val lines = str.split("\n")
    val t = readLine.trim.toInt
    //println(t) //1<= t <100
    def f(x:Long,y:Long,z:Long):Long = (x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x)
    for(i <-(0 to t-1)){
      val Array(nA,nB,nC) = readLine.trim.split(" ")
      //println(s"${nA} ${nB} ${nC}")
      val a0 = readLine.trim.split(" ").map(_.toInt)
      val b0 = readLine.trim.split(" ").map(_.toInt)
      val c0 = readLine.trim.split(" ").map(_.toInt)
      //println(a0.mkString(","))
      //println(b0.mkString(","))
      //println(c0.mkString(","))
      val a = a0.map(x=>(x,"A"))
      val b = b0.map(x=>(x,"B"))
      val c = c0.map(x=>(x,"C"))

      val concat = (a++b++c).sortBy(_._1)
      //println(concat.map(x=>s"${x._1} ${x._2}").mkString(","))
      println(mainFun(concat,f))
    }
  }

}
object C1336Tests extends App{
  import C1336._

  //val a: Array[(Int,String)]= Array((0,"C"),(0,"A"),(1,"B"),(5,"B"),(9,"B"),(10,"C"))
  val a: Array[(Int,String)]= Array((0,"A"),(1,"B"),(5,"B"),(10,"C"),(20,"A"))

  def runTests(): Unit ={
    //2 error found thx to this
    //println(moveToNext(a,"C",0)==5)
    //println(moveToNext(a,"B",0)==2)
    //println(moveToNext(a,"B",2)==3)
    //println(moveToNext(a,"C",5)==6)

    //println(returnMissing("AB")=="C")
    //println(returnMissing("BC")=="A")
    //println(returnMissing("CA")=="B")

    //for(i <- 1 to a.length-1){
    //  print(currAndPrevSymbol(a,i))
    //  print(",")
    //}
    //CABBBC
    //println(currAndPrevSymbol(a,0,"")=="C")
    //println(currAndPrevSymbol(a,1,"C")=="CA")
    //println(currAndPrevSymbol(a,2,"CA")=="AB")
    //println(currAndPrevSymbol(a,3,"AB") =="AB")
    //println(currAndPrevSymbol(a,4,"AB") =="AB")
    //println(currAndPrevSymbol(a,5,"AB")=="BC")
    //println(currAndPrevSymbol(a,6,"C")=="CA")
    //def f(x:Int,y:Int,z:Int) = (x-y)*(x-y)+(y-z)*(y-z)+(z-x)*(z-x)
    //mainFun(a,f)
    val input = """5
    2 2 3
    7 8
    6 3
    3 1 4
    1 1 1
    1
    1
    1000000000
    2 2 2
    1 2
    5 4
    6 7
    2 2 2
    1 2
    3 4
    6 7
    3 4 1
    3 2 1
    7 3 3 4
    6"""
  CalcFromInput(input)

  }
  runTests()
}