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

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

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

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


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)

    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

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


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

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

  }
}


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

}


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


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

  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
}


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

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

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

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


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)
      }
      m.foreach { f =>
        if(f >= 3) yes = true
      }
      if(yes) out.println("YES") else out.println("NO")
    }
  }
}

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


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

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

    case class pair(var minl: Int, var maxl:  Int, var minr: Int, var maxr:  Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return minl.compareTo(that.minl)
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n+1)
        var flag = false
        for (i <- 1 to n) {
            arr(i) = readInt()
            if (i > 1 && arr(i) <= arr(i-1))
                flag = true
        }
        if (n % 2 == 0) {
            writer.println("YES")
        } else {
            if (flag)
                writer.println("YES")
            else
                writer.println("NO")
        }
    }
    writer.flush()
}

object B extends App {

  def xorSpeciaLISt(xs: IndexedSeq[Int]): Boolean =
    xs.length % 2 == 0 || xs.indices.tail.exists { i => xs(i) <= xs(i - 1) }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val an = nextInts(n)

    xorSpeciaLISt(an) match {
      case true  => out.println("YES")
      case false => out.println("NO")
    }
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}


import scala.io.StdIn

object Test extends App {

  val s = StdIn.readLine().toInt
  (1 to s).foreach{_ =>
    var n = StdIn.readLine().toInt
    var ans = List.empty[Int]
    if(n == 10000) {
      println(1)
      println(n)
    } else {
      if (n / 1000 != 0) {
        val x = (n / 1000) * 1000
        ans = (x :: ans)
        n = n - x
      }
      if (n / 100 != 0) {
        val x = (n / 100) * 100
        ans = (x :: ans)
        n = n - x
      }
      if(n / 10 != 0){
        val x = (n / 10) * 10
        ans = (x :: ans)
        n = n - x
      }
      if(n != 0){
        ans = n :: ans
      }
      println(ans.size)
      ans.foreach(x => print(s"$x "))
      println()
    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int].toString.reverse

    val ans = n.indices collect {
      case i if n(i) - '0' > 0 => n(i) + ("0" * i)
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn.readInt

object Scala {
        def main(args: Array[String]): Unit = {
                var t: Int = readInt()
                while (t > 0) {
                        var x: Int = readInt()
                        var sum: Int = 1;
                        var ls: Array[Int] = Array()
                        while (x > 0) {
                                var m: Int = x % 10
                                if(m > 0) {
                                        ls = ls :+ (sum * m)
                                }
                                x /= 10
                                sum = sum * 10;
                        }
                        println(ls.length)
                        for(i <- ls) {
                                print(s"$i ")
                        }
                        println()
                        t -= 1
                }
        }
}

object C extends App {

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

  (0 until t).foreach { _ =>
    val x = scala.io.StdIn.readLine()
    println(x.filter(_ != '0').length)
    val m = x.zipWithIndex.collect {
        case (e,i) if(e != '0') => {
                e.asDigit * math.pow(10, x.length-i-1).toInt
            }
    }.mkString(" ")
    println(m)
  }
}

import scala.io.StdIn._

object Main2 extends App {
  val testNumber = readInt()
  1.to(testNumber).foreach {_ =>
    var digit = readInt()
    var answers: Vector[Int] = Vector()
    var divisor = 10
    while (digit > 0) {
      val answer = digit % divisor
      if (answer != 0) answers +:= answer
      digit = digit - answer
      divisor *= 10
    }
    println(answers.size)
    println(answers.mkString(" "))
  }
}

object ProblemA extends App {
  import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

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

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

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

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

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

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

  val n = in.nextInt()

  def solve(integer: Integer, step: Int = 1, res: List[Int] = List()): Unit = {
    if (integer == 0) {
      println(res.size)
      println(res.mkString(" "))
    } else {
      val k = integer % 10
      if (k != 0) {
        solve(integer / 10, step * 10, k * step :: res)
      } else {
        solve(integer / 10, step * 10, res)
      }
    }
  }

  for (i <- 1 to n) {
    val m = in.nextInt()
    solve(m)
  }

}

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

object Main {
   def main(args: Array[String]): Unit = {
      val count = StdIn.readInt()
      (0 until count)
        .map(_ => StdIn.readInt())
        .map(x => extractLocal(x))
        .foreach(x => {
             println(x.length)
             x.foreach(y => print(y.toString() + ' '))
             println()
          })
   }

   @tailrec
   def extractLocal(s: Int, result: List[Int] = Nil): List[Int] = {
     if (s == 0) {
       result
     } else if (s < 10) {
       s :: result
     } else {
       val min = findMin(s)
       val mod = s % min
       if (min < 10) min :: result
       else extractLocal(mod, (s - mod) :: result)
     }
   }

   def findMin(s: Int) =
     if (s > 1000) 1000
     else if (s > 100) 100
     else if (s > 10) 10
     else s

}

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

object A {

   @tailrec
   def ks(n: Int, acc: Seq[Int], l: Int): Seq[Int] =
      if (n < 10) acc :+ (n * l) else {
         ks(n / 10, acc ++ Some(n % 10).filter(_ != 0).map(_ * l), l * 10)
      }

   def solution(n: Int): Seq[Int] = {
      ks(n, Seq.empty, 1)
   }

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine().toInt)) {
         val result = A.solution(StdIn.readLine().toInt)
         println(result.length)
         println(result.mkString(" "))
      }
   }
}

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

import scala.collection.immutable
import scala.collection.mutable.ListBuffer
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 C640B(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 C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t =ni()
    REP(t) { _ =>
      val n = ni()
      var x = n
      var tens = 1
      val ls = new ListBuffer[Int]
      while (x > 0) {
        val r = x % 10
        if(r * tens > 0) ls += r * tens
        tens *= 10
        x /= 10
      }
      out.println(ls.length)
      out.println(ls.mkString(" "))
    }
  }
}

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

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readLine()
    val l  = n.length()
    val rs = n.zipWithIndex.filterNot(_._1 == '0').map { case (c, i) => (c - 48) * math.pow(10, l - i - 1).toInt }

    println(rs.length)
    println(rs.mkString(" "))
  }
}

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

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readLine()
    val rs = n.reverse.zipWithIndex
      .collect { case (c, i) if c != '0' => (c - 48) * math.pow(10, i).toInt }

    println(rs.length)
    println(rs.mkString(" "))
  }
}

import scala.io.StdIn

object Test extends App {

  val s = StdIn.readLine().toInt
  (1 to s).foreach{_ =>
    var n = StdIn.readLine().toInt
    var ans = List.empty[Int]
    if(n == 10000)println(n) else {
      if (n / 1000 != 0) {
        val x = (n / 1000) * 1000
        ans = (x :: ans)
        n = n - x
      }
      if (n / 100 != 0) {
        val x = (n / 100) * 100
        ans = (x :: ans)
        n = n - x
      }
      if(n / 10 != 0){
        val x = (n / 10) * 10
        ans = (x :: ans)
        n = n - x
      }
      if(n != 0){
        ans = n :: ans
      }
      println(ans.size)
      ans.foreach(x => print(s"$x "))
      println()
    }
  }
}

import scala.io.StdIn.readInt

object Scala {
        def main(args: Array[String]): Unit = {
                var t: Int = readInt()
                while (t > 0) {
                        var x: Int = readInt()
                        var sum: Int = 1;
                        while (x > 0) {
                                var m: Int = x % 10
                                if(m > 0) {
                                        print(s"${sum * m} ")
                                }
                                x /= 10
                                sum = sum * 10;
                        }
                        println()
                        t -= 1
                }
        }
}


import scala.io.StdIn.readLine
object Main {
    def main(args: Array[String]): Unit = {
      val lines = readLine.split(" ").map(_.toInt)
      val n = lines(0)
      val k = lines(1)
      if (k == 1) {
        print((1 to n).mkString(" "))
      }
      else {
        var a = 1
        var b = n

        for (i <- 1 to k/2) {
            print(b + " " + a + " ")
            a += 1
            b -= 1

        }

        if (k%2 != 0) {
            print((a to b).reverse.mkString(" "))
        }
        else {
            print((a to b).mkString(" "))
        }

      }

    }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val r = (0 until k).map { i =>
    if (i % 2 != 0) n - i / 2
    else i / 2 + 1
  }.toList
  val d = r.last
  val z = (k until n).map {
    i => if (d > n / 2) d - i + k - 1
      else d + i - k + 1
  }.toList
  println((r ::: z).mkString(" "))
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main {

  val br = new BufferedReader(new InputStreamReader(System.in))
  var st = new StringTokenizer(br.readLine())

  def nextDouble = next.toDouble
  def nextLong = next.toLong
  def nextInt = next.toInt

  def next = {
    while (!st.hasMoreTokens)
      st = new StringTokenizer(br.readLine())
    st.nextToken()
  }

  def main(args: Array[String]) {
    val n = nextInt
    val k = nextInt

    var inc = -1
    var cur = n
    print(n + " ")
    for (i <- k to 1 by -1) {
      cur += inc * i
      print(cur + " ")
      inc = -inc
    }
    for (i <- n - k - 1 to 1 by -1)
      print(i + " ")
  }

}

import scala.collection._

object A extends App {

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

  val Array(n, k) = readLongs(2)

  var l = 1l
  var r = n

  val res = new mutable.ArrayBuilder.ofLong

  res += l
  l += 1

  for (i <- 1l until k) {
    if (i % 2 == 1) {
      res += r
      r -= 1
    } else {
      res += l
      l += 1
    }
  }

  if (k % 2 == 0) {
    for (i <- k + 1 to n) {
      res += r
      r -= 1
    }
  } else {
    for (i <- k + 1 to n) {
      res += l
      l += 1
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.result.mkString(" "))
  Console.flush

}

import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.ArrayBuilder

object _482A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt

  if (k == 1) println((1 to n).mkString(" "))
  else {
    // e.g. n = 8
    // 2 3 4 5 6 7 |8 1    <- k = 2
    // 7 6 5 4 3 |2 8 1    <- k = 3
    // 3 4 5 6 |7 2 8 1    <- k = 4
    // 6 5 4 |3 7 2 8 1    <- k = 5
    // 4 5 |6 3 7 2 8 1    <- k = 6
    // 5 |4 6 3 7 2 8 1    <- k = 7

    //e.g. n = 5
    // 2 3 4 5 1
    // 4 3 2 5 1
    // 3 4 2 5 1

    val ans = new ArrayBuilder.ofInt
    ans += 1
    ans += n

    def doit(i: Int, pre: Int, left: Int, right: Int) {
      if (i < n) {
        if (i >= k) {
          if ((pre - left).abs == 1) {
            ans += left
            doit(i + 1, left, left + 1, right)
          } else {
            ans += right
            doit(i + 1, right, left, right - 1)
          }
        } else {
          if (i % 2 == 0) {
            ans += left
            doit(i + 1, left, left + 1, right)
          } else {
            ans += right
            doit(i + 1, right, left, right - 1)
          }
        }
      }
    }

    doit(2, n, 2, n - 1)
    println(ans.result().mkString(" "))
  }
}

import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.ArrayBuilder

object _482A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt

  if (k == 1) println((1 to n).mkString(" "))
  else {
    // e.g. n = 8
    // 2 3 4 5 6 7 |8 1    <- k = 2
    // 7 6 5 4 3 |2 8 1    <- k = 3
    // 3 4 5 6 |7 2 8 1    <- k = 4
    // 6 5 4 |3 7 2 8 1    <- k = 5
    // 4 5 |6 3 7 2 8 1    <- k = 6
    // 5 |4 6 3 7 2 8 1    <- k = 7

    //e.g. n = 5
    // 2 3 4 5 1
    // 4 3 2 5 1
    // 3 4 2 5 1

    val ans = new ArrayBuilder.ofInt
    ans += 1
    ans += n

    def doit(i: Int, left: Int, right: Int) {
      if (i < n) {
        if (i % 2 == 0) {
          ans += left
          doit(i + 1, left + 1, right)
        } else {
          ans += right
          doit(i + 1, left, right - 1)
        }
      }
    }

    doit(2, 2, n - 1)
    println(ans.result().mkString(" "))
  }
}

import scala.io.StdIn.readLine
object Main {
    def main(args: Array[String]): Unit = {
      val lines = readLine.split(" ").map(_.toInt)
      val n = lines(0)
      val k = lines(1)
      if (k == 1) {
        print((1 to n).mkString(" "))
      }
      else {
        var a = 1
        var b = n

        for (i <- 1 to k/2) {
            print(b + " " + a)
            a += 1
            b -= 1
        }
        print(" ")
        if (k%2 != 0) {
            print((a to b).reverse.mkString(" "))
        }
        else {
            print((a to b).mkString(" "))
        }

      }

    }

}

import scala.collection._

object A extends App {

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

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

  var x = 1L

  val res = new mutable.ArrayBuilder.ofLong

  res += x
  for (i <- 1 to k) {
    x += i
    res += x
  }

  for (i <- k + 2 to n) {
    x += 1
    res += x
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.result.mkString(" "))
  Console.flush

}

import scala.collection._

object A extends App {

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

  val Array(n, k) = readLongs(2)

  var l = 1l
  var r = n

  val res = new mutable.ArrayBuilder.ofLong

  res += l
  l += 1

  for (i <- 1l until k) {
    if (i % 2 == 1) {
      res += r
      r -= 1
    } else {
      res += l
      l += 1
    }
  }

  for (i <- k + 1 to n) {
    res += l
    l += 1
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.result.mkString(" "))
  Console.flush

}