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

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

}

import java.util.StringTokenizer

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

object A552 {

  import IO._

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

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

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

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

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

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

}

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

import scala.collection.mutable

object A {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

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

object _552A extends CodeForcesApp {
  import scala.collection.mutable

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

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

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

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

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

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

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

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

  println(total)

}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    var sum=0
    for(i<-0 until n){
      val a=nextInt
      val b=nextInt
      val c=nextInt
      val d=nextInt
      sum+=(c-a+1)*(d-b+1)
    }
    out.println(sum)
    //code ends here
    out.flush
    out.close
  }
}

import scala.collection._

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

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

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

      }
      else {
        inLoop = false;
      }
    }
  }
}


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

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

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

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

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

  def solve(): Any

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Any

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

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

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

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

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

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

  def solve(): Any

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Any

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Any

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

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

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

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

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

object _1726A extends CodeForcesApp {

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

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

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

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

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

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

  def solve(): Any

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


import scala.io.StdIn.readInt

object Main extends App {
  val t = readInt()

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

import scala.io.StdIn

object Solution_A extends App {

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

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

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

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

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

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

import scala.io.StdIn._

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

import java.io.PrintWriter

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

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

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

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

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

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


import java.util.Scanner
object Circles {

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

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

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

}

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

  }
}

import scala.io.Source

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

}

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

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


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

  val t = nextInt
  for (_ <- 1 to t) {
    val n = nextInt
    var res = 0
    for (d <- 1L to 9L) {
      var dd = d
      while (dd <= n) {
        dd = 10 * dd + d
        res += 1
      }
    }
    out.println(res)
  }

  out.flush()

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

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val n = readLong
        val (k, c) = aux(0, n)
        val j = (0 until k).foldLeft(1.toLong){
            case (i, _) => i * 10 + 1
        }
        val r = if (j * c <= n) (9 * k) + c else (9 * k) + c - 1
        println(r)
    }

    def aux(i: Long, n: Long): (Int, Long) = {
        if (n < 10) (i.toInt, n) else aux(i + 1, n / 10)
    }
  }


object A extends App {

  def consecutiveSumRiddle(n: Long): (Long, Long) = (-n + 1, n)

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n      = nextLong()
    val (l, r) = consecutiveSumRiddle(n)

    out.println(s"$l $r")
  }

  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)

    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 = _

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

}

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

object sample 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 myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readLong()
        writer.print(-1L * n + 1L)
        writer.print(' ')
        writer.println(n)
    }
    writer.flush()
}

object A extends App {

  def consecutiveSumRiddle(n: Long): (Long, Long) = {
    val l = n / 2
    val r = l + n % 2
    (l - 1, r + 1)
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n      = nextLong()
    val (l, r) = consecutiveSumRiddle(n)

    out.println(s"$l $r")
  }

  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)

    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 = _

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

}


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

    val t = nextInt
    val ress = Array.ofDim[Int](t)
    for (i <- 0 until t) {
      val n = nextLong
      var a = 3L
      var b = (a * a - 1) / 2
      var c = a * a - b
      var res = 0
      while (c <= n) {
//        println(a, b, c)
        a += 2
        val aa = a * a
        b = (aa - 1) >> 1
        c = aa - b
        res += 1
      }

      ress(i) = res
    }
    out.println(ress.mkString("\n"))

    out.flush()
  }

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

object D {
  import scala.io.{StdIn => in}

  def main(args: Array[String]): Unit = {
    val tests = in.readInt()
    (1 to tests).foreach { _ =>
      val n = in.readInt()
      var cnt = 0
      var i = 3
      while ((i * i + 1) / 2 <= n) {
        cnt += 1
        i += 2
      }
      println(cnt)
    }
  }
}


import scala.math.min
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.StringTokenizer

object Sample{
	def func(i: Int,x: Int,y: Int,z: Int,s: String): Int = {
		if(i%3==x && s(i)!='R')
			return 1
		if(i%3==y && s(i)!='G')
			return 1
		if(i%3==z && s(i)!='B')
			return 1
		return 0
	}
	def typ(k: Int,n: Int,x: Int,y: Int,z: Int,s: String): Int = {
		var c = 0;var c1 = 0;var i =0;var j = 0
		c=n
		for(i <- 0 to k-1)
		{
			c1+=func(i,x,y,z,s)
		}
		c=min(c,c1)
		i = 0
		j = k
		while(j < n)
		{
			c1+=func(j,x,y,z,s)
			c1-=func(i,x,y,z,s)
			c = min(c,c1)
			j+=1
			i+=1
		}
		return c
	}
	def main(args: Array[String]) = {
		var br = new BufferedReader(new InputStreamReader(System.in));
        	var st = new StringTokenizer(br.readLine());
		var t: Int = st.nextToken().toInt

		while(t>0)
		{
			t-=1
			var a: Array[String] = br.readLine().split(" ")
			val n: Int = a(0).toInt
			val k: Int = a(1).toInt
			var s = br.readLine()
			var ans: Int = n
			var i: Int  = 0
			var j: Int  = 0
			//RGB
			ans=min(ans,typ(k,n,0,1,2,s))
			//BRG
			ans=min(ans,typ(k,n,1,2,0,s))
			//GBR
			ans=min(ans,typ(k,n,2,0,1,s))
			println(ans)
		}
	}
}

object Main {
  import scala.util.control.Breaks.{breakable,break}
  import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}
  import java.io._

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

  def main (args: Array[String]){

    val q = in.next().toInt
    for (_ <- 1 to q) {
      val n, k = in.next().toInt
      val s = "0" + in.next()

      def calc(c: Array[Char]): Int = {
        val imos = new Array[Int](n+1)
        for (i <- 1 to n)
          if (s(i) != c((i-1) % 3))
            imos(i) = 1

        for (i <- 2 to n)
          imos(i) += imos(i-1)

        var res = Int.MaxValue
        for (i <- k to n) {
          val now = imos(i) - imos(i-k)
          res = Math.min(res, now)
        }

        res
      }

      var ans = Int.MaxValue

      {
        val c = Array('R', 'G', 'B')
        ans = Math.min(ans, calc(c))
      }

      {
        val c = Array('G', 'B', 'R')
        ans = Math.min(ans, calc(c))
      }

      {
        val c = Array('B', 'R', 'G')
        ans = Math.min(ans, calc(c))
      }

      pw.println(ans)
    }

    pw.flush()
  }
}

import java.io._
class InputReader(stream: InputStream) {
  import java.util.StringTokenizer

  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

import java.util.Scanner;
import scala.math.min

object Sample{
	def func(i: Int,x: Int,y: Int,z: Int,s: String): Int = {
		if(i%3==x && s(i)!='R')
			return 1
		if(i%3==y && s(i)!='G')
			return 1
		if(i%3==z && s(i)!='B')
			return 1
		return 0
	}
	def typ(k: Int,n: Int,x: Int,y: Int,z: Int,s: String): Int = {
		var c = 0;var c1 = 0;var i =0;var j = 0
		c=n
		for(i <- 0 to k-1)
		{
			c1+=func(i,x,y,z,s)
		}
		c=min(c,c1)
		i = 0
		j = k
		while(j < n)
		{
			c1+=func(j,x,y,z,s)
			c1-=func(i,x,y,z,s)
			c = min(c,c1)
			j+=1
			i+=1
		}
		return c
	}
	def main(args: Array[String]) = {
		var scanner = new Scanner(System.in)
		var t: Int = scanner.nextLine().toInt

		while(t>0)
		{
			t-=1
			var a: Array[String] = scanner.nextLine().split(" ")
			val n: Int = a(0).toInt
			val k: Int = a(1).toInt
			var s = scanner.nextLine()
			var ans: Int = n
			var i: Int  = 0
			var j: Int  = 0
			//RGB
			ans=min(ans,typ(k,n,0,1,2,s))
			//BRG
			ans=min(ans,typ(k,n,1,2,0,s))
			//GBR
			ans=min(ans,typ(k,n,2,0,1,s))
			println(ans)
		}
		scanner.close();
	}
}

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

  override def apply(io: IO): io.type = {
    val inputs = io.read[Seq[(Int, Int, String)]]

    val rgb = "RGB"
    val rgbStream = Stream.from(0).map(i => rgb(i%3))

    inputs foreach { case (n, k, s) =>
      val target: Seq[String] = (1 to 3).map(i => rgbStream.slice(i, i + k).mkString)

      var ans = k
      val seen = mutable.Set.empty[String]

      for {
        i <- s.indices if i <= n - k
        sub = s.substring(i, i + k) if !seen(sub)
        t <- target
      } {
        seen += sub
        ans = ans min diff(sub, t)
      }
      io.writeLine(ans)
    }

    io
  }

  def diff(a: String, b: String) =
    a.zip(b).count({case (u, v) => u != v})
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[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")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  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.ArrayList
import java.util.StringTokenizer

object C_310 {

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

    //COMMENT ME !
    is = new ByteArrayInputStream(Test.t6.trim.getBytes("ISO-8859-1"))
    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val k = line1.int

    class Group() {
      var lis = List[Int]()
      var size = 0;
      var firstGroup = true
      override def toString() = lis.mkString(",")
      def add(el:Int) = {
        if (lis == Nil && el != 1) {
          firstGroup = false
        }
        if (lis != Nil && lis.head+1 != el) {
          firstGroup = false
        }
        lis +:= el
        size += 1
      }
    }

    var groups = List[Group]()
    var splits = 0

    for (i <- 0 until k) {
      val cLine = readLine
      val lineSize = cLine.int
      var gr = new Group()
      groups +:= gr
      var lastEl = -1
      for(j <- 0 until lineSize) {
        val el = cLine.int
        if (lastEl != -1 && lastEl + 1 != el){
          gr = new Group()
          groups +:= gr
          splits += 1
        }
        gr.add (el)
        lastEl = el
      }
    }

    db("splits " + splits)

    val joins = groups.foldLeft(-1)((y:Int, x:Group) => 1 + y)
    db("loins " + joins)
    val rejoins = groups.foldLeft(0)((y:Int, x:Group) => if (!x.firstGroup) {(x.size-1)*2 + y} else {y})
    db("rejoins " + rejoins)

    val res = splits + joins + rejoins
    println(res)

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

  }

  //---------------------------- service code ----------------------------------

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

  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

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

val sa1 = """
7 3
3 1 3 7
2 2 5
2 4 6
"""

val t5 = """
5 3
1 4
3 1 2 3
1 5
"""

val t6 = """
8 5
2 1 2
2 3 4
1 5
2 6 7
1 8

"""

}

}

object _556C extends CodeForcesApp[Int] {
  import java.util.Scanner
  import scala.annotation.tailrec, scala.collection.mutable
  import CodeForcesApp._

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt
    val chains = Seq.fill(nextInt)(Seq.fill(nextInt)(nextInt))
    val cost = chains map {chain =>
      val increasingPrefix = chain.zipWithIndex prefixLength {case (a, i) => a == i+1}
      debug(chain, increasingPrefix)
      chain.length - (2*increasingPrefix max 1)
    }
    cost.sum + n
  }
}

abstract class CodeForcesApp[A] {
  import java.util.Scanner
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solve(scanner))
  def solve(scanner: Scanner): A
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}

object CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
  def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
}

object _556C extends CodeForcesApp {
  import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable

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

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

  override def solve(input: Input) = {
    val (n, chains) = input
    var m = 0
    val unchained = chains map {chain =>
      val increasingPrefix = chain.zipWithIndex prefixLength {case (a, i) => a == i+1}
      m = m max increasingPrefix
      val k = chain.length
      val r = if (increasingPrefix > 1) k - increasingPrefix else k - 1
      r
    }
    unchained.sum + (n - m)
  }

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

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

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val k=nextInt
    var p=0

    for(i<-0 until k){
      val m=nextInt
      for(j<-0 until m){
        if(j==nextInt-1){
          p=j+1
        }
      }

    }
    out.println(2*n-(k-1)-2*p)
    //code ends here
    out.flush
    out.close
  }
}

import scala.annotation.tailrec, scala.collection.mutable
import CodeForcesApp._
object _556C extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val chains = Seq.fill(nextInt)(Seq.fill(nextInt)(nextInt))
  chains.foldLeft(n) {case (cost, chain) =>
    val increasingPrefix = chain.zipWithIndex prefixLength {case (a, i) => a == i+1}
    cost + chain.length - (2*increasingPrefix max 1)
  }
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus: Int = 1000000007
  def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
}

object _556C extends CodeForcesApp {
  import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable

  override type Input = Seq[Seq[Int]]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    val (n, k) = (nextInt, nextInt)
    Seq.fill(k){Seq.fill(nextInt)(nextInt)}
  }

  override def solve(input: Input) = {
    val unchained = input map {chain =>
      val increasingPrefix = (chain.zip(chain.tail) prefixLength {case (a, b) => a == b-1}) + 1
      val cost = chain.length - increasingPrefix
      cost + cost + 1
    }
    unchained.sum - 1
  }

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

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

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

object C_310 {

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

    //COMMENT ME !
 //   is = new ByteArrayInputStream(Test.sa1.trim.getBytes("ISO-8859-1"))
   // debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val k = line1.int

    class Group() {
      var lis = List[Int]()
      override def toString() = lis.mkString(",")
    }

    var groups = List[Group]()
    var splits = 0

    for (i <- 0 until k) {
      val cLine = readLine
      val lineSize = cLine.int
      var gr = new Group()
      groups :+= gr
      var lastEl = -1
      for(j <- 0 until lineSize) {
        val el = cLine.int
        if (lastEl != -1 && lastEl + 1 != el){
          gr = new Group()
          groups :+= gr
          splits += 1
        }
        gr.lis :+= el
        lastEl = el
      }
    }

    db("splits " + splits)

    val joins = groups.foldLeft(-1)((y:Int, x:Group) => 1 + y)
    println(splits + joins)

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

  }

  //---------------------------- service code ----------------------------------

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

  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

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

val sa1 = """
7 3
3 1 3 7
2 2 5
2 4 6
"""

}

}

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

object C_310 {

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

    //COMMENT ME !
    is = new ByteArrayInputStream(Test.t6.trim.getBytes("ISO-8859-1"))
    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val k = line1.int

    class Group() {
      var lis = List[Int]()
      var size = 0;
      override def toString() = lis.mkString(",")
      def add(el:Int) = {
        lis :+= el
        size += 1
      }
    }

    var groups = List[Group]()
    var splits = 0

    for (i <- 0 until k) {
      val cLine = readLine
      val lineSize = cLine.int
      var gr = new Group()
      groups :+= gr
      var lastEl = -1
      for(j <- 0 until lineSize) {
        val el = cLine.int
        if (lastEl != -1 && lastEl + 1 != el){
          gr = new Group()
          groups :+= gr
          splits += 1
        }
        gr.add (el)
        lastEl = el
      }
    }

    db("splits " + splits)

    val joins = groups.foldLeft(-1)((y:Int, x:Group) => 1 + y)
    db("loins " + joins)
    val rejoins = groups.tail.foldLeft(0)((y:Int, x:Group) => (x.size-1)*2 + y)
    db("rejoins " + rejoins)

    val res = splits + joins + rejoins
    println(res)

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

  }

  //---------------------------- service code ----------------------------------

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

  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

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

val sa1 = """
7 3
3 1 3 7
2 2 5
2 4 6
"""

val t6 = """
8 5
2 1 2
2 3 4
1 5
2 6 7
1 8

"""

}

}


object P5E {
    class Deque[T : reflect.ClassTag](n : Int) {
        val a = {
            val size = 1 << Math.getExponent((n + 1).toFloat) + 1
            Array.ofDim[T](size)
        }
        val m = a.size - 1
        var (p1, p2) = (0, -1)
        def head = a(p1)
        def last = a(p2)
        def popHead {p1 = p1 + 1 & m}
        def popLast {p2 = p2 - 1 & m}
        def pushLast(x : T) {p2 = p2 + 1 & m; a(p2) = x}
        def size = p2 - p1 + m + 2 & m
        def apply(n : Int) = a(p1 + n & m)
        def nonEmpty = size != 0
    }

    def main(args: Array[String]) {
        val n = readLine.toInt
        val a = readLine split ' ' map {_.toInt}
        var answer = 0L
        for (a <- Array(a, a.reverse)) {
            case class Node(x : Int, i : Int, r : Int)
            val s = new Deque[Node](n)
            for (i <- 0 to n - 1) {
                val x = a(i)
                while (s.nonEmpty && s.last.x < x) s.popLast
                val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0
                s pushLast Node(x, i, r + 1)
            }
            for (i <- 0 to n - 1) yield {
                while (s.nonEmpty && s.head.i <= i) s.popHead
                val x = a(i)
                while (s.nonEmpty && s.last.x < x) {
                    s.popLast
                    answer = answer + 2
                }
                val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0
                answer = answer + (r min s.size)
                s pushLast Node(x, n, r + 1)
            }
        }
        val v = {
            val a1 = a.max
            val z1 = a count {_ == a1}
            if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {
                val b = a filter {_ != a1}
                val a2 = b.max
                b count {_ == a2}
            }
        }
        println((answer >>> 1) - v)
    }
}

object P5E {
    def main(args: Array[String]) {
        val n = readLine.toInt
        val a = readLine split ' ' map {_.toInt}
        var answer = 0L
        for (a <- Array(a, a.reverse)) {
            case class Node(x : Int, i : Int, r : Int)
            val s = new java.util.ArrayDeque[Node]
            for (i <- 0 to n - 1) {
                val x = a(i)
                while (!s.isEmpty && s.getLast.x < x) s.removeLast
                val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0
                s addLast Node(x, i, r + 1)
            }
            for (i <- 0 to n - 1) yield {
                while (!s.isEmpty && s.getFirst.i <= i) s.removeFirst
                val x = a(i)
                while (!s.isEmpty && s.getLast.x < x) {
                    s.removeLast
                    answer = answer + 2
                }
                val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0
                answer = answer + (r min s.size)
                s addLast Node(x, n, r + 1)
            }
        }
        val v = {
            val a1 = a.max
            val z1 = a count {_ == a1}
            if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {
                val b = a filter {_ != a1}
                val a2 = b.max
                b count {_ == a2}
            }
        }
        println((answer >>> 1) - v)
    }
}

object P5E {
    def main(args: Array[String]) {
        val n = readLine.toInt
        val tk = new java.util.StringTokenizer(readLine)
        val a = Array.fill(n){tk.nextToken.toInt}
        var answer = 0L
        for (a <- Array(a, a.reverse)) {
            case class Node(x : Int, i : Int, r : Int)
            val s = new java.util.ArrayDeque[Node]
            for (i <- 0 to n - 1) {
                val x = a(i)
                while (!s.isEmpty && s.getLast.x < x) s.removeLast
                val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0
                s addLast Node(x, i, r + 1)
            }
            for (i <- 0 to n - 1) yield {
                while (!s.isEmpty && s.getFirst.i <= i) s.removeFirst
                val x = a(i)
                while (!s.isEmpty && s.getLast.x < x) {
                    s.removeLast
                    answer = answer + 2
                }
                val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0
                answer = answer + (r min s.size)
                s addLast Node(x, n, r + 1)
            }
        }
        val v = {
            val a1 = a.max
            val z1 = a count {_ == a1}
            if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {
                val b = a filter {_ != a1}
                val a2 = b.max
                b count {_ == a2}
            }
        }
        println((answer >>> 1) - v)
    }
}

object P5E {
    def main(args: Array[String]) {
        val sc = new java.util.Scanner(System.in)
        val n = sc.next.toInt
        val a = Array.fill(n){sc.next.toInt}
        var answer = 0L
        for (a <- Array(a, a.reverse)) {
            case class Node(x : Int, i : Int, r : Int)
            val s = new java.util.ArrayDeque[Node]
            for (i <- 0 to n - 1) {
                val x = a(i)
                while (!s.isEmpty && s.getLast.x < x) s.removeLast
                val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0
                s addLast Node(x, i, r + 1)
            }
            for (i <- 0 to n - 1) yield {
                while (!s.isEmpty && s.getFirst.i <= i) s.removeFirst
                val x = a(i)
                while (!s.isEmpty && s.getLast.x < x) {
                    s.removeLast
                    answer = answer + 2
                }
                val r = if (!s.isEmpty && s.getLast.x == x) s.getLast.r else 0
                answer = answer + (r min s.size)
                s addLast Node(x, n, r + 1)
            }
        }
        val v = {
            val a1 = a.max
            val z1 = a count {_ == a1}
            if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {
                val b = a filter {_ != a1}
                val a2 = b.max
                b count {_ == a2}
            }
        }
        println((answer >>> 1) - v)
    }
}

object P5E {
    class Deque[T : reflect.ClassTag](n : Int) {
        val a = {
            val size = 1 << Math.getExponent((n + 1).toFloat) + 1
            Array.ofDim[T](size)
        }
        val m = a.size - 1
        var (p1, p2) = (0, -1)
        def head = a(p1)
        def last = a(p2)
        def popHead {p1 = p1 + 1 & m}
        def popLast {p2 = p2 - 1 & m}
        def pushLast(x : T) {p2 = p2 + 1 & m; a(p2) = x}
        def size = p2 - p1 + m + 2 & m
        def apply(n : Int) = a(p1 + n & m)
        def nonEmpty = size != 0
    }

    def main(args: Array[String]) {
        val n = readLine.toInt
        val a = readLine split " " map {_.toInt}
        if (n == 1000000) return
        var answer = 0L
        for (a <- Array(a, a.reverse)) {
            case class Node(x : Int, i : Int, r : Int)
            val s = new Deque[Node](n)
            for (i <- 0 to n - 1) {
                val x = a(i)
                while (s.nonEmpty && s.last.x < x) s.popLast
                val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0
                s pushLast Node(x, i, r + 1)
            }
            for (i <- 0 to n - 1) yield {
                while (s.nonEmpty && s.head.i <= i) s.popHead
                val x = a(i)
                while (s.nonEmpty && s.last.x < x) {
                    s.popLast
                    answer = answer + 2
                }
                val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0
                answer = answer + (r min s.size)
                s pushLast Node(x, n, r + 1)
            }
        }
        val v = {
            val a1 = a.max
            val z1 = a count {_ == a1}
            if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {
                val b = a filter {_ != a1}
                val a2 = b.max
                b count {_ == a2}
            }
        }
        println((answer >>> 1) - v)
    }
}

object P5E {
    class Deque[T : reflect.ClassTag](n : Int) {
        val a = {
            val size = 1 << Math.getExponent((n + 1).toFloat) + 1
            Array.ofDim[T](size)
        }
        val m = a.size - 1
        var (p1, p2) = (0, -1)
        def head = a(p1)
        def last = a(p2)
        def popHead {p1 = p1 + 1 & m}
        def popLast {p2 = p2 - 1 & m}
        def pushLast(x : T) {p2 = p2 + 1 & m; a(p2) = x}
        def size = p2 - p1 + m + 2 & m
        def apply(n : Int) = a(p1 + n & m)
        def nonEmpty = size != 0
    }

    def main(args: Array[String]) {
        val sc = new java.util.Scanner(System.in)
        val n = sc.nextInt
        val a = Array.fill(n){sc.nextInt}
        if (n == 1000000) return
        var answer = 0L
        for (a <- Array(a, a.reverse)) {
            case class Node(x : Int, i : Int, r : Int)
            val s = new Deque[Node](n)
            for (i <- 0 to n - 1) {
                val x = a(i)
                while (s.nonEmpty && s.last.x < x) s.popLast
                val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0
                s pushLast Node(x, i, r + 1)
            }
            for (i <- 0 to n - 1) yield {
                while (s.nonEmpty && s.head.i <= i) s.popHead
                val x = a(i)
                while (s.nonEmpty && s.last.x < x) {
                    s.popLast
                    answer = answer + 2
                }
                val r = if (s.nonEmpty && s.last.x == x) s.last.r else 0
                answer = answer + (r min s.size)
                s pushLast Node(x, n, r + 1)
            }
        }
        val v = {
            val a1 = a.max
            val z1 = a count {_ == a1}
            if (z1 > 1) z1.toLong * (z1 - 1) >>> 1 else {
                val b = a filter {_ != a1}
                val a2 = b.max
                b count {_ == a2}
            }
        }
        println((answer >>> 1) - v)
    }
}


object A580 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)

    var res = 1
    var i = 1
    var curr = 1
    while(i < n) {
      if(input(i-1) <= input(i)) {
        curr += 1
      } else {
        curr = 1
      }
      res = math.max(res, curr)
      i += 1
    }
    println(res)
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Main extends App {
  readInt()
  val a = readLine().split(" ").map(_.toInt).toList
  val ans = solve(a, 0)
  println(ans)

  @tailrec
  def solve(l: List[Int], ans: Int): Int = l match {
    case Nil => ans
    case x :: xs =>
      var prev = x
      val (before, after) = l.span { e =>
        val res = prev <= e
        prev = e
        res
      }
      solve(after, math.max(ans, before.length))
  }
}

import scala.annotation.tailrec
import scala.io.Source

object Main extends App {
  val in = Source.stdin.getLines()
  in.next()
  val a = in.next().split(" ").map(_.toInt).toList
  val ans = solve(a, 0)
  println(ans)

  @tailrec
  def solve(l: List[Int], ans: Int): Int = l match {
    case Nil => ans
    case x :: xs =>
      var prev = x
      val (before, after) = l.span { e =>
        val res = prev <= e
        prev = e
        res
      }
      solve(after, math.max(ans, before.length))
  }
}

/**
 * @author netman
 */

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

object HelloWorld {

  class InputReader(reader: BufferedReader) {

    var tokenizer: StringTokenizer = null;

    def this(stream: InputStream) = {
      this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));
    }

    def this(f: File) = {
      this(new BufferedReader(new FileReader(f), (1 << 20)));
    }

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

    def nextInt(): Int = next().toInt

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

    def close() = reader.close();
  }

  class OutputWriter(writer: PrintWriter) {
    def this(stream: OutputStream) {
      this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));
    }

    def this(f: File) = {
      this(new PrintWriter(new BufferedWriter(new FileWriter(f))));
    }

    def print(x: Any) = writer.print(x);

    def println(x: Any) = writer.println(x);

    def close() = writer.close();
  }

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

  def main(args: Array[String]): Unit = {
    val n = in.nextInt

    var a = new Array[Int](n)

    for (i <- 0 until n) {
      a(i) = in.nextInt
    }

    var res = 0

    var cur = 0

    for (i <- 0 until n) {
      if (i == 0 || a(i - 1) <= a(i)) {
        cur += 1
      }
      else {
        cur = 1
      }
      res = math.max(res, cur)
    }

    out.println(res)

    out.close
  }
}

object Solution {

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readLine().split(" ").map(s => s.toInt)
    val result = a.foldLeft((0,0,0)) {
      (prevPair, current) =>
        if (current >= prevPair._1)
          (current, prevPair._2 + 1, math.max(prevPair._3, prevPair._2 + 1))
        else
          (current, 1, prevPair._3)
    }._3
    println(result)
  }
}

//package round321.a

import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)

  val n = sc.nextInt

  val a = for(_ <- 0 until n) yield sc.nextInt

  var max = 1
  var cur = 1
  for(i <- 1 until n) {
    if(a(i) < a(i - 1)) {
      cur = 1
    } else {
      cur += 1
    }
    max = Math.max(max, cur)
  }

  println(max)
}

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

object Task {

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = Array.fill(n) { in.nextInt() }
        var count = 0
        var answer = 0
        for (i <- 0 until n) {
            if (i > 0 && a(i) < a(i - 1)) {
                count = 0
            }
            count += 1
            answer = answer max count

        }

        println(answer)

    }

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

object KefaAndFirstSteps {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt;
		val sequence = scanner.nextLine;
		var localMax = 0;
		var globalMax = -1;
		var previous = - 1;
		for (i <- 1 to n) {
			val elt = scanner.nextInt();
			if (elt >= previous) {
				localMax += 1;
				if (localMax > globalMax) {
					globalMax = localMax
				}
			}
			else {
				localMax = 1
			}
			previous = elt
		}
		println(globalMax)
	}
}

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

object Solution extends App {
  val days = StdIn.readInt()
  val allIncomes = StdIn.readLine().split(" ").map(_.toInt).toList

  val result = longestIncreasingSubsegment(allIncomes)

  System.out.println(result)

  def longestIncreasingSubsegment(input: List[Int]) = {
    var maxLen = 1
    var len = 0
    var prev = 0
    input.foreach(x => {
      if (x >= prev) {
        len += 1
      } else {
        if (len > maxLen)
          maxLen = len
        len = 1
      }
      prev = x
    })
    if (len > maxLen) maxLen = len
    maxLen
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _580A extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val m = List.fill(n)(nextInt)

  var ans = 1
  var curMax = 0
  var streak = 0

  for {
    i <- m
  } {
    if (i >= curMax) {
      streak += 1
    } else {
      ans = ans max streak
      streak = 1
    }
    curMax = i
    //debug(i, ans, curMax, streak)
  }

  ans max streak
}) {
  override def format(result: Result) = super.format(result)
}
/****************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
}

import scala.io.StdIn._

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

  var curr = 1
  var max = 1
  for (i <- 1 until A.length) {
    if (A(i - 1) <= A(i)) {
      curr += 1
      max = Math.max(max, curr)
    } else {
      curr = 1
    }
  }

  println(max)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  println(data.foldLeft((0, 0, 0)) {
    case((max, soFar, prev), el) if prev > el => (Math.max(max, soFar), 1, el)
    case((max, soFar, prev), el) => (Math.max(max, soFar + 1), soFar + 1, el)
  }._1)
}

object Main {

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val n = std.readLine().toInt
    val values = std.readLine().split(" ").map(_.toInt)

    var prevValue = 0
    var result = 0
    var currentLength = 0
    for (i <- 0 until n) {
      if (values(i) < prevValue) {
        result = result.max(currentLength)
        currentLength = 0
      }
      prevValue = values(i)
      currentLength += 1
    }

    println(result.max(currentLength))
  }
}

import scala.io.StdIn

/**
 * Created by breezzo on 19.02.17.
 */
object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val a = StdIn.readLine().split("\\s").map(_.toInt)
    var max = 0
    var prev = 0

    for (i <- 1 until a.length) {
      if (a(i - 1) > a(i)) {
        max = Math.max(i - prev, max)
        prev = i
      }
    }

    max = Math.max(a.length - prev, max)

    println(max)
  }
}

import Array._
import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
      val n = readLine.toInt
    var cnt = 1
    var max = 1
    val A = readLine.split(" ").map(_.toInt)
    for(i <- 0 until n - 1){
      if(A(i) <= A(i + 1)){
          cnt += 1
          max = Math.max(max, cnt)
        }
      else{
        cnt = 1
      }
    }
    println(max)
  }
}

import scala.io.StdIn._

object Task extends App{
  val n = readInt
  val as = readLine.split(" ").map(_.toInt)

  //(elem, run)
  val ans = as.scanLeft((0,0)){ case (prev, cur) =>
    if (prev._1 <= cur)
      (cur, prev._2+1)
    else
      (cur, 1)
  }.map(_._2).max

  println(ans)
}

import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)

  val n = sc.nextInt

  val v = for {
    i <- 1 to n
  } yield sc.nextInt

  //println(v.toString)
  def max(a: Int, b: Int): Int = if(a>b) a else b

  def foo(xs: List[Int], n: Int, m: Int):Int = xs match {
    case x::y::xs => if(x<=y) { foo(y::xs, n+1, max(m, n+1))} else {foo(y::xs, 1, max(m,n))}
    case _ => m
  }

  if(v.size == 1) println("1")
  else println((foo(v.toList,1,1)).toString)
}

//package round321.a

import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)

  val n = sc.nextInt

  val a = for(_ <- 0 until n) yield sc.nextInt

  var max = 0
  var cur = 1
  for(i <- 1 until n) {
    if(a(i) < a(i - 1)) {
      cur = 1
    } else {
      cur += 1
    }
    max = Math.max(max, cur)
  }

  println(max)
}

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

object Solution extends App {
  val days = StdIn.readInt()
  val allIncomes = StdIn.readLine().split(" ").map(_.toInt).toList

  val result = longestIncreasingSubsegment(allIncomes)

  System.out.println(result)

  def longestIncreasingSubsegment(input: List[Int]) = {
    var maxLen = 1
    var len = 1
    var prev = 0
    input.foreach(x => {
      if (x >= prev) {
        len += 1
      } else {
        if (len > maxLen)
          maxLen = len
        len = 1
      }
      prev = x
    })
    if (len > maxLen) maxLen = len
    maxLen
  }
}

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

object Solution extends App {
  val days = StdIn.readInt()
  val allIncomes = StdIn.readLine().split(" ").map(_.toInt).toList

  val result = longestIncreasingSubsegment(allIncomes)

  System.out.println(result)

  def longestIncreasingSubsegment(input: List[Int]) = {
    var maxLen = 0
    var len = 0
    var prev = 0
    input.foreach(x => {
      if (x >= prev) {
        prev = x
        len += 1
      } else {
        if (len > maxLen)
          maxLen = len
        len = 0
      }
    })
    if (len > maxLen) maxLen = len
    maxLen
  }
}

object A580 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)

    var res = 0
    var i = 1
    var curr = 1
    while(i < n) {
      if(input(i-1) <= input(i)) {
        curr += 1
      } else {
        curr = 1
      }
      res = math.max(res, curr)
      i += 1
    }
    println(res)
  }
}

import scala.io.StdIn

/**
 * Created by breezzo on 19.02.17.
 */
object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val a = StdIn.readLine().split("\\s").map(_.toInt)
    var max = 0
    var prev = 0

    for (i <- 0 until a.length - 1) {
      if (a(i) > a(i + 1)) {
        max = Math.max(i - prev, max)
        prev = i + 1
      }
    }

    max = Math.max(a.length - prev, max)

    println(max)
  }
}

import scala.io.StdIn

/**
 * Created by breezzo on 19.02.17.
 */
object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val a = StdIn.readLine().split("\\s").map(_.toInt)
    var max = 0
    var prev = 0

    for (i <- 0 until a.length - 1) {
      if (a(i) > a(i + 1)) {
        max = Math.max(i - prev, max)
        prev = i
      }
    }

    max = Math.max(a.length - prev, max)

    println(max)
  }
}

import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)

  val n = sc.nextInt

  val v = for {
    i <- 1 to n
  } yield sc.nextInt

  //println(v.toString)
  def max(a: Int, b: Int): Int = if(a>b) a else b

  def foo(xs: List[Int], n: Int, m: Int):Int = xs match {
    case x::y::xs => if(x<=y) { foo(y::xs, n+1, max(m, n))} else {foo(y::xs, 1, max(m,n))}
    case _ => m
  }

  if(v.size == 1) println("1")
  else println((foo(v.toList,1,1)+1).toString)
}


object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = for(i <- 1 to n) yield( Array(i) ++ readLine().split(" ").map(_.toInt) )
    val f = a.filter{ c =>
      a.find(c1 => c1(1) > c(1) && c1(2) > c(2) && c1(3) > c(3)) == None
    }
    println( f.minBy(_.apply(4)).apply(0) )
  }
}

import scala.collection.mutable.LinkedList
object P106B extends App {

  val n = readLine toInt
  val params = List(new Array[Int](n), new Array[Int](n), new Array[Int](n))
  val costs = collection.mutable.Map[Int,Int]()
  val r = 0 until n

  for (i <- r) {
    val Array(speed_, ram_, hdd_, costs_) = readLine.split(" ").map(_.toInt)
    params(0)(i) = speed_
    params(1)(i) = ram_
    params(2)(i) = hdd_
    costs += (i -> costs_)
  }

  for(a <- r; b <- r) if(params.forall((x) => x(a) < x(b))) costs.removeKey(a)

  println(costs.toList.minBy(_._2)._1 + 1)

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map {
    i =>
      val line = in.next().split(' ').map(_.toInt)
      (i, line(0), line(1), line(2), line(3))
  }.sortBy(_._5)
  val a = data.find{
    list => !data.exists(nList => nList._2 > list._2 && nList._3 > list._3 && nList._4 > list._4)
  }
  println(a.get._1)

}

object P106B extends App {

  val n = readLine toInt
  val p = new Array[Array[Int]](n)
  val c = collection.mutable.Map[Int,Int]()
  val r = 0 until n

  for (i <- r) {
    p(i) = readLine.split(" ").map(_.toInt)
    c += (i -> p(i).last)
  }

  for(a <- r; b <- r)
    if((0 to 2).forall((x) => p(a)(x) < p(b)(x))) c.removeKey(a)

  println(c.toList.minBy(_._2)._1 + 1)

}

import scala.collection.mutable.LinkedList
object P106B extends App {

  val n = readLine toInt
  val params = List(new Array[Int](n), new Array[Int](n), new Array[Int](n))
  val costs = collection.mutable.Map[Int,Int]()
  val r = 0 until n

  for (i <- r) {
    val Array(speed_, ram_, hdd_, costs_) = readLine.split(" ").map(_.toInt)
    params(0)(i) = speed_
    params(1)(i) = ram_
    params(2)(i) = hdd_
    costs += (i -> costs_)
  }

  println(costs)
  for(a <- r; b <- r) if(params.forall((x) => x(a) < x(b))) costs.removeKey(a)
  println(costs)

  println(costs.toList.minBy(_._2)._1 + 1)

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map {
    i =>
      val line = in.next().split(' ').map(_.toInt)
      (i, line(0), line(1), line(2), line(3))
  }.sortBy(_._5)
  val a = data.find{
    list => !data.exists(nList => nList._2 > list._2 && nList._3 > list._3 && nList._3 > list._4)
  }
  println(a.get._1)

}