Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.

The first line of the input contains n (1 ≤ n ≤ 200 000) — the number of bishops. Each of next n lines contains two space separated integers xi and yi (1 ≤ xi, yi ≤ 1000) — the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.

Output one integer — the number of pairs of bishops which attack each other.

NoteIn the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.

/**
  * Created by octavian on 31/01/2016.
  */
object Bishops {

  val TABLE_S = 1000

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("./src/bishops.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/bishops.out")))

    val n = readInt()
    var grid = Array.ofDim[Int](TABLE_S + 1, TABLE_S + 1)

    for(i <- 1 to n) {
      val Array(x, y) = readLine.split(" ").map(_.toInt)
      //println("x is " + x + ", y is" + y)
      grid(x)(y) = 1
    }

    var attack: BigInt = 0
    for(i <- 1 to TABLE_S) {
      attack += comb2(searchDiagonal(i, 1, 1, grid))
      attack += comb2(searchDiagonal(i, TABLE_S, -1, grid))
      if(i > 1) {
        attack += comb2(searchDiagonal(1, i, 1, grid))
      }
      if(i < TABLE_S) {
        attack += comb2(searchDiagonal(1, i, -1, grid))
      }
    }

    println(attack)
  }

  def searchDiagonal(s_lin: Int, s_col: Int, add_col: Int, grid: Array[Array[Int]]): Int = {
    var result = 0
    var lin = s_lin
    var col = s_col

    while(lin <= TABLE_S && 0 < col && col <= TABLE_S) {
      result += grid(lin)(col)

      lin += 1
      col += add_col
    }
    //println("result for " + s_lin + ", " + s_col + " is " + result)
    return result
  }

  def comb2(n: Int): Int = {
    return n * (n - 1) / 2
  }

}

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

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val ls, rs = mutable.HashMap[Int, Int]().withDefault(_ => 0)
    for (i <- 0 until n) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)
      ls(l - r) += 1
      rs(l + r) += 1
    }
    var ans = 0
    for (v <- ls.values ++ rs.values) {
      ans += v * (v - 1) / 2
    }
    println(ans)
  }
}

import scala.collection.mutable.ListBuffer

object B {
  def main(args: Array[String]) {
    val n = scala.io.StdIn.readInt
    val ups = ListBuffer.empty[Int]
    val downs = ListBuffer.empty[Int]
    (1 to n).foreach(x => {
      val q = scala.io.StdIn.readLine.split(" ").map(_.toShort)
      ups+=q(0)-q(1)
      downs+=q(0)+q(1)
    })
    val u = ups.groupBy(l => l).map(x => (x._2.length * (x._2.length - 1)/2).toLong).sum
    val d = downs.groupBy(l => l).map(x => (x._2.length * (x._2.length - 1)/2).toLong).sum
    println(d+u)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val diogonal = Array.ofDim[Long](1999)
  val backDiogonal = Array.ofDim[Long](1999)
  val n = in.next().toInt
  (1 to n).foreach { _ =>
    val Array(x, y) = in.next().split(' ').map(_.toInt)
    diogonal(1000 - y + x - 1) += 1
    backDiogonal(2000 - y - x) += 1
  }
  val seed = diogonal.foldLeft(0l) {
    case (acc, el) => acc + el * (el - 1) / 2
  }
  println(backDiogonal.foldLeft(seed) {
    case (acc, el) => acc + el * (el - 1) / 2
  })
}

object B621 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))
    val map1 = cu.Map.empty[Int, Long].withDefaultValue(0)
    val map2 = cu.Map.empty[Int, Long].withDefaultValue(0)
    in.foreach { case (x, y) =>
      map1(x-y) += 1
      map2(x+y) += 1
    }
    println(Array(map1,map2).map(_.values.map(x => (x*(x-1))/2).sum).sum)
  }

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

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

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

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

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

}

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)

  val cntA, cntB = mutable.Map.empty[Int, Int].withDefaultValue(0)

  for (_ <- 1 to n) {
    val Array(r, c) = readInts(2)
    cntA(r - c) += 1
    cntB(r + c) += 1
  }

  val a = cntA.values.map(x => x * (x - 1) / 2).sum
  val b = cntB.values.map(x => x * (x - 1) / 2).sum

  println(a + b)
}

// So you like object Task
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

/**
  * Created with IntelliJ IDEA.
  * User: xie
  * Date: 2/6/16
  * Time: 2:03 PM
  */
object Task {

    case class Bishop(x: Int, y: Int)
    def calc(x: Long) = x * (x - 1) / 2

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = Array.fill(n) { Bishop(in.nextInt(), in.nextInt()) }
        val a_sum = a.groupBy(b => b.x + b.y).map(b => calc(b._2.length)).sum
        val a_diff = a.groupBy(b => b.x - b.y).map(b => calc(b._2.length)).sum
        out.println(a_sum + a_diff)
    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch  {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while(!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

    def nextDouble(): Double = {
        next().toDouble
    }

    def close(): Unit = {
        inputStream.close()
    }
}

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

object Solution {

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

  def main(args: Array[String]) {

    val n = readLine().toInt

    val a = Array.fill(2001)(0)
    val b = Array.fill(2001)(0)
    (1 to n).foreach { _ =>
      val Array(x, y) = readInts(2)
      a(1000+x-y) += 1
      b(x+y) += 1
    }

    var res: Long = 0

    a.foreach { v => res += v*(v-1)/2 }
    b.foreach { v => res += v*(v-1)/2 }

    println(res)

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

/**
  * Created by octavian on 31/01/2016.
  */
object Bishops {

  val TABLE_S = 1000

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("./src/bishops.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/bishops.out")))

    val n = readInt()
    var grid = Array.ofDim[Int](TABLE_S + 1, TABLE_S + 1)

    for(i <- 1 to n) {
      val Array(x, y) = readLine.split(" ").map(_.toInt)
      //println("x is " + x + ", y is" + y)
      grid(x)(y) = 1
    }

    var attack: BigInt = 0
    for(i <- 1 to TABLE_S) {
      attack += comb2(searchDiagonal(i, 1, 1, grid))
      if(i > 1) {
        attack += comb2(searchDiagonal(i, 1, -1, grid))
        attack += comb2(searchDiagonal(1, i, 1, grid))
        attack += comb2(searchDiagonal(1, i, -1, grid))
      }
    }

    println(attack)
  }

  def searchDiagonal(s_lin: Int, s_col: Int, add_col: Int, grid: Array[Array[Int]]): Int = {
    var result = 0
    var lin = s_lin
    var col = s_col

    while(lin <= TABLE_S && 0 < col && col <= TABLE_S) {
      result += grid(lin)(col)

      lin += 1
      col += add_col
    }
    //println("result for " + s_lin + ", " + s_col + " is " + result)
    return result
  }

  def comb2(n: Int): Int = {
    return n * (n - 1) / 2
  }

}

import scala.collection.mutable.ListBuffer

object B {
  def main(args: Array[String]) {
    val n = scala.io.StdIn.readInt
    val ups = ListBuffer.empty[Int]
    val downs = ListBuffer.empty[Int]
    (1 to n).foreach(x => {
      val q = scala.io.StdIn.readLine.split(" ").map(_.toShort)
      ups+=q(0)-q(1)
      downs+=q(0)-q(1)
    })
    val u = ups.groupBy(l => l).map(x => x._2.length * (x._2.length - 1)/2).sum
    val d = downs.groupBy(l => l).map(x => x._2.length * (x._2.length - 1)/2).sum
    println(d+u)
  }
}

import scala.collection.mutable.ListBuffer

object B {
  def main(args: Array[String]) {
    val n = scala.io.StdIn.readInt
    val ups = ListBuffer.empty[Int]
    val downs = ListBuffer.empty[Int]
    (1 to n).foreach(x => {
      val q = scala.io.StdIn.readLine.split(" ").map(_.toShort)
      ups+=q(0)-q(1)
      downs+=q(0)-q(1)
    })
    val u = ups.groupBy(l => l).map(x => (x._2.length * (x._2.length - 1)/2).toLong).sum
    val d = downs.groupBy(l => l).map(x => (x._2.length * (x._2.length - 1)/2).toLong).sum
    println(d+u)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val diogonal = Array.ofDim[Long](1998)
  val backDiogonal = Array.ofDim[Long](1998)
  val n = in.next().toInt
  (1 to n).foreach { _ =>
    val Array(x, y) = in.next().split(' ').map(_.toInt - 1)
    diogonal(999 - x + y) += 1
    backDiogonal(999 - y + x) += 1
  }
  val seed = diogonal.foldLeft(0l) {
    case (acc, el) => acc + el * (el - 1) / 2
  }
  println(backDiogonal.foldLeft(seed) {
    case (acc, el) => acc + el * (el - 1) / 2
  })
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val diogonal = Array.ofDim[Int](1998)
  val backDiogonal = Array.ofDim[Int](1998)
  val n = in.next().toInt
  (1 to n).foreach { _ =>
    val Array(x, y) = in.next().split(' ').map(_.toInt - 1)
    diogonal(999 - x + y) += 1
    backDiogonal(999 - y + x) += 1
  }
  val seed = diogonal.foldLeft(0l) {
    case (acc, el) => acc + el.toLong * (el - 1) / 2
  }
  println(backDiogonal.foldLeft(seed) {
    case (acc, el) => acc + el.toLong * (el - 1) / 2
  })
}

object B621 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))
    val map = cu.Map.empty[Int, Long].withDefaultValue(0)
    in.foreach { case (x, y) =>
      map(x-y) += 1
      map(x+y) += 1
    }
    println(map.values.map(x => (x*(x-1))/2).sum)
  }

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

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

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

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

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

}

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)

  val cntA, cntB = mutable.Map.empty[Int, Int].withDefaultValue(0)

  for (_ <- 1 to n) {
    val Array(r, c) = readInts(2)
    cntA(r - c) += 1
    cntB(r + c) += 1
  }

  val a = cntA.values.filter(_ > 1).sum
  val b = cntB.values.filter(_ > 1).sum

  println(a + b)
}

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

object Solution {

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

  def main(args: Array[String]) {

    val n = readLine().toInt

    var a = 0
    var b = 0
    (1 to n).foreach { _ =>
      val Array(x, y) = readInts(2)
      if (x == y) a += 1
      if (x + y == n + 1) b += 1
    }

    println(a*(a-1)/2 + b*(b-1)/2)

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}


Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:There are two arrays of integers $$$a$$$ and $$$b$$$ of length $$$n$$$. It turned out that array $$$a$$$ contains only elements from the set $$$\{-1, 0, 1\}$$$.Anton can perform the following sequence of operations any number of times:   Choose any pair of indexes $$$(i, j)$$$ such that $$$1 \le i < j \le n$$$. It is possible to choose the same pair $$$(i, j)$$$ more than once.   Add $$$a_i$$$ to $$$a_j$$$. In other words, $$$j$$$-th element of the array becomes equal to $$$a_i + a_j$$$. For example, if you are given array $$$[1, -1, 0]$$$, you can transform it only to $$$[1, -1, -1]$$$, $$$[1, 0, 0]$$$ and $$$[1, -1, 1]$$$ by one operation.Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $$$a$$$ so that it becomes equal to array $$$b$$$. Can you help him?

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)  — the length of arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-1 \le a_i \le 1$$$)  — elements of array $$$a$$$. There can be duplicates among elements. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$)  — elements of array $$$b$$$. There can be duplicates among elements. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing the described operations, or "NO" if it's impossible. You can print each letter in any case (upper or lower).

NoteIn the first test-case we can choose $$$(i, j)=(2, 3)$$$ twice and after that choose $$$(i, j)=(1, 2)$$$ twice too. These operations will transform $$$[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$$$In the second test case we can't make equal numbers on the second position.In the third test case we can choose $$$(i, j)=(1, 2)$$$ $$$41$$$ times. The same about the fourth test case.In the last lest case, it is impossible to make array $$$a$$$ equal to the array $$$b$$$.

object B extends App {
  case class Case(as: List[Int], bs: List[Int])

  private def isPossible(c: Case): Boolean = {
    val Case(as, bs) = c

    val p = as.indexOf(1)
    val m = as.indexOf(-1)

    bs.zip(as).zipWithIndex.forall {
      case ((a, b), i) =>
        if (b == a) true
        else if (b > a) m > -1 && m < i
        else p > -1 && p < i
    }
  }

  val t = scala.io.StdIn.readInt()

  val cases = (0 until t)
    .foldLeft(List.empty[Case]) { (acc, _) =>
      scala.io.StdIn.readInt()
      val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList
      val bs = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

      Case(as, bs) :: acc
    }
    .reverse

  val answers = cases.map(isPossible)

  answers.foreach(if (_) println("YES") else println("NO"))
}


You are given an array $$$a_1, a_2, \ldots, a_n$$$ of positive integers. A good pair is a pair of indices $$$(i, j)$$$ with $$$1 \leq i, j \leq n$$$ such that, for all $$$1 \leq k \leq n$$$, the following equality holds:$$$$$$ |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, $$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Find a good pair. Note that $$$i$$$ can be equal to $$$j$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ for all test cases is at most $$$2 \cdot 10^5$$$.

For each test case, print a single line with two space-separated indices $$$i$$$ and $$$j$$$ which form a good pair of the array. The case $$$i=j$$$ is allowed. It can be shown that such a pair always exists. If there are multiple good pairs, print any of them.

import scala.io.StdIn

object Sol extends App {
  val tests = StdIn.readInt()

  for (x <- 1 to tests) {
    val length = StdIn.readInt()
    val ints = StdIn.readLine()
    val singleCaseInts = ints.split(" ").map(x => x.toInt)

    val withIndex = singleCaseInts.zipWithIndex
    val maxIndex = withIndex.maxBy(x => x._1)._2
    val minIndex = withIndex.minBy(x => x._1)._2

    println(s"${maxIndex + 1} ${minIndex + 1}")
  }
}

import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)

  def solve() = {
      val size = readLine.toInt
      val arr = rsi
      val tup = arr.foldLeft(arr.head, arr.head, 1, 1, 1)(
        (acc, elem) => {
            val (min, max, mini, maxi, count) = acc
            if (min > elem) (elem, max, count, maxi, count + 1)
            else if (max < elem) (min, elem, mini, count, count + 1)
            else (min, max, mini, maxi, count + 1)
         }
      )

      s"${tup._3} ${tup._4}"

  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt
    for (
      i <- 0 until cases
    ) println(solve)
  }
}

import scala.io.StdIn

object Sol extends App {
  val tests = StdIn.readInt()

  for (x <- 1 to tests) {
    val length = StdIn.readInt()
    val ints = StdIn.readLine()
    val singleCaseInts = ints.split(" ").map(x => x.toInt)

    println(singleCaseInts)
    val withIndex = singleCaseInts.zipWithIndex
    val maxIndex = withIndex.maxBy(x => x._1)._2
    val minIndex = withIndex.minBy(x => x._1)._2

    println(s"${maxIndex + 1} ${minIndex + 1}")
  }
}


Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked $$$n$$$ of them how much effort they needed to reach red."Oh, I just spent $$$x_i$$$ hours solving problems", said the $$$i$$$-th of them. Bob wants to train his math skills, so for each answer he wrote down the number of minutes ($$$60 \cdot x_i$$$), thanked the grandmasters and went home. Bob could write numbers with leading zeroes — for example, if some grandmaster answered that he had spent $$$2$$$ hours, Bob could write $$$000120$$$ instead of $$$120$$$.Alice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently:   rearranged its digits, or  wrote a random number. This way, Alice generated $$$n$$$ numbers, denoted $$$y_1$$$, ..., $$$y_n$$$.For each of the numbers, help Bob determine whether $$$y_i$$$ can be a permutation of a number divisible by $$$60$$$ (possibly with leading zeroes).

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 418$$$) — the number of grandmasters Bob asked. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains a single integer $$$y_i$$$ — the number that Alice wrote down. Each of these numbers has between $$$2$$$ and $$$100$$$ digits '0' through '9'. They can contain leading zeroes.

Output $$$n$$$ lines. For each $$$i$$$, output the following. If it is possible to rearrange the digits of $$$y_i$$$ such that the resulting number is divisible by $$$60$$$, output "red" (quotes for clarity). Otherwise, output "cyan".

NoteIn the first example, there is one rearrangement that yields a number divisible by $$$60$$$, and that is $$$360$$$.In the second example, there are two solutions. One is $$$060$$$ and the second is $$$600$$$.In the third example, there are $$$6$$$ possible rearrangments: $$$025$$$, $$$052$$$, $$$205$$$, $$$250$$$, $$$502$$$, $$$520$$$. None of these numbers is divisible by $$$60$$$.In the fourth example, there are $$$3$$$ rearrangements: $$$228$$$, $$$282$$$, $$$822$$$.In the fifth example, none of the $$$24$$$ rearrangements result in a number divisible by $$$60$$$.In the sixth example, note that $$$000\dots0$$$ is a valid solution.

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

  override def solve(io: IO) = io.repeat {
    val s = io.read[String].map(i => i - '0')
    val z = s.indexOf(0)
    val isRed = z >= 0 &&
      s.zipWithIndex.exists({case (s, i) => s%2 == 0 && i != z}) &&
      s.sum%3 == 0
    io.write(if (isRed) "red" else "cyan")
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


Let's define $$$S(x)$$$ to be the sum of digits of number $$$x$$$ written in decimal system. For example, $$$S(5) = 5$$$, $$$S(10) = 1$$$, $$$S(322) = 7$$$.We will call an integer $$$x$$$ interesting if $$$S(x + 1) < S(x)$$$. In each test you will be given one integer $$$n$$$. Your task is to calculate the number of integers $$$x$$$ such that $$$1 \le x \le n$$$ and $$$x$$$ is interesting.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) for the $$$i$$$-th test case.

Print $$$t$$$ integers, the $$$i$$$-th should be the answer for the $$$i$$$-th test case.

NoteThe first interesting number is equal to $$$9$$$.

import scala.io.StdIn

object Main {
  def main(args: Array[String]) = {
    def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }

    rep(StdIn.readInt) {
      println((9 to StdIn.readInt by 10).length)
    }

  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readInt()

    val ans = (n + 1) / 10

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readInt()

    val ans = n / 10 + (if (n % 10 == 9) 1 else 0)

    println(ans)
  }
}

import scala.io.StdIn._;

object Main extends App {

  def a(ignored: Int, z: Array[Long]): Long = z.zip(z.slice(1, z.length)).map(l => l._1 * l._2).max
//  for (_ <- 0 until readInt()) println(a(readInt(), readLine().split(" ").map(_.toLong)))

  def b(l: Long): Long = (l + 1)/10

  for (_ <- 0 until readInt()) println(b(readLong()))
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) = {
    println("Started program")
    def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }

    rep(StdIn.readInt) {
      println((9 to StdIn.readInt by 10).length)
    }

  }
}


You are given a positive integer $$$x$$$. Check whether the number $$$x$$$ is representable as the sum of the cubes of two positive integers.Formally, you need to check if there are two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b$$$) such that $$$a^3+b^3=x$$$.For example, if $$$x = 35$$$, then the numbers $$$a=2$$$ and $$$b=3$$$ are suitable ($$$2^3+3^3=8+27=35$$$). If $$$x=4$$$, then no pair of numbers $$$a$$$ and $$$b$$$ is suitable.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$x$$$ ($$$1 \le x \le 10^{12}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

For each test case, output on a separate line:    "YES" if $$$x$$$ is representable as the sum of the cubes of two positive integers.  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteThe number $$$1$$$ is not representable as the sum of two cubes.The number $$$2$$$ is represented as $$$1^3+1^3$$$.The number $$$4$$$ is not representable as the sum of two cubes.The number $$$34$$$ is not representable as the sum of two cubes.The number $$$35$$$ is represented as $$$2^3+3^3$$$.The number $$$16$$$ is represented as $$$2^3+2^3$$$.The number $$$703657519796$$$ is represented as $$$5779^3+7993^3$$$.

import scala.io.StdIn.readLine
import util.control.Breaks._

object Main {
    def main(args: Array[String]) = {
        var num = readLine().toInt
        while(num > 0 ){
            var found = 0
            var entry = readLine().toDouble
            num -= 1
            for( x <- scala.math.cbrt(entry).toInt to 1 by -1){
                val c1 = (entry - scala.math.pow(x,3))
                breakable {
                    if (c1 < 1) {
                        break
                    }
                    var res = scala.math.round(scala.math.cbrt(c1))
                    if (scala.math.pow(res,3) + scala.math.pow(x,3) == entry) {
                        found = 1
                    }
                }
            }
            if (found == 1) println("YES") else println("NO")
        }
    }
}


You are a given a list of integers $$$a_1, a_2, \ldots, a_n$$$ and $$$s$$$ of its segments $$$[l_j; r_j]$$$ (where $$$1 \le l_j \le r_j \le n$$$).You need to select exactly $$$m$$$ segments in such a way that the $$$k$$$-th order statistic of the multiset of $$$a_i$$$, where $$$i$$$ is contained in at least one segment, is the smallest possible. If it's impossible to select a set of $$$m$$$ segments in such a way that the multiset contains at least $$$k$$$ elements, print -1.The $$$k$$$-th order statistic of a multiset is the value of the $$$k$$$-th element after sorting the multiset in non-descending order.

The first line contains four integers $$$n$$$, $$$s$$$, $$$m$$$ and $$$k$$$ ($$$1 \le m \le s \le 1500$$$, $$$1 \le k \le n \le 1500$$$) — the size of the list, the number of segments, the number of segments to choose and the statistic number. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the values of the numbers in the list. Each of the next $$$s$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the endpoints of the segments. It is possible that some segments coincide.

Print exactly one integer — the smallest possible $$$k$$$-th order statistic, or -1 if it's impossible to choose segments in a way that the multiset contains at least $$$k$$$ elements.

NoteIn the first example, one possible solution is to choose the first and the third segment. Together they will cover three elements of the list (all, except for the third one). This way the $$$2$$$-nd order statistic for the covered elements is $$$2$$$.

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

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

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

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

  def solve(): Unit = {
    val N, S, M, K = ni()
    val A = na(N)
    val (l, r) = na2(S, -1)

    val B = A.clone()
    radixSort(B)

    val INF = 1e5.toInt
    val rl = Array.fill[Int](N)(INF) // 点を含むセグメントで、Lが一番小さいもの
    rep(S) { i =>
      rl(r(i)) = min(rl(r(i)), l(i))
    }
    rep_r(N - 1) { i =>
      rl(i) = min(rl(i), rl(i + 1))
    }

    // 各点ごとに使ったセグメントの個数で最大個数を求める
    // セグメントを点で分割すると考えると、右側に新しいセグメントが来るとして、左で選ぶのはLが一番小さいものが最適
    val dp = Array.ofDim[Int](N + 1, M + 1)

    // B(x)より小さい値だけでK個以上を達成できるか
    val ix = binSearch(0, N - 1) { x =>
      val flags = map(N){ i => if (A(i) <= B(x)) 1 else 0 }
      val cum = cumSum(flags)

      rep(N) { i =>
        Array.copy(dp(i), 0, dp(i + 1), 0, M + 1) // 何も選ばなかった場合

        if (rl(i) <= i) { // この点を含むセグメントが存在する
          val prev = dp(rl(i)) // セグメントの左端の一つ前から遷移する
          val next = dp(i + 1)
          val cnt = cum(i + 1) - cum(rl(i))
          rep(M) { j =>
            next(j + 1) = max(next(j + 1), prev(j) + cnt)
          }
        }
      }
      val k = dp(N).max
      k >= K
    }

    if (ix == N) {
      out.println(-1)
    } else {
      out.println(B(ix))
    }
  }

  def binSearch(ms: Int, mx: Int)(f: Int => Boolean): Int = {
    var high = mx + 1
    var low = ms - 1
    while(abs(high - low) > 1) {
      val mid = (high + low) / 2
      if (f(mid)) high = mid
      else low = mid
    }
    high
  }

  /**
    * 正の値のみのときだけ
    */
  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(as: Array[Int], n: Int): Array[Int] = {
    val n = as.length
    val xs = Array(as, new Array[Int](n))
    val b = Array.ofDim[Int](65537)

    def step(k: Int, x: Int): Unit = {
      rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }
      rep(65536, 1){ i => b(i) += b(i - 1) }
      rep(n){ i =>
        val j = xs(x)(i) >>> k & 0xffff
        xs(x ^ 1)(b(j)) = xs(x)(i)
        b(j) += 1
      }
    }

    step(0, 0)
    java.util.Arrays.fill(b, 0)
    step(16, 1)

    as
  }

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

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

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

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

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

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


Alice gave Bob two integers $$$a$$$ and $$$b$$$ ($$$a > 0$$$ and $$$b \ge 0$$$). Being a curious boy, Bob wrote down an array of non-negative integers with $$$\operatorname{MEX}$$$ value of all elements equal to $$$a$$$ and $$$\operatorname{XOR}$$$ value of all elements equal to $$$b$$$.What is the shortest possible length of the array Bob wrote?Recall that the $$$\operatorname{MEX}$$$ (Minimum EXcluded) of an array is the minimum non-negative integer that does not belong to the array and the $$$\operatorname{XOR}$$$ of an array is the bitwise XOR of all the elements of the array.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \leq a \leq 3 \cdot 10^5$$$; $$$0 \leq b \leq 3 \cdot 10^5$$$) — the $$$\operatorname{MEX}$$$ and $$$\operatorname{XOR}$$$ of the array, respectively.

For each test case, output one (positive) integer — the length of the shortest array with $$$\operatorname{MEX}$$$ $$$a$$$ and $$$\operatorname{XOR}$$$ $$$b$$$. We can show that such an array always exists.

NoteIn the first test case, one of the shortest arrays with $$$\operatorname{MEX}$$$ $$$1$$$ and $$$\operatorname{XOR}$$$ $$$1$$$ is $$$[0, 2020, 2021]$$$.In the second test case, one of the shortest arrays with $$$\operatorname{MEX}$$$ $$$2$$$ and $$$\operatorname{XOR}$$$ $$$1$$$ is $$$[0, 1]$$$.It can be shown that these arrays are the shortest arrays possible.

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

object Solution extends App {

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

  val testNumber = readInt()
  val calculatedXor = Array.tabulate(500000)(index => index).scan(0)(_ ^ _)
  1.to(testNumber).foreach { _ =>
    val Array(mex,xor) = readIntList()
    val existingXor: Int = calculatedXor(mex)
    val numberToMakeXor: Int = xor ^ existingXor
    val answer = (mex, xor) match {
      case (n, `existingXor`) => n
      case (n, _) if n == numberToMakeXor => n + 2
      case (n, _) => n + 1
    }
    println(answer)
  }

}

object B extends App {

  def shortest(a: Int, b: Int): Int =
    (((a - 1) % 4) match {
      case 0 => a - 1
      case 1 => 1
      case 2 => a
      case 3 => 0
    }) match {
      case c if a == (b ^ c) => a + 2
      case c if b == c       => a
      case _                 => a + 1
    }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    println(shortest(a, b))
  }

}


There are $$$n$$$ cats in a line, labeled from $$$1$$$ to $$$n$$$, with the $$$i$$$-th cat at position $$$i$$$. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.For example, if there are $$$3$$$ cats, this is a valid reordering: $$$[3, 1, 2]$$$. No cat is in its original position. The total distance the cats move is $$$1 + 1 + 2 = 4$$$ as cat $$$1$$$ moves one place to the right, cat $$$2$$$ moves one place to the right, and cat $$$3$$$ moves two places to the left.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first and only line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of cats. It can be proven that under the constraints of the problem, an answer always exist.

Output $$$t$$$ answers, one for each test case. Each answer consists of $$$n$$$ integers — a permutation with the minimum total distance. If there are multiple answers, print any.

NoteFor the first test case, there is only one possible permutation that satisfies the conditions: $$$[2, 1]$$$.The second test case was described in the statement. Another possible answer is $$$[2, 3, 1]$$$.

object hello extends App {
  import scala.io.StdIn
  val n = StdIn.readInt()
  for (i <- 1 to n) {
    val t = StdIn.readInt()
    var j = 1
    if (t % 2 == 1) {
      print("3 1 2 ")
      j = 4
    }
    while (j <= t) {
      print(j + 1)
      print(' ')
      print(j)
      print(' ')
      j = j + 2
    }
    println()
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readInt()
    val ans = {
      val t = Array.range(1, n + 1, 1).map {
        case i if n % 2 == 1 && i == n - 2 => n - 1
        case i if n % 2 == 1 && i == n - 1 => n
        case i if n % 2 == 1 && i == n     => n - 2
        case i if i % 2 == 0               => i - 1
        case i => i + 1
      }

      t
    }

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

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val cats = Array.tabulate(n){ x=> x + 1}
      if (n % 2 == 0) {
        for (i <- 0 until n) {
          cats(i) = i / 2 * 2 - i % 2 + 2
        }
      } else {
        cats(0) = 2
        cats(1) = 3
        cats(2) = 1
        for (i <- 3 until n) {
          val j = i + 1
          cats(i) = j / 2 * 2 - j % 2 + 1
        }
      }

      out.println(cats.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
  }
}


You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.

The first line of the input contains integer n (1 ≤ n ≤ 2000) — the number of points. Each of the next n lines contains two integers (xi, yi) (0 ≤ xi, yi ≤ 109) — the coordinates of the i-th point.

Print the only integer c — the number of parallelograms with the vertices at the given points.

import scala.collection.mutable
import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val points = Array.ofDim[(Int, Int)](n)
  val map = mutable.Map.empty[(Int, Int), Int]
  (0 until n).foreach { i =>
      val Array(x, y) = in.next().split(' ').map(_.toInt)
      points(i) = (x, y)
      (0 until i).foreach { j =>
          val (x1, y1) = points(j)
          val key =
            if (x1 == x)
              (0, Math.abs(y1 - y))
            else if (x1 > x)
              (x1 - x, y1 - y)
            else
              (x - x1, y - y1)
          map += (key -> (map.getOrElse(key, 0) + 1))
      }
  }

//  println(map)
//  println(map.filter(_._2 > 1))
//  println(map.filter(_._2 > 1).map(i => i._2 * (i._2 - 1) / 2))
//  println(points)

  println(map.values.foldLeft(0l){
    case (acc, el) => acc + el * (el - 1) / 2} / 2)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).foldLeft(Map.empty[(Int, Int), Int], List.empty[(Int, Int)]) {
    case((map, points), _) =>
      val Array(x, y) = in.next().split(' ').map(_.toInt)
      (points.foldLeft(map) { case (acc, (x1, y1)) =>
        val key = (Math.abs(x1 - x), Math.abs(y1 - y))
        acc + (key -> (map.getOrElse(key, 0) + 1))
      }, (x, y) :: points)
  }._1.values.foldLeft(0l){
    case (acc, el) => acc + el * (el - 1) / 2} / 2)
}


The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0, y0) of a rectangular squared field of size x × y, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly x·y tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same.After placing the objects on the field the robot will have to run a sequence of commands given by string s, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code.Moving to the left decreases coordinate y, and moving to the right increases it. Similarly, moving up decreases the x coordinate, and moving down increases it.The tests can go on for very long, so your task is to predict their results. For each k from 0 to length(s) your task is to find in how many tests the robot will run exactly k commands before it blows up.

The first line of the input contains four integers x, y, x0, y0 (1 ≤ x, y ≤ 500, 1 ≤ x0 ≤ x, 1 ≤ y0 ≤ y) — the sizes of the field and the starting coordinates of the robot. The coordinate axis X is directed downwards and axis Y is directed to the right. The second line contains a sequence of commands s, which should be fulfilled by the robot. It has length from 1 to 100 000 characters and only consists of characters 'L', 'R', 'U', 'D'.

Print the sequence consisting of (length(s) + 1) numbers. On the k-th position, starting with zero, print the number of tests where the robot will run exactly k commands before it blows up.

NoteIn the first sample, if we exclude the probable impact of the mines, the robot's route will look like that: .

import scala.collection._

object B extends App {

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

  val Array(x, y, x0, y0) = readInts(4)
  val ms = readLine.toCharArray
  val res = Array.fill(ms.size + 1){ 0 }

  val visited = Array.fill(x, y){ false }

  var _x = x0 - 1
  var _y = y0 - 1

  res(0) = 1
  var cnt = 0
  for (k <- ms.indices) {
    if (!visited(_x)(_y)) {
      visited(_x)(_y) = true
      cnt += 1
      res(k) = 1
    }
    ms(k) match {
      case 'U' => _x -= 1
      case 'D' => _x += 1
      case 'L' => _y -= 1
      case 'R' => _y += 1
    }
    if (_x < 0) _x = 0
    if (_x > x - 1) _x = x - 1
    if (_y < 0) _y = 0
    if (_y > y - 1) _y = y - 1
    //println(_x + 1, _y + 1)
  }

  /*if (!visited(_x)(_y))*/ res(res.size - 1) = (x * y - cnt) //max 1

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

  println(res.mkString(" "))

  Console.flush
}

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

object _606B extends CodeForcesApp {
  override type Result = Seq[Int]

  override def solve(scanner: Scanner) = {
    import scanner._
    val Seq(x, y, x0, y0) = Seq.fill(4)(nextInt())
    val command = nextLine().toCharArray.toList
    val seen = true
    val field = Array.ofDim[Boolean](x+1, y+1)

    @tailrec
    def move(i: Int, j: Int, command: List[Char], acc: Int): (Int, Int, List[Char], Int) = command match {
      case Nil => (i, j, command, acc)
      case _ if field(i)(j) == !seen =>
        field(i)(j) = seen
        (i, j, command, acc)
      case 'U' :: cs => move((i-1) max 1, j, cs, 1 + acc)
      case 'D' :: cs => move((i+1) min x, j, cs, 1 + acc)
      case 'L' :: cs => move(i, (j-1) max 1, cs, 1 + acc)
      case 'R' :: cs => move(i, (j+1) min y, cs, 1 + acc)
    }

    val moves = mmap[Int].to(0)

    var i = x0
    var j = y0
    var cmd = command
    var m = 0
    repeat(x * y) {
      val (ni, nj, ncmd, nm) = move(i, j, cmd, m)
      moves(nm) = moves(nm) + 1
      i = ni
      j = nj
      cmd = ncmd
      m = nm
    }

    (0 to command.length) map moves
  }

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

  def mmap[A] = new {
    def to[B](default: B): mutable.Map[A, B] = mutable.Map.empty[A, B] withDefaultValue default
  }

  override def format(result: Result) = result mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

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

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

object B{
  //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 (x,y)=(nextInt,nextInt)
    var (x0,y0)=(nextInt,nextInt)
    val s=nextString
    val visited=Array.ofDim[Boolean](x,y)
    var count=1
    out.print("1 ")
    visited(x0-1)(y0-1)=true
    s.dropRight(1).foreach(c=>{
                c match {
                  case 'U'=> x0-=1
                  case 'D'=> x0+=1
                  case 'L'=> y0-=1
                  case 'R'=> y0+=1
                  case _  => ()
                }
                if(x0<1){ x0=1}
                else if(x0>x){
                  x0=x
                }
                if(y0<1){y0=1}
                else if(y0>y){
                  y0=y
                }

                if(visited(x0-1)(y0-1)){
                  out.print("0 ")
                }else{

                  visited(x0-1)(y0-1)=true
                  count+=1
                  out.print("1 ")
                }
              })
    out.println(x*y-count)

    //code ends here
    out.flush
    out.close
  }
}

import scala.collection._

object B extends App {

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

  val Array(x, y, x0, y0) = readInts(4)
  val ms = readLine.toCharArray
  val res = Array.fill(ms.size + 1){ 0 }

  val visited = Array.fill(x, y){ false }

  var _x = x0 - 1
  var _y = y0 - 1

  res(0) = 1
  var cnt = 0
  for (k <- ms.indices) {
    if (!visited(_x)(_y)) {
      visited(_x)(_y) = true
      cnt += 1
      res(k) = 1
    }
    ms(k) match {
      case 'U' => _x -= 1
      case 'D' => _x += 1
      case 'L' => _y -= 1
      case 'R' => _y += 1
    }
    if (_x < 0) _x = 0
    if (_x > x - 1) _x = x - 1
    if (_y < 0) _y = 0
    if (_y > y - 1) _y = y - 1
  }

  if (!visited(_x)(_y)) res(res.size - 1) = x * y - cnt

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

  println(res.mkString(" "))

  Console.flush
}

import scala.collection._

object B extends App {

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

  val Array(x, y, x0, y0) = readInts(4)
  val ms = readLine.toCharArray
  val res = Array.fill(ms.size + 1){ 0 }

  val visited = Array.fill(x, y){ false }

  var _x = x0 - 1
  var _y = y0 - 1

  res(0) = 1
  var cnt = 0
  for (k <- ms.indices) {
    if (!visited(_x)(_y)) {
      visited(_x)(_y) = true
      cnt += 1
      res(k) = 1
    }
    ms(k) match {
      case 'U' => _x -= 1
      case 'D' => _x += 1
      case 'L' => _y -= 1
      case 'R' => _y += 1
    }
    if (_x < 0) _x = 0
    if (_x > x - 1) _x = x - 1
    if (_y < 0) _y = 0
    if (_y > y - 1) _y = y - 1
    //println(_x + 1, _y + 1)
  }

  /*if (!visited(_x)(_y)) */res(res.size - 1) = (x * y - cnt) max 1

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

  println(res.mkString(" "))

  Console.flush
}

import scala.collection._

object B extends App {

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

  val Array(x, y, x0, y0) = readInts(4)
  val ms = readLine.toCharArray
  val res = Array.fill(ms.size + 1){ 0 }

  val visited = Array.fill(x, y){ false }

  var _x = x0 - 1
  var _y = y0 - 1

  res(0) = 1
  var cnt = 0
  for (k <- ms.indices) {
    if (!visited(_x)(_y)) {
      visited(_x)(_y) = true
      cnt += 1
      res(k) = 1
    }
    ms(k) match {
      case 'U' => _x -= 1
      case 'D' => _x += 1
      case 'L' => _y -= 1
      case 'R' => _y += 1
    }
    if (_x < 0) _x = 0
    if (_x > x - 1) _x = x - 1
    if (_y < 0) _y = 0
    if (_y > y - 1) _y = y - 1
  }

  if (!visited(_x)(_y)) res(res.size - 1) = x * y - cnt else res(res.size - 1) = 1

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

  println(res.mkString(" "))

  Console.flush
}

import scala.collection._

object B extends App {

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

  val Array(x, y, x0, y0) = readInts(4)
  val ms = readLine.toCharArray
  val res = Array.fill(ms.size + 1){ 0 }

  val visited = Array.fill(x, y){ false }

  var _x = x0 - 1
  var _y = y0 - 1

  res(0) = 1
  var cnt = 0
  for (k <- ms.indices) {
    if (!visited(_x)(_y)) {
      visited(_x)(_y) = true
      cnt += 1
      res(k) = 1
    }
    ms(k) match {
      case 'U' => _x -= 1
      case 'D' => _x += 1
      case 'L' => _y -= 1
      case 'R' => _y += 1
    }
    if (_x < 0) _x = 0
    if (_x > x - 1) _x = x - 1
    if (_y < 0) _y = 0
    if (_y > y - 1) _y = y - 1
    //println(_x + 1, _y + 1)
  }

  if (!visited(_x)(_y)) res(res.size - 1) = (x * y - cnt) max 1

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

  println(res.mkString(" "))

  Console.flush
}


You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r).Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains integers: a1, a2, ..., an (0 ≤ ai ≤ 109).

Print the length of the longest good segment in array a.

object Solution365B extends App {

  def solution() {
    val n = _int
    val a = 1.to(n).map(_ => _int)

    if (a.length == 0) {
      println(0)
      return
    }
    if (a.length == 1) {
      println(1)
      return
    }
    if (a.length == 2) {
      println(2)
      return
    }

    val seq = a.tail.tail.zip(a.tail).zip(a).map(q => (q._1._1, q._1._2, q._2))
    val res = seq.foldLeft((0, 0))((memo, a) => {
      if (a._1 == a._2 + a._3) {
        (math.max(memo._1, memo._2 + 1), memo._2 + 1)
      } else {
        (memo._1, 0)
      }
    })
    println(res._1 + 2)
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

import java.util.Scanner
import java.net.InetAddress
import java.security.MessageDigest

/**
 * Contest 213, Div 2, problem B
 *
 *
You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good
 * if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r).
 *
 * Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the
 * segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if
 * len([l1, r1]) > len([l2, r2]).
 *
 * Your task is to find a good segment of the maximum length in array
 * a. Note that a segment of length 1 or 2 is always good.

 */
object Round213_Div2_Task2 {
  val inputScan = {
    val md = MessageDigest.getInstance("SHA-1")
    val userName = System.getProperty("user.name")
    val hostName = InetAddress.getLocalHost.getHostName

    val bytes = md.digest((userName + hostName).getBytes)
    val sb = new StringBuilder
    for (i ← 0 until bytes.length)
      sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))

    if (sb.result == "51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91") new Scanner(new java.io.FileInputStream("tmp/0.txt"))
    else new Scanner(System.in)
  }

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

    val n = scan.nextLine.toInt
    val res = n match {
      case 1 ⇒ 1
      case 2 ⇒ 2
      case _ ⇒
        val lengths = Array.fill(n)(0)
        val values = Array.fill(n)(0); values(0) = scan.nextInt; values(1) = scan.nextInt
        for (i ← 2 until n) {
          values(i) = scan.nextInt
          if (values(i) == values(i - 2) + values(i - 1) || values(i - 2) + values(i - 1) + values(i) == 0) {
            lengths(i) = 1
          } else lengths(i) = 0
        }
        for (i ← 2 until n) {
          if (lengths(i - 1) > 0 && lengths(i) > 0) lengths(i) = lengths(i - 1) + 1
        }
        lengths.max + 2
    }
    println(res)
  }
}

import java.util.Scanner
import java.net.InetAddress
import java.security.MessageDigest

/**
 * Contest 213, Div 2, problem B
 *
 *
You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good
 * if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r).
 *
 * Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the
 * segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if
 * len([l1, r1]) > len([l2, r2]).
 *
 * Your task is to find a good segment of the maximum length in array
 * a. Note that a segment of length 1 or 2 is always good.

 */
object Round213_Div2_Task2 {
  val inputScan = {
    val md = MessageDigest.getInstance("SHA-1")
    val userName = System.getProperty("user.name")
    val hostName = InetAddress.getLocalHost.getHostName

    val bytes = md.digest((userName + hostName).getBytes)
    val sb = new StringBuilder
    for (i ← 0 until bytes.length)
      sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))

    if (sb.result == "51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91") new Scanner(new java.io.FileInputStream("tmp/0.txt"))
    else new Scanner(System.in)
  }

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

    val n = scan.nextLine.toInt
    val result = n match {
      case 1 ⇒ 1
      case 2 ⇒ 2
      case _ ⇒
        val lengths = Array.fill(n)(0)
        val values = Array.fill(n)(0); values(0) = scan.nextInt; values(1) = scan.nextInt
        for (i ← 2 until n) {
          values(i) = scan.nextInt
          lengths(i) =
            if (values(i) == values(i - 2) + values(i - 1) || values(i - 2) + values(i - 1) + values(i) == 0)
              lengths(i - 1) + 1
            else 0
        }
        lengths.max + 2
    }
    println(result)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  var max = Math.min(2, n)
  var i = 0
  while (i < n - 1) {
    var j = i + 2
    var d = 0
    while (j < n && data(j) == data(j - 1) + data(j - 2)) {
      j += 1
      d += 1
    }
    i = j - 1
    max = Math.max(max, d + 2)
  }
  println(max)
}

import scala.collection._

object B extends App {

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

  val n = readInt
  val as = readLongs(n)

  var l, r = 0
  var max = n min 2

  for (i <- 2 until n) {
    if (as(i) == as(i - 1) + as(i - 2)) {
      if (i - l + 1 > max) max = i - l + 1
    } else l = i - 1
  }

  println(max)
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N = sc.nextInt
    val A = List.fill(N)(sc.nextLong)

    @tailrec
    def loop(acc: Int, cur: Int, as: List[Long]): Int = as match {
        case x :: y :: z :: _ => {
          if (x + y == z) loop(acc max (cur + 1), cur + 1, as.tail)
          else loop(acc, 0, as.tail)
        }
        case _ => (acc + 2) min N
      }

    loop(0, 0, A)
  }

  out.println(solve)
  out.close
}

/**
 * @author pvasilyev
 * @since 08 Aug 2016
 */
object B365 extends App{

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val a: Array[Long] = scala.io.StdIn.readLine().split(" ").map(_.toLong)
    if (n == 1) {
      println(1)
    } else {
      val b: Array[Int] = Array.ofDim[Int](n)
      b(0) = 1
      b(1) = 2
      for (i <- 2 until n) {
        if (a(i) == a(i - 1) + a(i - 2)) {
          b(i) = b(i - 1) + 1
        } else {
          b(i) = 2
        }
      }
      println(b.max)
    }
  }

  solve()

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    if (n == 1) println("1")
    else {
      var s1 = a(0)
      var s2 = a(1)
      var max = 2
      var current = 2
      for (i <- 2 until a.size) {
        if (a(i) == s1 + s2) {
          current += 1
        } else {
          max = max.max(current)
          current = 2
        }
        s1 = s2
        s2 = a(i)
      }
      println(max.max(current))
    }
  }
}

import java.util.Scanner
import scala.math.max

object TheFibonacciSegment extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    val a = new Array[Int](n)

    var ans = 2
    var nowx: Int = _
    var nowy: Int = _
    var nowl = 2
    for(i <- 0 until n) {
        val z = scan.nextInt
        if(i >= 2) {
            if(nowx + nowy == z) {
                ans = max(ans, nowl + 1)
                nowl = nowl + 1
            } else nowl = 2
        }
        nowx = nowy
        nowy = z
    }

    if(n == 1) ans = 1
    println(ans)
}

object Fib extends App {
  def fibsegment(elements: IndexedSeq[Int]) = {

    if (elements.length == 1) 1
    else if (elements.length == 2) 2
    else {
      var max = 2
      var localLength = 2
      for (i <- 2 until elements.length) {
        if (elements(i) == elements(i - 1) + elements(i - 2)) {
          localLength += 1

          if (max < localLength) max = localLength
        } else {
          localLength = 2
        }
      }

      max
    }
  }

  val lines = io.Source.stdin.getLines().toIndexedSeq

  println(fibsegment(lines.last.split(" ").map(_.toInt).toIndexedSeq))
}

object Main {
    def main(args : Array[String]) {
        val n = readInt()
        val nums = readLine().split(" ") map { _.toInt }

        val (max, c) = nums.sliding(3).foldLeft((2, 2)) { (m, w) => w match {
            case Array(x, y, z) =>
                if(x + y == z)
                    (math.max(m._1, m._2 + 1), m._2 + 1)
                else
                    (m._1, 2)
            case Array(x, y) => (2, 0)
            case Array(x) => (1, 0)
        }}

        println(max)
    }
}

object B {
  def main(args: Array[String]) {
    val n = Integer.parseInt(readLine())
    val tokens: Array[String] = readLine().split(" ")
    val number: Array[Int] = new Array[Int](n)

    for(i <- Range(0, n))
    {
      number(i) = Integer.parseInt(tokens(i))
    }

    var counter = Math.min(n, 2)
    var max = counter
    for(i <- Range(2, n))
    {
      if(number(i) == (number(i-2) + number(i-1)))
      {
        counter = Math.max(3, counter + 1)
      }
      else
      {
        if(counter > max)
        {
          max = counter
        }

        counter = 0
      }
    }

    println(Math.max(counter, max))
  }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N = sc.nextInt
    val A = List.fill(N)(sc.nextLong)

    @tailrec
    def loop(acc: Int, cur: Int, as: List[Long]): Int = as match {
        case x :: y :: z :: _ => {
          if (x + y == z) loop(acc max (cur + 1), cur + 1, as.tail)
          else loop(acc, 0, as.tail)
        }
        case _ => acc + 2
      }

    loop(0, 0, A)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N = sc.nextInt
    val A = List.fill(N)(sc.nextLong)

    @tailrec
    def loop(acc: Int, cur: Int, as: List[Long]): Int = as match {
        case x :: y :: z :: _ => {
          if (x + y == z) loop(acc max (cur + 1), cur + 1, as.tail)
          else loop(acc, 0, as.tail)
        }
        case _ => (acc + 2) max N
      }

    loop(0, 0, A)
  }

  out.println(solve)
  out.close
}

object Fib extends App {
  def fibsegment(elements: IndexedSeq[Int]) = {

    if (elements.length == 1) 1
    else if (elements.length == 2) 2
    else {
      var max = 2
      var localLength = 2
      for (i <- 2 until elements.length) {
        if (elements(i) == elements(i - 1) + elements(i - 2)) {
          localLength += 1

          if (max < localLength) max = localLength
        } else {
          localLength = 0
        }
      }

      max
    }
  }

  val lines = io.Source.stdin.getLines().toIndexedSeq

  println(fibsegment(lines.last.split(" ").map(_.toInt).toIndexedSeq))
}


Sayaka Saeki is a member of the student council, which has $$$n$$$ other members (excluding Sayaka). The $$$i$$$-th member has a height of $$$a_i$$$ millimeters.It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wants to arrange all the members in a line such that the amount of photogenic consecutive pairs of members is as large as possible.A pair of two consecutive members $$$u$$$ and $$$v$$$ on a line is considered photogenic if their average height is an integer, i.e. $$$\frac{a_u + a_v}{2}$$$ is an integer.Help Sayaka arrange the other members to maximize the number of photogenic consecutive pairs.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 500$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$)  — the number of other council members. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$)  — the heights of each of the other members in millimeters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.

For each test case, output on one line $$$n$$$ integers representing the heights of the other members in the order, which gives the largest number of photogenic consecutive pairs. If there are multiple such orders, output any of them.

NoteIn the first test case, there is one photogenic pair: $$$(1, 1)$$$ is photogenic, as $$$\frac{1+1}{2}=1$$$ is integer, while $$$(1, 2)$$$ isn't, as $$$\frac{1+2}{2}=1.5$$$ isn't integer.In the second test case, both pairs are photogenic.

object cf1509a {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		for (nCase <- 1 to cases) {
			val nCount = readInt()
			val members = readInts()
			val odds = members.filter(_ % 2 == 1)
			val even = members.filter(_ % 2 == 0)
			val res = if (odds.size > even.size) odds ++ even else even ++ odds
			println(res.mkString(" "))
    }
  }
}

object cf1509a {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		for (nCase <- 1 to cases) {
			val nCount = readInt()
			val members = readInts()
			val odds = members.filter(_ % 2 == 1)
			val even = members.filter(_ % 2 == 0)
			val res = odds.slice(0, odds.size - odds.size % 2) ++ even ++ { if (odds.size % 2 == 1) Array(odds.last) else Array.emptyIntArray }
			println(res.mkString(" "))
    }
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Your task is to determine if $$$a$$$ has some subsequence of length at least $$$3$$$ that is a palindrome.Recall that an array $$$b$$$ is called a subsequence of the array $$$a$$$ if $$$b$$$ can be obtained by removing some (possibly, zero) elements from $$$a$$$ (not necessarily consecutive) without changing the order of remaining elements. For example, $$$[2]$$$, $$$[1, 2, 1, 3]$$$ and $$$[2, 3]$$$ are subsequences of $$$[1, 2, 1, 3]$$$, but $$$[1, 1, 2]$$$ and $$$[4]$$$ are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array $$$a$$$ of length $$$n$$$ is the palindrome if $$$a_i = a_{n - i - 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n$$$. For example, arrays $$$[1234]$$$, $$$[1, 2, 1]$$$, $$$[1, 3, 2, 2, 3, 1]$$$ and $$$[10, 100, 10]$$$ are palindromes, but arrays $$$[1, 2]$$$ and $$$[1, 2, 3, 1]$$$ are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 5000$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$ ($$$\sum n \le 5000$$$).

For each test case, print the answer — "YES" (without quotes) if $$$a$$$ has some subsequence of length at least $$$3$$$ that is a palindrome and "NO" otherwise.

NoteIn the first test case of the example, the array $$$a$$$ has a subsequence $$$[1, 2, 1]$$$ which is a palindrome.In the second test case of the example, the array $$$a$$$ has two subsequences of length $$$3$$$ which are palindromes: $$$[2, 3, 2]$$$ and $$$[2, 2, 2]$$$.In the third test case of the example, the array $$$a$$$ has no subsequences of length at least $$$3$$$ which are palindromes.In the fourth test case of the example, the array $$$a$$$ has one subsequence of length $$$4$$$ which is a palindrome: $$$[1, 2, 2, 1]$$$ (and has two subsequences of length $$$3$$$ which are palindromes: both are $$$[1, 2, 1]$$$).In the fifth test case of the example, the array $$$a$$$ has no subsequences of length at least $$$3$$$ which are palindromes.

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 C627B(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 C627B(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)

      val m = Array.fill[Int](5005)(0)
      var other = false
      var yes = false
      var prev = -1
      REP(n) { i =>
        if(m(a(i)) != 0 && other && a(i) != prev) {
          yes = true
        }
        if(m(a(i)) == 0 && i > 0) {
          m(a(i)) = 1
          other = true
        } else m(a(i)) += 1

        prev = a(i)
      }
      m.foreach { f =>
        if(f >= 3) yes = true
      }
      if(yes) out.println("YES") else out.println("NO")
    }
  }
}

object _1324B 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[Seq[Int]]
    val first, last = mutable.Map.empty[Int, Int]
    var result = false

    as.zipWithIndex foreach {case (a, i) =>
      first(a) = i min first.getOrElse(a, Int.MaxValue)
      last(a) = i max last.getOrElse(a, Int.MinValue)
      result |= (last(a) - first(a)) > 1
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.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 C627B(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 C627B(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)

      val m = Array.fill[Int](5005)(0)
      var other = false
      var yes = false
      var prev = -1
      REP(n) { i =>
        if(m(a(i)) != 0 && other && a(i) != prev) {
          yes = true
        }
        if(m(a(i)) == 0 && i > 0) {
          m(a(i)) = 1
          other = true
        } else m(a(i)) += 1

        prev = a(i)
      }
      if(yes) out.println("YES") else out.println("NO")
    }
  }
}