You are given $$$n$$$ segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.Your task is the following: for every $$$k \in [1..n]$$$, calculate the number of points with integer coordinates such that the number of segments that cover these points equals $$$k$$$. A segment with endpoints $$$l_i$$$ and $$$r_i$$$ covers point $$$x$$$ if and only if $$$l_i \le x \le r_i$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of segments. The next $$$n$$$ lines contain segments. The $$$i$$$-th line contains a pair of integers $$$l_i, r_i$$$ ($$$0 \le l_i \le r_i \le 10^{18}$$$) — the endpoints of the $$$i$$$-th segment.

Print $$$n$$$ space separated integers $$$cnt_1, cnt_2, \dots, cnt_n$$$, where $$$cnt_i$$$ is equal to the number of points such that the number of segments that cover these points equals to $$$i$$$.

NoteThe picture describing the first example:Points with coordinates $$$[0, 4, 5, 6, 7, 8]$$$ are covered by one segment, points $$$[1, 2]$$$ are covered by two segments and point $$$[3]$$$ is covered by three segments.The picture describing the second example:Points $$$[1, 4, 5, 6, 7]$$$ are covered by one segment, points $$$[2, 3]$$$ are covered by two segments and there are no points covered by three segments.

object Main2 extends App {

import java.io._
import java.util
import java.util.{Locale, StringTokenizer, TreeSet}

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

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt

  var points = new Array[(Long, Int)](2*n)

  for (i <- 0 until n) {
    val l = in.nextLong
    val r = in.nextLong
    points(i*2) =  (l, 0)
    points(i*2+1) =  (r, 1)
  }

  points = points.sorted

  var ans = Map[Int, Long]()
  for (i <- 0 to n) ans += i -> 0

  var cnt = 0
  var prev = (0l, 0)
  for (point <- points) {

    if (prev._1 != point._1)
      ans += cnt -> (ans(cnt) + point._1 - prev._1 - 1)

    if (prev._1 != point._1 && prev._2 == 0)
      ans += cnt -> (ans(cnt) + 1)

    if (point._2 == 0) cnt += 1
    else {
      if (prev._1 == point._1 && prev._2 != point._2)
        ans += cnt -> (ans(cnt) + 1)

      if (prev._1 != point._1)
        ans += cnt -> (ans(cnt) + 1)

        cnt -= 1
    }

    prev = point
  }

  for (i <- 1 to n) out.print(ans(i)+" ")

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

object Main2 extends App {

import java.io._
import java.util
import java.util.{Locale, StringTokenizer, TreeSet}

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

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt

  var points = Vector[(Long, Int)]()

  for (_ <- 0 until n) {
    val l = in.nextLong
    val r = in.nextLong
    points = points :+ (l, 0)
    points = points :+ (r, 1)
  }

  points = points.sorted

  var ans = Map[Int, Long]()
  for (i <- 0 to n) ans += i -> 0

  var cnt = 0
  var prev = (0l, 0)
  for (point <- points) {

    if (prev._1 != point._1)
      ans += cnt -> (ans(cnt) + point._1 - prev._1 - 1)

    if (prev._1 != point._1 && prev._2 == 0)
      ans += cnt -> (ans(cnt) + 1)

    if (point._2 == 0) cnt += 1
    else {
      if (prev._1 == point._1 && prev._2 != point._2)
        ans += cnt -> (ans(cnt) + 1)

      if (prev._1 != point._1)
        ans += cnt -> (ans(cnt) + 1)

        cnt -= 1
    }

    prev = point
  }

  for (i <- 1 to n) out.print(ans(i)+" ")

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}


Ehab has an array $$$a$$$ of length $$$n$$$. He has just enough free time to make a new array consisting of $$$n$$$ copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.

The first line contains an integer $$$t$$$ — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$. The sum of $$$n$$$ across the test cases doesn't exceed $$$10^5$$$.

For each testcase, output the length of the longest increasing subsequence of $$$a$$$ if you concatenate it to itself $$$n$$$ times.

NoteIn the first sample, the new array is $$$[3,2,\textbf{1},3,\textbf{2},1,\textbf{3},2,1]$$$. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be $$$[1,3,4,5,9]$$$.

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 C628B(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 C628B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val a = na(n).toIndexedSeq.sorted
      var count = 1
      REP(n) { i =>
        if(i > 0 && a(i-1) != a(i)) count+=1
      }
      out.println(count)
    }
  }
}

object Main extends App {
    (0 until readInt()).map(_ => {
        readLine()
        readLine().split(" ").map(n => n.toInt).toSet.size
    }).foreach(n => println(s"$n"))
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      val a = (1 to n).map(_ => in.nextInt())
      out.println(a.distinct.length)
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

import java.io.PrintWriter

import scala.collection.mutable
import util.control.Breaks._

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

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

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

    def solve(): Unit = {
        val n = readInt()
        val a = readArrayInt()
        println(a.distinct.length)

    }

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

object CF1325B extends App{
  val sc = new java.util.Scanner(System.in)
  val t = sc.nextInt
  for (i <- 1 to t) {
    val n = sc.nextInt
    sc.nextLine()
    val nx = sc.nextLine().split(" ").toSet
    println(Math.min(n, nx.size))
  }
}


You have a bag of size $$$n$$$. Also you have $$$m$$$ boxes. The size of $$$i$$$-th box is $$$a_i$$$, where each $$$a_i$$$ is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if $$$n = 10$$$ and $$$a = [1, 1, 32]$$$ then you have to divide the box of size $$$32$$$ into two parts of size $$$16$$$, and then divide the box of size $$$16$$$. So you can fill the bag with boxes of size $$$1$$$, $$$1$$$ and $$$8$$$.Calculate the minimum number of divisions required to fill the bag of size $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{18}, 1 \le m \le 10^5$$$) — the size of bag and the number of boxes, respectively. The second line of each test case contains $$$m$$$ integers $$$a_1, a_2, \dots , a_m$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of boxes. It is guaranteed that each $$$a_i$$$ is a power of two. It is also guaranteed that sum of all $$$m$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the minimum number of divisions required to fill the bag of size $$$n$$$ (or $$$-1$$$, if it is impossible).

import scala.collection.Set

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val tb = stdin.next().toInt
  val rel = stdin.take(tb * 2).map(_.split(" ").map(_.toLong)).grouped(2).map(arr => {
    var Array(n, m) = arr.head
    solve(n, arr.last)
  })
  println(rel.mkString("\n"))

  def solve(n: Long, arr: Array[Long]): Int =
    if (arr.sum < n) -1
    else solveNoCheck(n, arr.groupBy(i => i).map(pair => pair._1 -> pair._2.length), 1)

  def solveNoCheck(n: Long, map: Map[Long, Int], split: Long): Int = {
    if (split > n) 0
    else if (map.get(split / 2).exists(_ >= 2))
      solveNoCheck(n, map + (split -> (map.getOrElse(split, 0) + map(split / 2) / 2)) + (split / 2 -> 0), split)
    else if ((n / split) % 2 == 0) solveNoCheck(n, map, split * 2)
    else {
      var nMap = map
      var nSplit = split
      var count = 0
      while (nMap.getOrElse(nSplit, 0) == 0) {
        nMap += (nSplit -> 1)
        nSplit = nSplit * 2
        count += 1
      }
      nMap += (nSplit -> (nMap(nSplit) - 1))
      count + solveNoCheck(n, nMap, split * 2)
    }
  }
}


Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.

On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.

NoteIn the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.

import java.util.StringTokenizer

object _381A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  def f(l: Int, r: Int, which: Int, one: Int, two: Int): (Int, Int) =
    if (l > r) (one, two)
    else if (which == 0) {
      if (a(l) > a(r)) f(l + 1, r, 1 - which, one + a(l), two)
      else f(l, r - 1, 1 - which, one + a(r), two)
    } else {
      if (a(l) > a(r)) f(l + 1, r, 1 - which, one, two + a(l))
      else f(l, r - 1, 1 - which, one, two + a(r))
    }
  val ans = f(0, n - 1, 0, 0, 0)
  println(ans._1 + " " + ans._2)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var ser = 0
  var dim = 0
  var left = 0
  var right = data.length - 1
  var dh = false
  while (right >= left) {
    var score = Math.max(data(left), data(right))
    if (data(left) >= data(right))
      left += 1
    else
      right -= 1

    if (dh)
      dim += score
    else
      ser += score
    dh = !dh
  }
  println(ser + " " + dim)
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val n = input.next().toInt
    var ns = input.next().split(" ").map(_.toInt).toList
    var s = 0
    var e = ns.length
    var l = List.empty[Int]
    while (ns.nonEmpty) {
      if (ns.head > ns.last) {
        l = ns.head :: l
        ns = ns.drop(1)
      } else {
        l = ns.last :: l
        ns = ns.dropRight(1)
      }
    }
    val as = l.reverse.grouped(2).map(a => if (a.size == 2) (a(0), a(1)) else (a(0), 0)).toList.unzip
    print(as._1.sum + " " + as._2.sum)
  }
}

import java.util.Scanner

object P381A {
    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val n = scanner.nextInt()
        val cards = for (i <- 0 until n) yield scanner.nextInt()
        val ans = emulate(cards.toList)
        println(ans._1 + " " + ans._2)
    }

    def emulate(list: List[Int]): (Int, Int) = {
        if (list.isEmpty) (0, 0)
        else if (list.head > list.last) {
            val points = emulate(list.tail).swap
            (list.head + points._1, points._2)
        }
        else {
            val points = emulate(list.init).swap
            (list.last + points._1, points._2)
        }
    }
}

import scala.util.Sorting
object Solve{
    def main(args: Array[String]): Unit = {

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

        var dimaSum = 0
        var serejaSum = 0
        var left = 0
        var right = arr.length - 1
        var sTurn = true
        var temp = 0
        while(left <= right){
             if(arr(left) > arr(right))
                 { temp = arr(left); left += 1; }
             else
                { temp = arr(right); right -= 1; }

            if(sTurn)
                serejaSum += temp
            else
                dimaSum += temp

            sTurn = !sTurn
        }

        println(serejaSum + " " + dimaSum)

    }
}

object A381 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    var in = readInts(n)
    var ser = 0
    var dima = 0
    while(in.nonEmpty){
      if(in.head > in.last) {
        ser += in.head
        in = in.drop(1)
      } else {
        ser += in.last
        in = in.dropRight(1)
      }
      if(in.nonEmpty) {
        if(in.head > in.last) {
          dima += in.head
          in = in.drop(1)
        } else {
          dima += in.last
          in = in.dropRight(1)
        }
      }

    }
    println(s"$ser $dima")
  }

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

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

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

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

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

}

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

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

  type Cards = List[Int]
  val CS: Cards = List.fill(N)(sc.nextInt)

  def solve(): Unit = {

    @tailrec
    def loop(spt: Int, dpt: Int, turn: Int, cs: Cards, rcs: Cards): Unit = {
      if (turn == N) out.println(List(spt, dpt).mkString(" "))
      else (cs, rcs) match {
        case (x :: xs, y :: ys) if x > y => if (turn % 2 == 0) loop(spt + x, dpt, turn + 1, xs, rcs)
                                            else loop(spt, dpt + x, turn + 1, xs, rcs)
        case (_, y :: ys) => if (turn % 2 == 0) loop(spt + y, dpt, turn + 1, cs, ys)
                             else loop(spt, dpt + y, turn + 1, cs, ys)
      }
    }

    loop(0, 0, 0, CS, CS.reverse)
  }

  solve
  out.close
}

import java.util.Scanner

object CF381A {

    def main(args: Array[String]) {
        val in = new Scanner(System.in)
        val n = in.nextInt()
        val cards = for(i <- 0 until n) yield in.nextInt()
        val answers = gao(cards.toList)
        println(answers._1 + " " + answers._2)
    }

    def gao(list: List[Int]): (Int, Int) = {
        if (list.isEmpty) (0, 0)
        else if (list.head > list.last) {
            val scores = gao(list.tail).swap
            (list.head + scores._1, scores._2)
        } else {
            val scores = gao(list.init).swap
            (list.last + scores._1, scores._2)
        }
    }
}

import scala.util.Sorting
object Solve{
    def main(args: Array[String]): Unit = {

        val n = readInt()
        val arr = readLine().split(" ").map(_.toInt)
        val cmp = (x: Int, y: Int) => x > y
        Sorting.stableSort(arr, cmp)
        //arr.foreach(println(_))

        var dimaSum = 0
        var serejaSum = 0
        for (i <- 0 to arr.length - 1)
          if(i % 2 == 0)
            serejaSum += arr(i)
          else
            dimaSum += arr(i)

        println(serejaSum + " " + dimaSum)

    }
}


This problem is different from the easy version. In this version Ujan makes at most $$$2n$$$ swaps. In addition, $$$k \le 1000, n \le 50$$$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $$$2n$$$ times: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$.Ujan's goal is to make the strings $$$s$$$ and $$$t$$$ equal. He does not need to minimize the number of performed operations: any sequence of operations of length $$$2n$$$ or shorter is suitable.

The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 1000$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 50$$$), the length of the strings $$$s$$$ and $$$t$$$.  Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

For each test case, output "Yes" if Ujan can make the two strings equal with at most $$$2n$$$ operations and "No" otherwise. You can print each letter in any case (upper or lower). In the case of "Yes" print $$$m$$$ ($$$1 \le m \le 2n$$$) on the next line, where $$$m$$$ is the number of swap operations to make the strings equal. Then print $$$m$$$ lines, each line should contain two integers $$$i, j$$$ ($$$1 \le i, j \le n$$$) meaning that Ujan swaps $$$s_i$$$ and $$$t_j$$$ during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than $$$2n$$$ is suitable.

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_599_B2 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val K = readLine.int

    for(k <- 1 to K) {
      val n = readLine.int
      var w1 = readLine.string.toCharArray()
      var w2 = readLine.string.toCharArray()

      def change(i1: Int, i2: Int) {
        val ch1 = w1(i1)
        w1(i1) = w2(i2)
        w2(i2) = ch1
      }

      def debugWords() {
        debug(s"w1: " + w1.mkString(""))
        debug(s"w2: " + w2.mkString(""))
      }

      var diffsL = List[Int]()
      for (i <- 0 until n) {
        if (w1(i) != w2(i)) diffsL ::= i
      }
      val diffs = diffsL.toArray.reverse
      val allLetters = diffs.flatMap(i => Array(w1(i), w2(i)))
      val evenNumber = allLetters.groupBy(x => x).mapValues(a => a.size % 2 == 0).values.forall(x => x)

      var res = if (evenNumber) {
        var steps = List[String]()
        def recordStep(ind1: Int, ind2: Int) = { steps ::= (ind1+1) + " " + (ind2+1) }
        for(st <- 0 until diffs.length) {
          val ind = diffs(st)
          val ch1 = w1(ind)
          debug(s"Step. Pos:$st, ind:$ind, ch1:$ch1")
          if (ch1 != w2(ind)) { //need to do something
            val inW1 = findAvailable(w1, diffs, st+1, ch1)
            if (inW1 != -1) { //one step
              change(inW1, ind)
              recordStep(inW1, ind)
              debug(" only one step: " + steps.head)
            } else {
              val inW2 = findAvailable(w2, diffs, st+1, ch1)
              val w1InterPos = diffs(st+1)
              change(w1InterPos, inW2)
              recordStep(w1InterPos, inW2)
              debug(" first step: " + steps.head)
              debugWords
              change(w1InterPos, ind)
              recordStep(w1InterPos, ind)
              debug(" second step: " + steps.head)
            }
            debugWords
          } else {
            debug(s" -- nothing")
          }

        }

        "Yes\n" + steps.size + "\n" + steps.reverse.mkString("\n")
      } else {
        "No"
      }

      outLn(res)
    }

//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  def findAvailable(ww: Array[Char], diffs: Array[Int], fromDif: Int, ch: Char): Int = {
    for (i <- fromDif until diffs.length) {
      if (ww(diffs(i)) == ch) {
        return diffs(i)
      }
    }
    -1
  }

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

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } 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 runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

val sa1 = """
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
"""

val sa2 = """
1
3
abc
bca
"""

val sa3 = """
10100
"""
 }
}


The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.The Two-dimensional kingdom has a regular army of n people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the i-th soldier indicated size ai. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from ai - x to ai + y, inclusive (numbers x, y ≥ 0 are specified). The Two-dimensional kingdom has m vests at its disposal, the j-th vest's size equals bj. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The i-th soldier can put on the j-th vest, if ai - x ≤ bj ≤ ai + y.

The first input line contains four integers n, m, x and y (1 ≤ n, m ≤ 105, 0 ≤ x, y ≤ 109) — the number of soldiers, the number of vests and two numbers that specify the soldiers' unpretentiousness, correspondingly. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) in non-decreasing order, separated by single spaces — the desired sizes of vests.  The third line contains m integers b1, b2, ..., bm (1 ≤ bj ≤ 109) in non-decreasing order, separated by single spaces — the sizes of the available vests.

In the first line print a single integer k — the maximum number of soldiers equipped with bulletproof vests.  In the next k lines print k pairs, one pair per line, as "ui vi" (without the quotes). Pair (ui, vi) means that soldier number ui must wear vest number vi. Soldiers and vests are numbered starting from one in the order in which they are specified in the input. All numbers of soldiers in the pairs should be pairwise different, all numbers of vests in the pairs also should be pairwise different. You can print the pairs in any order. If there are multiple optimal answers, you are allowed to print any of them.

NoteIn the first sample you need the vests' sizes to match perfectly: the first soldier gets the first vest (size 1), the third soldier gets the second vest (size 3). This sample allows another answer, which gives the second vest to the fourth soldier instead of the third one.In the second sample the vest size can differ from the desired size by at most 2 sizes, so all soldiers can be equipped.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n1, m1, x, y) = in.next().split(' ').map(_.toInt)
  val men = in.next().split(' ').map(_.toInt)
  val vests = in.next().split(' ').map(_.toInt)

  def process(mi: Int = 0, vi: Int = 0, pairs: List[(Int, Int)] = Nil): List[(Int, Int)] =
    if (mi == n1 || vi == m1) pairs
    else {
      if (men(mi) + y >= vests(vi) && men(mi) - x <= vests(vi))
        process(mi + 1, vi + 1, (mi + 1, vi + 1) :: pairs)
      else if (men(mi) < vests(vi)) process(mi + 1, vi, pairs)
      else process(mi, vi + 1, pairs)
  }

  val res = process()
  println(res.length)
  println(res.map(i => s"${i._1} ${i._2}").mkString("\n"))
}

object Main {
    def main(args: Array[String]) {
        val nmxy = readLine.split(" ").map(i => i.toInt)
        val n = nmxy(0)
        val m = nmxy(1)
        val x = nmxy(2)
        val y = nmxy(3)

        val a = readLine.split(" ").map(i => i.toInt)
        val b = readLine.split(" ").map(i => i.toInt)

        var ap = 0
        var bp = 0

        var resa = new Array[Int](n)
        var resb = new Array[Int](n)

        var i = 0

        while(ap < n && bp < m) {
            if(a(ap)-x <= b(bp) && b(bp) <= a(ap)+y) {
                resa(i) = ap
                resb(i) = bp
                i += 1
                ap += 1
                bp += 1
            } else if(a(ap)-x > b(bp)) {
                bp += 1
            } else {
                ap += 1
            }
        }

        println(i)
        (0 until i).foreach(j => println((resa(j)+1)+" "+(resb(j)+1)))
    }
}

import java.util.Scanner

object A {
  val in = new Scanner(System.in)

  def main(args: Array[String]) {
    val n = in.nextInt()
    val m = in.nextInt()
    val x = in.nextInt()
    val y = in.nextInt()
    val a = Array.fill[Int](n)(in.nextInt())
    val b = Array.fill[Int](m)(in.nextInt())
//    a.sortWith(_ < _)
//    b.sortWith(_ < _)
    var j = 0
    var ans = List[(Int,  Int)]()
    for (i <- 0 until a.length) {
      while (j < b.length && b(j) < a(i) - x) {
        j += 1
      }
//      println(i + " " + j + " " + b(j)  + " " + (a(i) + y))
      if (j < b.length && b(j) <= a(i) + y) {
        ans ::= (i + 1, j + 1)
        j += 1
      }
    }
    println(ans.size)
    for (x <- ans) {
      println(x._1 + " " + x._2)
    }

  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n1, m1, x, y) = in.next().split(' ').map(_.toInt)
  val men = in.next().split(' ').map(_.toInt)
  val vests = in.next().split(' ').map(_.toInt)

  def process(mi: Int = 0, vi: Int = 0, pairs: List[(Int, Int)] = Nil): List[(Int, Int)] =
    if (mi == n1 || vi == m1) pairs
    else {
      if (men(mi) + y >= vests(vi) && men(mi) - x <= vests(vi))
        process(mi + 1, vi + 1, (n1 - mi, m1 - vi) :: pairs)
      else if (men(mi) < vests(vi)) process(mi + 1, vi, pairs)
      else process(mi, vi + 1, pairs)
  }

  val res = process()
  println(res.length)
  println(res.map(i => s"${i._1} ${i._2}").mkString("\n"))
}


Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi.As Petya is older, he wants to take the chores with complexity larger than some value x (hi > x) to leave to Vasya the chores with complexity less than or equal to x (hi ≤ x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a + b = n).In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?

The first input line contains three integers n, a and b (2 ≤ n ≤ 2000; a, b ≥ 1; a + b = n) — the total number of chores, the number of Petya's chores and the number of Vasya's chores. The next line contains a sequence of integers h1, h2, ..., hn (1 ≤ hi ≤ 109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different. All numbers on the lines are separated by single spaces.

Print the required number of ways to choose an integer value of x. If there are no such ways, print 0.

NoteIn the first sample the possible values of x are 3, 4 or 5.In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4.

object Solution extends App {
  val data = scala.io.Source.stdin.getLines()
  val Array(n, a, b) = data.next().split(" ").map(_.toInt)
  val tasks = data.next().split(" ").map(_.toInt).sorted
  println(tasks(b) - tasks(b - 1))
}

object Chores169A   extends App {
    import java.io.{InputStream, PrintStream}
    import java.util.Scanner
    solve(System.in,System.out)
    def solve(in: InputStream, out: PrintStream): Unit = {
        val scanner = new Scanner(in)
      val n = scanner.nextInt()
      val a = scanner.nextInt()
      val b = scanner.nextInt()

      val h = (1 to n).map(_ => scanner.nextInt()).sorted.toArray
      val (bChores,aChores) = h.splitAt(b)
      val lastB = bChores.last
      val firstA = aChores.head

      /**
        * todos los valores mayores o iguales que lastB y menores que firstA son validos
        */
      val result = firstA-lastB
      out.println(result)
    }
}

object Solution extends App {
  val data = scala.io.Source.stdin.getLines()
  val Array(n, a, b) = data.next().split(" ").map(_.toInt)
  val tasks = data.next().split(" ").map(_.toInt).sorted
  if (tasks(b) != tasks(b - 1)) println(tasks(b - 1))
  else println(0)

}

object Solution extends App {
  val data = scala.io.Source.stdin.getLines()
  val Array(n, a, b) = data.next().split(" ").map(_.toInt)
  val tasks = data.next().split(" ").map(_.toInt).sorted
  if (tasks(b) != tasks(b - 1)) println(tasks(b - 1))
  else tasks(0)

}


Given an array $$$a$$$ of length $$$n$$$, find another array, $$$b$$$, of length $$$n$$$ such that:  for each $$$i$$$ $$$(1 \le i \le n)$$$ $$$MEX(\{b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_i\})=a_i$$$. The $$$MEX$$$ of a set of integers is the smallest non-negative integer that doesn't belong to this set.If such array doesn't exist, determine this.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$0 \le a_i \le i$$$) — the elements of the array $$$a$$$. It's guaranteed that $$$a_i \le a_{i+1}$$$ for $$$1\le i < n$$$.

If there's no such array, print a single line containing $$$-1$$$. Otherwise, print a single line containing $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_n$$$ ($$$0 \le b_i \le 10^6$$$) If there are multiple answers, print any.

NoteIn the second test case, other answers like $$$[1,1,1,0]$$$, for example, are valid.

import java.util

import scala.collection.mutable

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

    val n = nextInt
    val as = nextInts(n)
    val res = Array.ofDim[Int](n)

    val need = new java.util.TreeSet[Int]()
    var prev = -1
    for (a <- as) {
      if (prev < a) {
        prev += 1
        while (prev < a) {
          need.add(prev)
          prev += 1
        }
      }
    }

    var maxPrev = 0
    for (i <- 0 until n) {
      if (as(i) > maxPrev) {
        need.add(maxPrev)
        maxPrev = as(i)
      }
      if (!need.isEmpty) {
        res(i) = need.first()
        need.remove(res(i))
      } else if (as(i) == 0) {
        res(i) = n + 1
      } else {
        res(i) = as(i) - 1
      }
    }

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

import java.util

import scala.collection.mutable

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

    val n = nextInt
    val as = nextInts(n)
    val res = Array.ofDim[Int](n)

    val need = new mutable.TreeSet[Int]()
    var prev = -1
    for (a <- as) {
      if (prev < a) {
        prev += 1
        while (prev < a) {
          need.add(prev)
          prev += 1
        }
      }
    }

    var maxPrev = 0
    for (i <- 0 until n) {
      if (need.nonEmpty) {
        res(i) = need.min
        need.remove(res(i))
      } else if (as(i) == 0) {
        res(i) = n + 1
      } else {
        res(i) = maxPrev
      }
      if (as(i) > maxPrev) {
        maxPrev = as(i)
      }
    }

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


Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes).

First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100.

Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower).

NoteIn test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".

object ATomRiddlesDiary extends App {
  val n = scala.io.StdIn.readLine.toInt
  (0 until n).foldLeft(Map.empty[String, Boolean]) { (map, _) =>
      val name = scala.io.StdIn.readLine
      if (map contains name) println("YES")
      else {
        println("NO")
      }
      map + (name -> true)
  }
}

import java.util.Scanner
import java.util.HashSet

object TomRiddleDiary {
  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)

    val n = in.nextInt

    val s = new HashSet[String]
    val _ = in.nextLine

    (1 to n).map {
      x => {
        val str = in.nextLine
        if (s.contains(str)) {
          println("YES")
        } else {
          println("NO")
        }

        s.add(str)
      }
    }
  }
}

import scala.io.StdIn._
import scala.collection.mutable.HashSet

object Codeforces extends App {
  val n = readInt()
  val bag = HashSet[String]()
  1 to n foreach(_ => {
    val name = readLine()
    if (bag.contains(name))
      println("YES")
    else {
      bag.add(name)
      println("NO")
    }
  })
}


Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room n × m meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office.

The first line contains 2 space-separated numbers n and m (1 ≤ n, m ≤ 25) — the office room dimensions. Then there follow n lines with m characters 0 or 1 each. 0 stands for a free square meter of the office room. 1 stands for an occupied square meter. It's guaranteed that at least one square meter in the room is free.

Output one number — the maximum possible perimeter of a bargaining table for Bob's office room.

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, m) = readLine.split(" ").map(_.toInt);
    var a = Array.ofDim[Char](n, m);
    for (i <- 0 until n) {
      a(i) = readLine.toArray;
    }
    var max = 0;
    for (i <- 0 until n) {      //i - x1
      for (j <- 0 until m) {    //j - y1
        for (ii <- i to n) {    //ii - x2
          for (jj <- j to m) {  //jj - y2
            var free = true;
            for (x <- i until ii) {
              for (y <- j until jj) {
                if (a(x)(y) == '1') free = false;
              }
            }
            if (free && (ii - i) != 0 && (jj - j) != 0) {
              max = math.max(max, (ii - i) * 2 + (jj - j) * 2);
            }
          }
        }
      }
    }
    println(max);
  }

}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, m) = readLine.split(" ").map(_.toInt);
    var a = Array.ofDim[Char](n, m);
    for (i <- 0 until n) {
      a(i) = readLine.toArray;
    }
    var max = 0;
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        for (ii <- i to n) {
          for (jj <- j to m) {
            var free = true;
            for (x <- i until ii) {
              for (y <- j until jj) {
                if (a(x)(y) == '1') free = false;
              }
            }
            if (free) {
              max = math.max(max, (ii - i) * 2 + (jj - j) * 2);
            }
          }
        }
      }
    }
    println(max);
  }

}


Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.

The first line contains integer n (1 ≤ n ≤ 100) — the number of rectangles. Each of the following n lines contains four integers x1, y1, x2, y2 (1 ≤ x1 ≤ x2 ≤ 100, 1 ≤ y1 ≤ y2 ≤ 100), where x1 and y1 are the number of the column and row of the lower left cell and x2 and y2 are the number of the column and row of the upper right cell of a rectangle.

In a single line print the sum of all values in the cells of the table.

NoteNote to the first sample test:Values of the table in the first three rows and columns will be as follows:121121110So, the sum of values will be equal to 10.Note to the second sample test:Values of the table in the first three rows and columns will be as follows:222222222So, the sum of values will be equal to 18.

import scala.collection._

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

    var inLoop = true;
    while (inLoop) {
      val rectCountS = scala.io.StdIn.readLine
      if (rectCountS != null) {
        val rectCount = rectCountS.toInt
        var cellCount = 0

        for (i <- 0 to (rectCount - 1)) {
          val rect = scala.io.StdIn.readLine.split(' ').map(_.toInt)
          cellCount += (rect(2) + 1 - rect(0)) * (rect(3) + 1 - rect(1))
        }
        println(cellCount)

      }
      else {
        inLoop = false;
      }
    }
  }
}

import java.util.Scanner
import java.util.Locale

object Main {
  def main(args: Array[String]): Unit = {
    Locale.setDefault(Locale.US)
    val sc = new Scanner(System.in)
    var sum = 0;
    val m = sc.nextInt()
    for( i <- 1 to m) {
      val x1 = sc.nextInt()
      val y1 = sc.nextInt()
      val x2 = sc.nextInt()
      val y2 = sc.nextInt()
      sum += (x2-x1+1) * (y2-y1+1)
    }
    println(sum)
  }

}

import java.util.StringTokenizer

object _552A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => (1 to 4).map(j => next.toInt).toArray)
  val b = a.map(i => (i(2) - i(0) + 1) * (i(3) - i(1) + 1))
  println(b.sum)
}

object A552 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    var res = 0L
    for(_ <- 0 until n) {
      val arr = readLongs(4)
      res += (arr(2)-arr(0)+1)*(arr(3)-arr(1)+1)
    }
    println(res)
  }

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

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

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

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

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

}

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

import scala.collection.mutable

object A {

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

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

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val arr = new Array[Array[Int]](100)
    for (i <- 0 until 100) {
      arr(i) = new Array[Int](100)
    }
    for (i <- 0 until n) {
      val x1 = nextInt - 1
      val y1 = nextInt - 1
      val x2 = nextInt - 1
      val y2 = nextInt - 1
      for (j <- x1 to x2) {
        for (k <- y1 to y2) {
          arr(j)(k) += 1
        }
      }
    }
    var ans = 0
    for (i <- 0 until 100)
      for (j <- 0 until 100)
        ans += arr(i)(j)
    out.println(ans)
    return 0
  }
}

object _552A extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[(Int, Int, Int, Int)]
  override type Output = Int

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

  override def solve(input: Input) = input map {
    case (x1, y1, x2, y2) => (x2 - x1 + 1) * (y2 - y1 + 1)
  } sum

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

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

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._

object A extends App {
  val n = readInt()
  var total = 0

  for (_ <- 1 to n) {
    val Array(x1, y1, x2, y2) = readLine().split(" ").map(_.toInt)
    total += (x2 - x1 + 1) * (y2 - y1 + 1)
  }

  println(total)

}

object A{
  //import scala.collection.mutable.PriorityQueue
  //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
    var sum=0
    for(i<-0 until n){
      val a=nextInt
      val b=nextInt
      val c=nextInt
      val d=nextInt
      sum+=(c-a+1)*(d-b+1)
    }
    out.println(sum)
    //code ends here
    out.flush
    out.close
  }
}


Mainak has an array $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers. He will do the following operation to this array exactly once:  Pick a subsegment of this array and cyclically rotate it by any amount.  Formally, he can do the following exactly once:  Pick two integers $$$l$$$ and $$$r$$$, such that $$$1 \le l \le r \le n$$$, and any positive integer $$$k$$$.  Repeat this $$$k$$$ times: set $$$a_l=a_{l+1}, a_{l+1}=a_{l+2}, \ldots, a_{r-1}=a_r, a_r=a_l$$$ (all changes happen at the same time). Mainak wants to maximize the value of $$$(a_n - a_1)$$$ after exactly one such operation. Determine the maximum value of $$$(a_n - a_1)$$$ that he can obtain.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 999$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.

For each test case, output a single integer — the maximum value of $$$(a_n - a_1)$$$ that Mainak can obtain by doing the operation exactly once.

Note In the first test case, we can rotate the subarray from index $$$3$$$ to index $$$6$$$ by an amount of $$$2$$$ (i.e. choose $$$l = 3$$$, $$$r = 6$$$ and $$$k = 2$$$) to get the optimal array: $$$$$$[1, 3, \underline{9, 11, 5, 7}] \longrightarrow [1, 3, \underline{5, 7, 9, 11}]$$$$$$ So the answer is $$$a_n - a_1 = 11 - 1 = 10$$$. In the second testcase, it is optimal to rotate the subarray starting and ending at index $$$1$$$ and rotating it by an amount of $$$2$$$. In the fourth testcase, it is optimal to rotate the subarray starting from index $$$1$$$ to index $$$4$$$ and rotating it by an amount of $$$3$$$. So the answer is $$$8 - 1 = 7$$$.

object _1726A extends CodeForcesApp {
  override def solve() = repeat() {
    val as = nextN(nextInt()).toSeq

    val ans = Seq(
      as.last - as.min,
      as.max - as.head,
      (as :+ as.head).sliding(2).map({ case Seq(p, n) => p - n }).max
    ).max

    out.println(ans)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  import java.io._
  var in = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)

  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s"DEBUG: $x")
  def eng(b: Boolean): String = if (b) "Yes" else "No"

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

object _1726A extends CodeForcesApp {
  override def solve() = repeat() {
    val as: Seq[Int] = nextN(nextInt())

    val ans = Seq(
      as.last - as.min,
      as.max - as.head,
      (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max
    ).max

    out.println(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  import java.io._

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

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

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

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]

  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  def solve(): Any

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

object _1726A extends CodeForcesApp {
  override def solve() = repeat() {
    val as: Seq[Int] = in.nextN(in.nextInt())

    val ans = Seq(
      as.last - as.min,
      as.max - as.head,
      (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max
    ).max

    out.println(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def solve(): Any

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

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge && args.length == 2) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(new StringTokenizer(_))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]
}

class StringTokenizer(s: String, delimiter: Char  = ' ') extends Iterator[String] {
  private var i = 0
  private def skip(delim: Boolean) = {
    while(i < s.length && (s(i) == delimiter ^ !delim)) i += 1
    i
  }
  override def hasNext = skip(delim = true) < s.length
  override def next() = s.substring(i, skip(delim = false))
}

object _1726A extends CodeForcesApp {
  override def solve() = repeat() {
    val as: Seq[Int] = in.nextN(in.nextInt())

    val ans = Seq(
      as.last - as.min,
      as.max - as.head,
      (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max
    ).max

    out.println(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def solve(): Any

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

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge && args.length == 2) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]
}

object _1726A extends CodeForcesApp {
  override def solve() = repeat() {
    val as = in.nextN(in.nextInt()).toSeq

    val ans = Seq(
      as.last - as.min,
      as.max - as.head,
      (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max
    ).max

    out.println(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def solve(): Any

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

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge && args.length == 2) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble

  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
}

object _1726A extends CodeForcesApp {
  override def solve() = in.repeat() {
    val as = in.nextSeq()(in.nextInt()).toSeq

    val ans = Seq(
      as.last - as.min,
      as.max - as.head,
      (as :+ as.head).sliding(2).map({case Seq(p, n) => p - n}).max
    ).max

    out.println(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def solve(): Any

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble

  def repeat(n: Int = nextInt())(f: => Unit): Unit = (1 to n).foreach(_ => f)
  def nextSeq[A](n: Int = nextInt())(r: => A): Iterator[A] = Iterator.fill(n)(r)
}

object _1726A extends CodeForcesApp {

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

  override def solve() = in.repeat() {
    val as = in.nextSeq()(in.nextInt()).toSeq

    val ans = Seq(
      when(as.length > 1)(as.last - as.init.min),
      when(as.length > 1)(as.tail.max - as.head),
      Some((as :+ as.head).sliding(2).map({case Seq(p, n) => n - p}).max)
    ).flatten.max

    out.println(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def solve(): Any

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble

  def repeat(n: Int = nextInt())(f: => Unit): Unit = (1 to n).foreach(_ => f)
  def nextSeq[A](n: Int = nextInt())(r: => A): Iterator[A] = Iterator.fill(n)(r)
}

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

  override def solve(io: IO) = io.repeat {
    val as = io.read[IndexedSeq[Int]]

    val ans = Seq(
      as.last - as.min,
      as.max - as.head,
      (as :+ as.head).sliding(2).map({case Seq(p, n) => n - p}).max
    ).max

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

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

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

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

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

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

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

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

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

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

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

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

  override def solve(io: IO) = io.repeat {
    val as = io.read[IndexedSeq[Int]]
    val n = as.length

    val ans = Seq(
      as(n-1) - as.min,
      as.max - as(0),
      if (as.length > 1) as(n-2) - as(n-1) else -1
    ).max

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

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

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

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

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

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

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

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

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

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

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

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

  override def solve(io: IO) = io.repeat {
    val as = io.read[IndexedSeq[Int]]

    val ans = Seq(
      as.last - as.min,
      as.max - as.head,
      (as ++ as).sliding(2).map({case Seq(p, n) => n - p}).max
    ).max

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

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

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

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

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

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

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

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

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

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

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


There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that:  Alice will get $$$a$$$ ($$$a > 0$$$) candies;  Betty will get $$$b$$$ ($$$b > 0$$$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$);  all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — the number of candies you have.

For each test case, print the answer — the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.

NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are:  $$$a=6$$$, $$$b=1$$$;  $$$a=5$$$, $$$b=2$$$;  $$$a=4$$$, $$$b=3$$$.

import scala.io.StdIn

object Solution_A extends App {

  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val N = StdIn.readInt()
    if (N <= 2) {
      println("0")
    } else {
      println((N - 1) / 2)
    }
  }
}

import scala.io.StdIn.readInt

object Main extends App {
  val t = readInt()

  for (_ <- 1 to t) {
    val n = readInt()
    println((n + 1) / 2 - 1)
  }
}

object Main extends App {
  import scala.io.StdIn._
  val t = readInt
  for(_ <- 0 until t) {
    val n = readInt()
    println((n - 1) >> 1)
  }
}

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

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readInt()
    val ans = 0 max (n - n / 2 - 1)
    println(ans)
  }
}

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

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readInt()
    val ans = (n - 1) / 2
    println(ans)
  }
}

import scala.io.StdIn._

object Main2 extends App {
  val testNumber = readInt()
  0.until(testNumber)
    .map(_ => readInt())
    .map(n => (n-1) / 2)
    .foreach(println(_))
}

import java.io.PrintWriter

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

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

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

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

    def solve(t: Int): Unit = {
        val n = readInt()
        if (n % 2 == 0) println(n / 2 - 1)
        else println(n / 2)
    }

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


Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.

The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.  The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).

In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val mapping = Array.fill[List[Int]](n){ Nil }
    in.take(n - 1).map(_.split(' ').map(_.toInt - 1)).foreach {
    case Array(a, b) =>
      mapping(a) ::= b
      mapping(b) ::= a
  }
  val init = in.next().split(' ').map(_.toInt)
  val goal = in.next().split(' ').map(_.toInt)
  val changes = Array.ofDim[Int](n)
  val changesNext = Array.ofDim[Int](n)
  val visited = Array.ofDim[Boolean](n)
  val current = mutable.Queue(0)
  var result = 0
  var res = List.empty[Int]

  while (current.nonEmpty) {
    val head = current.dequeue()
    visited(head) = true
    val newNodes = mapping(head).filterNot(visited)

    if ((init(head) + changes(head)) % 2 != goal(head)) {
      res ::= (head + 1)
      result += 1
      newNodes.foreach{i =>
        changesNext(i) = (changes(head) + 1) % 2
        changes(i) = changesNext(head)
      }
    } else {
      newNodes.foreach{i =>
        changes(i) = changesNext(head)
        changesNext(i) = changes(head)
      }
    }

    current.enqueue(newNodes: _*)
  }

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


In the snake exhibition, there are $$$n$$$ rooms (numbered $$$0$$$ to $$$n - 1$$$) arranged in a circle, with a snake in each room. The rooms are connected by $$$n$$$ conveyor belts, and the $$$i$$$-th conveyor belt connects the rooms $$$i$$$ and $$$(i+1) \bmod n$$$. In the other words, rooms $$$0$$$ and $$$1$$$, $$$1$$$ and $$$2$$$, $$$\ldots$$$, $$$n-2$$$ and $$$n-1$$$, $$$n-1$$$ and $$$0$$$ are connected with conveyor belts.The $$$i$$$-th conveyor belt is in one of three states:  If it is clockwise, snakes can only go from room $$$i$$$ to $$$(i+1) \bmod n$$$.  If it is anticlockwise, snakes can only go from room $$$(i+1) \bmod n$$$ to $$$i$$$.  If it is off, snakes can travel in either direction.   Above is an example with $$$4$$$ rooms, where belts $$$0$$$ and $$$3$$$ are off, $$$1$$$ is clockwise, and $$$2$$$ is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$): the number of test cases. The description of the test cases follows.   The first line of each test case description contains a single integer $$$n$$$ ($$$2 \le n \le 300\,000$$$): the number of rooms.  The next line of each test case description contains a string $$$s$$$ of length $$$n$$$, consisting of only '<', '>' and '-'.   If $$$s_{i} = $$$ '>', the $$$i$$$-th conveyor belt goes clockwise.  If $$$s_{i} = $$$ '<', the $$$i$$$-th conveyor belt goes anticlockwise.  If $$$s_{i} = $$$ '-', the $$$i$$$-th conveyor belt is off.  It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$300\,000$$$.

For each test case, output the number of returnable rooms.

NoteIn the first test case, all rooms are returnable except room $$$2$$$. The snake in the room $$$2$$$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts.

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val s = nextLine
      val hasL = s.contains('<')
      val hasR = s.contains('>')

      val res = if (!hasL || !hasR) n
      else {
        var cnt = 0
        for (l <- 0 until n) {
          val r = (l + 1) % n
          if (s(l) == '-' || s(r) == '-') cnt += 1
        }
        cnt
      }

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


One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides, any two neighboring parts were painted different colors, that is, the red and the blue color were alternating, i. e. followed one after the other. The outer area of the wall (the area that lied outside all circles) was painted blue. Help Sherlock Holmes determine the total area of red parts of the wall.Let us remind you that two circles are called concentric if their centers coincide. Several circles are called concentric if any two of them are concentric.

The first line contains the single integer n (1 ≤ n ≤ 100). The second line contains n space-separated integers ri (1 ≤ ri ≤ 1000) — the circles' radii. It is guaranteed that all circles are different.

Print the single real number — total area of the part of the wall that is painted red. The answer is accepted if absolute or relative error doesn't exceed 10 - 4.

NoteIn the first sample the picture is just one circle of radius 1. Inner part of the circle is painted red. The area of the red part equals π × 12 = π.In the second sample there are three circles of radii 1, 4 and 2. Outside part of the second circle is painted blue. Part between the second and the third circles is painted red. Part between the first and the third is painted blue. And, finally, the inner part of the first circle is painted red. Overall there are two red parts: the ring between the second and the third circles and the inner part of the first circle. Total area of the red parts is equal (π × 42 - π × 22) + π × 12 = π × 12 + π = 13π

import java.util.Scanner
object Circles {

  val scanner = new Scanner(System.in)
  val n = scanner.nextInt();

  val rs = (1 to n) map (i=> scanner.nextInt())

  def main(args: Array[String]): Unit = {
    val sorted = rs sortWith( (a,b)=> a > b )
    val sum = (0.0/:(0 until(n,2))){(sum,r) => sum + Math.Pi*sorted(r)*sorted(r)}
    val ans = (sum/:(1 until(n,2))){(sum,r) => sum - Math.Pi*sorted(r)*sorted(r)}
    println("%.9f".format(ans))
  }

}

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 01.03.12
 * Time: 1:51
 * To change this template use File | Settings | File Templates.
 */
object B {
  def main(args: Array[String]) {
    val n = readInt()
    import math.{abs, Pi}
    println( Pi * abs(0 :: (readLine split ' ' map (_.toInt) sortBy (-_) toList) reduceLeft ((sum, x) => - sum + x * x)))

  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println(in.next().split(' ').map(_.toInt).sorted.reverse.foldLeft((0, 1)) {
    case ((sum, sign), i) => (sum + i * i * sign, -sign)
  }._1 * Math.PI)

}

object B {
  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines().toList.tail.head.split(" ").map(_ toDouble).toList.sort(_>_)
    println (lines.zip(Stream.continually(List(1,-1)).flatten).map ({ case (r,s) => scala.math.Pi * r * r * s}).sum)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toLong).sorted.reverse
    val sum = a.zipWithIndex.map{ t =>
      if (t._2 % 2 == 0) t._1 * t._1
      else -t._1 * t._1
    }.sum
    println(3.1415926535897932384626433832795f * sum)
  }
}