Colossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for.Arkadi and Boris Strugatsky. Monday starts on SaturdayReading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: $$$a - (a \oplus x) - x = 0$$$ for some given $$$a$$$, where $$$\oplus$$$ stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some $$$x$$$, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many non-negative solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help.

Each test contains several possible values of $$$a$$$ and your task is to find the number of equation's solution for each of them. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of these values. The following $$$t$$$ lines contain the values of parameter $$$a$$$, each value is an integer from $$$0$$$ to $$$2^{30} - 1$$$ inclusive.

For each value of $$$a$$$ print exactly one integer — the number of non-negative solutions of the equation for the given value of the parameter. Print answers in the same order as values of $$$a$$$ appear in the input. One can show that the number of solutions is always finite.

NoteLet's define the bitwise exclusive OR (XOR) operation. Given two integers $$$x$$$ and $$$y$$$, consider their binary representations (possibly with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of the number $$$x$$$ and $$$y_i$$$ is the $$$i$$$-th bit of the number $$$y$$$. Let $$$r = x \oplus y$$$ be the result of the XOR operation of $$$x$$$ and $$$y$$$. Then $$$r$$$ is defined as $$$r_k \dots r_2 r_1 r_0$$$ where:$$$$$$ r_i = \left\{ \begin{aligned} 1, ~ \text{if} ~ x_i \ne y_i \\ 0, ~ \text{if} ~ x_i = y_i \end{aligned} \right. $$$$$$For the first value of the parameter, only $$$x = 0$$$ is a solution of the equation.For the second value of the parameter, solutions are $$$x = 0$$$ and $$$x = 2$$$.

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

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

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

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

  val pow2 = Array.ofDim[Long](32)
  pow2(0) = 1
  rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2)

  def solve(): Unit = {
    val t = ni()
    rep(t) { _ =>
      val a = ni()
      val ans = pow2(Integer.bitCount(a))
      out.println(ans)
    }
  }

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

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

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

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

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


On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 ≤ i ≤ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should be equal to each other, the heights of the 2-nd and the (n - 1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not. Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful.

The first line contains integer n (1 ≤ n ≤ 105) which is the number of trees. The second line contains integers ai (1 ≤ ai ≤ 105) which are the heights of the trees.

Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful.

object P058C extends App {
  val n = readInt
  val a = readLine.split(' ').map(_.toInt)
  val target = List.range(0, n).map(i => if (i <= (n-1)/2) i+1 else n-i)
  val m = collection.mutable.Map[Int, Int]()
  a.zip(target).foreach(x=>m.update(x._1-x._2, m.getOrElse(x._1-x._2, 0)+1))
  var maxval = 0
  for (k <- m.keys) {
    if (k >= 0 && m(k) > maxval) {
      maxval = m(k)
    }
  }
  println(n-maxval)
}


Monocarp is planning to host a martial arts tournament. There will be three divisions based on weight: lightweight, middleweight and heavyweight. The winner of each division will be determined by a single elimination system.In particular, that implies that the number of participants in each division should be a power of two. Additionally, each division should have a non-zero amount of participants.$$$n$$$ participants have registered for the tournament so far, the $$$i$$$-th of them weighs $$$a_i$$$. To split participants into divisions, Monocarp is going to establish two integer weight boundaries $$$x$$$ and $$$y$$$ ($$$x < y$$$). All participants who weigh strictly less than $$$x$$$ will be considered lightweight. All participants who weigh greater or equal to $$$y$$$ will be considered heavyweight. The remaining participants will be considered middleweight.It's possible that the distribution doesn't make the number of participants in each division a power of two. It can also lead to empty divisions. To fix the issues, Monocarp can invite an arbitrary number of participants to each division.Note that Monocarp can't kick out any of the $$$n$$$ participants who have already registered for the tournament.However, he wants to invite as little extra participants as possible. Help Monocarp to choose $$$x$$$ and $$$y$$$ in such a way that the total amount of extra participants required is as small as possible. Output that amount.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of the registered participants. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the weights of the registered participants. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the smallest number of extra participants Monocarp is required to invite after he chooses the weight boundaries $$$x$$$ and $$$y$$$.

NoteIn the first testcase of the example, Monocarp can choose $$$x=2$$$ and $$$y=3$$$. Lightweight, middleweight and heavyweight divisions will have $$$2$$$, $$$1$$$ and $$$1$$$ participants, respectively. They all are powers of two, so no extra participants are required.In the second testcase of the example, regardless of the choice of $$$x$$$ and $$$y$$$, one division will have $$$1$$$ participant, the rest will have $$$0$$$. Thus, Monocarp will have to invite $$$1$$$ participant into both of the remaining divisions.In the third testcase of the example, Monocarp can choose $$$x=1$$$ and $$$y=2$$$. Lightweight, middleweight and heavyweight divisions will have $$$0$$$, $$$3$$$ and $$$3$$$ participants, respectively. So an extra participant is needed in each division.In the fourth testcase of the example, Monocarp can choose $$$x=8$$$ and $$$y=9$$$. Lightweight, middleweight and heavyweight divisions will have $$$8$$$, $$$0$$$ and $$$0$$$ participants, respectively. Middleweight and heavyweight division need an extra participant each.

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

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

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Long](n+1)
        val l = new Array[Long](n+2)
        val r = new Array[Long](n+2)
        val p = new Array[Long](40)
        for (i <- 1 to n) {
            arr(readInt()) += 1
        }
        for (i <- 1 to n) {
            l(i) = l(i-1) + arr(i)
        }
        for (i <- (1 to n).reverse) {
            r(i) = r(i+1) + arr(i)
        }
        p(0) = 1
        for (i <- 1 to 37) {
            p(i) = 2L * p(i-1)
        }
        var ans = p(37)
        var pl = 0
        var pr = 0
        var cnt = 0L
        var pm = 0
        for (i <- 0 to 36) {
            while (pl < n && l(pl+1) <= p(i)) {
                pl += 1
            }
            for (j <- 0 to 36) {
                pr = bs(pl+1, n+1, p(j)).toInt
                cnt = l(pr-1) - l(pl)
                pm = 0
                while (p(pm) < cnt) {
                    pm += 1
                }
                ans = min(ans, p(i) + p(j) + p(pm) - l(pl) - r(pr) - cnt)
            }
        }
        writer.println(ans)

        def check(kk: Long, fi: Long): Boolean = {
            if (r(kk.toInt) <= fi)
                return true
            return false
        }
        def bs(st:Long, en:Long, fi:Long): Long = {
            if (en - st <= 1L) {
                if (check(st, fi))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid, fi))
                return bs(st, mid, fi)
            else
                return bs(mid, en, fi)
        }
    }
    writer.flush()
}


Hooray! Polycarp turned $$$n$$$ years old! The Technocup Team sincerely congratulates Polycarp!Polycarp celebrated all of his $$$n$$$ birthdays: from the $$$1$$$-th to the $$$n$$$-th. At the moment, he is wondering: how many times he turned beautiful number of years?According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $$$1$$$, $$$77$$$, $$$777$$$, $$$44$$$ and $$$999999$$$. The following numbers are not beautiful: $$$12$$$, $$$11110$$$, $$$6969$$$ and $$$987654321$$$.Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).Help Polycarpus to find the number of numbers from $$$1$$$ to $$$n$$$ (inclusive) that are beautiful.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of one line, which contains a positive integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — how many years Polycarp has turned.

Print $$$t$$$ integers — the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between $$$1$$$ and $$$n$$$, inclusive.

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


Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).You are given an integer $$$n$$$. You need to find two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{18}$$$).

For each test case, print the two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.  It can be proven that an answer always exists. If there are multiple answers, print any.

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

}


A Pythagorean triple is a triple of integer numbers $$$(a, b, c)$$$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $$$a$$$, $$$b$$$ and $$$c$$$, respectively. An example of the Pythagorean triple is $$$(3, 4, 5)$$$.Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $$$c = a^2 - b$$$.Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $$$(3, 4, 5)$$$: $$$5 = 3^2 - 4$$$, so, according to Vasya's formula, it is a Pythagorean triple.When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print one integer — the number of triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean according both to the real definition and to the formula Vasya came up with.

NoteThe only Pythagorean triple satisfying $$$c = a^2 - b$$$ with $$$1 \le a \le b \le c \le 9$$$ is $$$(3, 4, 5)$$$; that's why the answer for $$$n = 3$$$ is $$$0$$$, and the answer for $$$n = 6$$$ (and for $$$n = 9$$$) is $$$1$$$.

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

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


Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:Given two binary numbers $$$a$$$ and $$$b$$$ of length $$$n$$$. How many different ways of swapping two digits in $$$a$$$ (only in $$$a$$$, not $$$b$$$) so that bitwise OR of these two numbers will be changed? In other words, let $$$c$$$ be the bitwise OR of $$$a$$$ and $$$b$$$, you need to find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will not be equal to $$$c$$$.Note that binary numbers can contain leading zeros so that length of each number is exactly $$$n$$$.Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $$$01010_2$$$ OR $$$10011_2$$$ = $$$11011_2$$$.Well, to your surprise, you are not Rudolf, and you don't need to help him$$$\ldots$$$ You are the security staff! Please find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will be changed.

The first line contains one integer $$$n$$$ ($$$2\leq n\leq 10^5$$$) — the number of bits in each number. The second line contains a binary number $$$a$$$ of length $$$n$$$. The third line contains a binary number $$$b$$$ of length $$$n$$$.

Print the number of ways to swap two bits in $$$a$$$ so that bitwise OR will be changed.

object Main {
  import java.io._
  import java.util.Scanner

  import collection.mutable.HashMap
  import scala.collection.{SortedSet, mutable}
  import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
      val n = ins.nextLine.toInt
      val s1 = ins.nextLine
      val s2 = ins.nextLine
      var bothZero = 0L
      var allZeros = 0L
      var oneAndZero = 0L
      var allOnes = 0L
      for(i <- s1.indices) {
        if(s1(i) == '0') {
          allZeros += 1
          if(s2(i) == '0') {
            bothZero += 1
          }
        } else {
          allOnes += 1
          if(s2(i) == '0') {
            oneAndZero += 1
          }
        }
      }

      println(bothZero * allOnes + oneAndZero * allZeros - bothZero * oneAndZero)
    }

  }

}


The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...".

NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG".

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

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

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


Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5. In one second, you can perform one of the two following operations:  Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b;  Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b. According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.

The first line contains integers n (1 ≤ n ≤ 105) and k (1 ≤ k ≤ 105) — the number of matryoshkas and matryoshka chains in the initial configuration. The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1 ≤ mi ≤ n), and then mi numbers ai1, ai2, ..., aimi — the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka). It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.

In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.

NoteIn the first sample test there are two chains: 1 → 2 and 3. In one second you can nest the first chain into the second one and get 1 → 2 → 3.In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.

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

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
}

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

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

"""

}

}


Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.

The first line of the input data contains an integer number n (3 ≤ n ≤ 106), n — the amount of hills around the capital. The second line contains n numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.

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


Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).

Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.

NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.

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

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

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

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

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

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


Vasya is choosing a laptop. The shop has n laptops to all tastes.Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.If all three properties of a laptop are strictly less than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.

The first line contains number n (1 ≤ n ≤ 100). Then follow n lines. Each describes a laptop as speed ram hdd cost. Besides,    speed, ram, hdd and cost are integers  1000 ≤ speed ≤ 4200 is the processor's speed in megahertz  256 ≤ ram ≤ 4096 the RAM volume in megabytes  1 ≤ hdd ≤ 500 is the HDD in gigabytes  100 ≤ cost ≤ 1000 is price in tugriks  All laptops have different prices.

Print a single number — the number of a laptop Vasya will choose. The laptops are numbered with positive integers from 1 to n in the order in which they are given in the input data.

NoteIn the third sample Vasya considers the first and fifth laptops outdated as all of their properties cannot match those of the third laptop. The fourth one is the cheapest among the laptops that are left. Thus, Vasya chooses the fourth laptop.

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

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

  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)

}