Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types:  Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1 ≤ x, y ≤ n) — are numbers of two of some company employees. If team(x) matches team(y), then nothing happens.  Merge departments team(x), team(x + 1), ..., team(y), where x and y (1 ≤ x ≤ y ≤ n) — the numbers of some two employees of the company. At that the crisis manager can sometimes wonder whether employees x and y (1 ≤ x, y ≤ n) work at the same department.Help the crisis manager and answer all of his queries.

The first line of the input contains two integers n and q (1 ≤ n ≤ 200 000, 1 ≤ q ≤ 500 000) — the number of the employees of the company and the number of queries the crisis manager has. Next q lines contain the queries of the crisis manager. Each query looks like type x y, where . If type = 1 or type = 2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type = 3, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.

For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.

import scala.collection._

object D extends App {

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

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  val uf = new UnionFind(n)
  val nexts = Array.tabulate(n)(_ + 1)

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

  for (_ <- 0 until q) {

    val Array(t, _x, _y) = readInts(3)
    val x = _x - 1
    val y = _y - 1

    t match {

      case 1 =>
        uf.union(x, y)

      case 2 =>
        var l = x + 1
        while (l <= y) {
          uf.union(l, x)
          val tmp = l
          l = nexts(l)
          nexts(tmp) = y + 1
        }

      case 3 =>
        println(if (uf.same(x, y)) "YES" else "NO")
    }
  }

  Console.flush
}

import scala.collection._

object D extends App {

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

  val Array(n) = readInts(1)

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

  println()

  Console.flush
}


This is a harder version of the problem. In this version, $$$n \le 300\,000$$$.Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not.The cyclical shift of the string $$$s$$$ of length $$$n$$$ by $$$k$$$ ($$$0 \leq k < n$$$) is a string formed by a concatenation of the last $$$k$$$ symbols of the string $$$s$$$ with the first $$$n - k$$$ symbols of string $$$s$$$. For example, the cyclical shift of string "(())()" by $$$2$$$ equals "()(())".Cyclical shifts $$$i$$$ and $$$j$$$ are considered different, if $$$i \ne j$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 300\,000$$$), the length of the string. The second line contains a string, consisting of exactly $$$n$$$ characters, where each of the characters is either "(" or ")".

The first line should contain a single integer — the largest beauty of the string, which can be achieved by swapping some two characters. The second line should contain integers $$$l$$$ and $$$r$$$ ($$$1 \leq l, r \leq n$$$) — the indices of two characters, which should be swapped in order to maximize the string's beauty. In case there are several possible swaps, print any of them.

NoteIn the first example, we can swap $$$7$$$-th and $$$8$$$-th character, obtaining a string "()()()()()". The cyclical shifts by $$$0, 2, 4, 6, 8$$$ of this string form a correct bracket sequence.In the second example, after swapping $$$5$$$-th and $$$10$$$-th character, we obtain a string ")(())()()(()". The cyclical shifts by $$$11, 7, 5, 3$$$ of this string form a correct bracket sequence.In the third example, swap of any two brackets results in $$$0$$$ cyclical shifts being correct bracket sequences.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._
  case class Ans(num: Int, i: Int, j: Int)
  def maxAns(a1: Ans, a2: Ans) = if (a1.num >= a2.num) a1 else a2
  val zero = Ans(0, 0, 0)
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val n = ni()
    val s = ns(n)
    val bal = Array.ofDim[Int](n)
    REP(n) { i =>
      if (i > 0) bal(i) = bal(i - 1)
      bal(i) += (if (s(i) == '(') 1 else -1)
    }
    val minBal = bal.min
    val cntMin = bal.count(_ == minBal)

    val cumMin, cumPlus1, cumPlus2 = Array.ofDim[Int](n + 1)
    REP(n) { i =>
      if (bal(i) == minBal) cumMin(i + 1) = 1
      if (bal(i) == minBal + 1) cumPlus1(i + 1) = 1
      if (bal(i) == minBal + 2) cumPlus2(i + 1) = 1
    }
    REP(n) { i =>
      cumMin(i + 1) += cumMin(i)
      cumPlus1(i + 1) += cumPlus1(i)
      cumPlus2(i + 1) += cumPlus2(i)
    }
    debug(bal)
    debug(cumMin)
    debug(cumPlus1)
    debug(cumPlus2)

    def show(ans: Ans): Unit = {
      out.println(ans.num)
      out.println(s"${ans.i+1} ${ans.j+1}")
    }

    if (bal.last != 0) {
      show(zero)
      return
    }

    def cntEq: Ans = {
      var i, j = 0
      var ans = Ans(cntMin, 0, 0)
      while(i < n) {
        j = i
        var p1, p2 = -1
        while(j < n && bal(j) >= minBal + 2) {
          if (s(j) == '(' && p1 == -1) p1 = j
          if (s(j) == ')') p2 = j
          j += 1
        }
        if (j < n && s(j) == ')') p2 = j
        debug(s"$i $j $p1 $p2")
        if (p1 != -1 && p2 != -1 && p1 < p2) {
          val cntNew = cumPlus2(p2) - cumPlus2(p1)
          ans = maxAns(ans, Ans(cntMin + cntNew, p1, p2))
        }
        i = j + 1
      }

      ans
    }

    def cntMinus1: Ans = {
      var i, j = 0
      var ans = Ans(0, 0, 0)
      while(i < n) {
        j = i
        var p1, p2 = -1
        while(j < n && bal(j) > minBal) {
          if (s(j) == '(' && p1 == -1) p1 = j
          if (s(j) == ')') p2 = j
          j += 1
        }
        if (j < n && s(j) == ')') p2 = j
        debug(s"$i $j $p1 $p2")
        if (p1 != -1 && p2 != -1 && p1 < p2) {
          val cntNew = cumPlus1(p2) - cumPlus1(p1)
          ans = maxAns(ans, Ans(cntNew, p1, p2))
        }
        i = j + 1
      }

      ans
    }

    def cntPlus1: Ans = {
      // minを全部消す
      var p1, p2 = -1
      var ans = Ans(0, 0, 0)
      var i = bal.indexWhere(_ == minBal)
      while(i >= 0) {
        if (s(i) == ')' && p1 == -1) p1 = i
        i -= 1
      }
      var j = bal.lastIndexWhere(_ == minBal) + 1
      while(j < n) {
        if (s(j) == '(' && p2 == -1) p2 = j
        j += 1
      }
      if (p1 != -1 && p2 != -1 && p1 < p2) {
        val l = cumPlus1(p1)
        val r = cumPlus1.last - cumPlus1(p2)
        ans = maxAns(ans, Ans(l + r, p1, p2))
      }

      ans
    }

    def cntPlus2: Ans = {
      // minとmin+1を全部消す
      var p1, p2 = -1
      var v = 0
      var i = bal.indexWhere(a => a == minBal || a == minBal + 1)
      while(i >= 0) {
        if (s(i) == ')' && p1 == -1) {
          val oldP2 = cumPlus2(i)
          val newP2 = cumMin.last - cumMin(i)
          if (v < oldP2 + newP2) {
            p1 = i
            v = oldP2 + newP2
          }
        }
        i -= 1
      }
      v = 0
      var j = bal.lastIndexWhere(a => a == minBal || a == minBal + 1) + 1
      while(j < n) {
        if (s(j) == '(' && p2 == -1) {
          val oldP2 = cumPlus2.last - cumPlus2(j)
          val newP2 = cumMin(j)
          if (v < oldP2 + newP2) {
            p2 = j
            v = oldP2 + newP2
          }
        }
        j += 1
      }
      if (p1 != -1 && p2 != -1 && p1 < p2) {
        val oldP2 = cumPlus2(p1) + cumPlus2.last - cumPlus2(p2)
        val newP2 = cumMin(p2) - cumMin(p1)
        Ans(oldP2 + newP2, p1, p2)
      } else {
        zero
      }
    }

    debug(s"cntEq:$cntEq")
    debug(s"cntMinus1:$cntMinus1")
    debug(s"cntPlus1:$cntPlus1")
    debug(s"cntPlus2:$cntPlus2")

    val ans = Seq(cntEq, cntMinus1, cntPlus1, cntPlus2).maxBy(_.num)
    show(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._
  case class Ans(num: Int, i: Int, j: Int)
  def maxAns(a1: Ans, a2: Ans) = if (a1.num >= a2.num) a1 else a2
  val zero = Ans(0, 0, 0)
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val n = ni()
    val s = ns(n)
    val bal = Array.ofDim[Int](n)
    REP(n) { i =>
      if (i > 0) bal(i) = bal(i - 1)
      bal(i) += (if (s(i) == '(') 1 else -1)
    }
    val minBal = bal.min
    val cntMin = bal.count(_ == minBal)

    val cumMin, cumPlus1, cumPlus2 = Array.ofDim[Int](n + 1)
    REP(n) { i =>
      if (bal(i) == minBal) cumMin(i + 1) = 1
      if (bal(i) == minBal + 1) cumPlus1(i + 1) = 1
      if (bal(i) == minBal + 2) cumPlus2(i + 1) = 1
    }
    REP(n) { i =>
      cumMin(i + 1) += cumMin(i)
      cumPlus1(i + 1) += cumPlus1(i)
      cumPlus2(i + 1) += cumPlus2(i)
    }
    debug(bal)
    debug(cumMin)
    debug(cumPlus1)
    debug(cumPlus2)

    def show(ans: Ans): Unit = {
      out.println(ans.num)
      out.println(s"${ans.i+1} ${ans.j+1}")
    }

    if (bal.last != 0) {
      show(zero)
      return
    }

    def cntEq: Ans = {
      var i, j = 0
      var ans = Ans(0, 0, 0)
      while(i < n) {
        j = i
        var p1, p2 = -1
        while(j < n && bal(j) >= minBal + 2) {
          if (s(j) == '(' && p1 == -1) p1 = j
          if (s(j) == ')') p2 = j
          j += 1
        }
        if (j < n && s(j) == ')') p2 = j
        debug(s"$i $j $p1 $p2")
        if (p1 != -1 && p2 != -1 && p1 < p2) {
          val cntNew = cumPlus2(p2) - cumPlus2(p1)
          ans = maxAns(ans, Ans(cntMin + cntNew, p1, p2))
        }
        i = j + 1
      }

      ans
    }

    def cntMinus1: Ans = {
      var i, j = 0
      var ans = Ans(0, 0, 0)
      while(i < n) {
        j = i
        var p1, p2 = -1
        while(j < n && bal(j) > minBal) {
          if (s(j) == '(' && p1 == -1) p1 = j
          if (s(j) == ')') p2 = j
          j += 1
        }
        if (j < n && s(j) == ')') p2 = j
        debug(s"$i $j $p1 $p2")
        if (p1 != -1 && p2 != -1 && p1 < p2) {
          val cntNew = cumPlus1(p2) - cumPlus1(p1)
          ans = maxAns(ans, Ans(cntNew, p1, p2))
        }
        i = j + 1
      }

      ans
    }

    def cntPlus1: Ans = {
      // minを全部消す
      var p1, p2 = -1
      var ans = Ans(0, 0, 0)
      var i = bal.indexWhere(_ == minBal)
      while(i >= 0) {
        if (s(i) == ')' && p1 == -1) p1 = i
        i -= 1
      }
      var j = bal.lastIndexWhere(_ == minBal) + 1
      while(j < n) {
        if (s(j) == '(' && p2 == -1) p2 = j
        j += 1
      }
      if (p1 != -1 && p2 != -1 && p1 < p2) {
        val l = cumPlus1(p1)
        val r = cumPlus1.last - cumPlus1(p2)
        ans = maxAns(ans, Ans(l + r, p1, p2))
      }

      ans
    }

    def cntPlus2: Ans = {
      // minとmin+1を全部消す
      var p1, p2 = -1
      var v = 0
      var i = bal.indexWhere(a => a == minBal || a == minBal + 1)
      while(i >= 0) {
        if (s(i) == ')' && p1 == -1) {
          val oldP2 = cumPlus2(i)
          val newP2 = cumMin.last - cumMin(i)
          if (v < oldP2 + newP2) {
            p1 = i
            v = oldP2 + newP2
          }
        }
        i -= 1
      }
      v = 0
      var j = bal.lastIndexWhere(a => a == minBal || a == minBal + 1) + 1
      while(j < n) {
        if (s(j) == '(' && p2 == -1) {
          val oldP2 = cumPlus2.last - cumPlus2(j)
          val newP2 = cumMin(j)
          if (v < oldP2 + newP2) {
            p2 = j
            v = oldP2 + newP2
          }
        }
        j += 1
      }
      if (p1 != -1 && p2 != -1 && p1 < p2) {
        val oldP2 = cumPlus2(p1) + cumPlus2.last - cumPlus2(p2)
        val newP2 = cumMin(p2) - cumMin(p1)
        Ans(oldP2 + newP2, p1, p2)
      } else {
        zero
      }
    }

    debug(s"cntEq:$cntEq")
    debug(s"cntMinus1:$cntMinus1")
    debug(s"cntPlus1:$cntPlus1")
    debug(s"cntPlus2:$cntPlus2")

    val ans = Seq(cntEq, cntMinus1, cntPlus1, cntPlus2).maxBy(_.num)
    show(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._
  case class Ans(num: Int, i: Int, j: Int)
  def maxAns(a1: Ans, a2: Ans) = if (a1.num >= a2.num) a1 else a2
  val zero = Ans(0, 0, 0)
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val n = ni()
    val s = ns(n)
    val bal = Array.ofDim[Int](n)
    REP(n) { i =>
      if (i > 0) bal(i) = bal(i - 1)
      bal(i) += (if (s(i) == '(') 1 else -1)
    }
    val minBal = bal.min
    val cntMin = bal.count(_ == minBal)

    val cumMin, cumPlus1, cumPlus2 = Array.ofDim[Int](n + 1)
    REP(n) { i =>
      if (bal(i) == minBal) cumMin(i + 1) = 1
      if (bal(i) == minBal + 1) cumPlus1(i + 1) = 1
      if (bal(i) == minBal + 2) cumPlus2(i + 1) = 1
    }
    REP(n) { i =>
      cumMin(i + 1) += cumMin(i)
      cumPlus1(i + 1) += cumPlus1(i)
      cumPlus2(i + 1) += cumPlus2(i)
    }
    debug(bal)
    debug(cumMin)
    debug(cumPlus1)
    debug(cumPlus2)

    def show(ans: Ans): Unit = {
      out.println(ans.num)
      out.println(s"${ans.i+1} ${ans.j+1}")
    }

    if (bal.last != 0) {
      show(zero)
      return
    }

    def cntEq: Ans = {
      var i, j = 0
      var ans = Ans(0, 0, 0)
      while(i < n) {
        j = i
        var p1, p2 = -1
        while(j < n && bal(j) >= minBal + 2) {
          if (s(j) == '(' && p1 == -1) p1 = j
          if (s(j) == ')') p2 = j
          j += 1
        }
        if (j < n && s(j) == ')') p2 = j
        debug(s"$i $j $p1 $p2")
        if (p1 != -1 && p2 != -1 && p1 < p2) {
          val cntNew = cumPlus2(p2) - cumPlus2(p1)
          ans = maxAns(ans, Ans(cntMin + cntNew, p1, p2))
        }
        i = j + 1
      }

      ans
    }

    def cntMinus1: Ans = {
      var i, j = 0
      var ans = Ans(0, 0, 0)
      while(i < n) {
        j = i
        var p1, p2 = -1
        while(j < n && bal(j) > minBal) {
          if (s(j) == '(' && p1 == -1) p1 = j
          if (s(j) == ')') p2 = j
          j += 1
        }
        debug(s"$i $j $p1 $p2")
        if (p1 != -1 && p2 != -1 && p1 < p2) {
          val cntNew = cumPlus1(p2) - cumPlus1(p1)
          ans = maxAns(ans, Ans(cntNew, p1, p2))
        }
        i = j + 1
      }

      ans
    }

    def cntPlus1: Ans = {
      // minを全部消す
      var p1, p2 = -1
      var ans = Ans(0, 0, 0)
      var i = bal.indexWhere(_ == minBal)
      while(i >= 0) {
        if (s(i) == ')' && p1 == -1) p1 = i
        i -= 1
      }
      var j = bal.lastIndexWhere(_ == minBal) + 1
      while(j < n) {
        if (s(j) == '(' && p2 == -1) p2 = j
        j += 1
      }
      if (p1 != -1 && p2 != -1 && p1 < p2) {
        val l = cumPlus1(p1)
        val r = cumPlus1.last - cumPlus1(p2)
        ans = maxAns(ans, Ans(l + r, p1, p2))
      }

      ans
    }

    def cntPlus2: Ans = {
      // minとmin+1を全部消す
      var p1, p2 = -1
      var v = 0
      var i = bal.indexWhere(a => a == minBal || a == minBal + 1)
      while(i >= 0) {
        if (s(i) == ')' && p1 == -1) {
          val oldP2 = cumPlus2(i)
          val newP2 = cumMin.last - cumMin(i)
          if (v < oldP2 + newP2) {
            p1 = i
            v = oldP2 + newP2
          }
        }
        i -= 1
      }
      v = 0
      var j = bal.lastIndexWhere(a => a == minBal || a == minBal + 1) + 1
      while(j < n) {
        if (s(j) == '(' && p2 == -1) {
          val oldP2 = cumPlus2.last - cumPlus2(j)
          val newP2 = cumMin(j)
          if (v < oldP2 + newP2) {
            p2 = j
            v = oldP2 + newP2
          }
        }
        j += 1
      }
      if (p1 != -1 && p2 != -1 && p1 < p2) {
        val oldP2 = cumPlus2(p1) + cumPlus2.last - cumPlus2(p2)
        val newP2 = cumMin(p2) - cumMin(p1)
        Ans(oldP2 + newP2, p1, p2)
      } else {
        zero
      }
    }

    debug(s"cntEq:$cntEq")
    debug(s"cntMinus1:$cntMinus1")
    debug(s"cntPlus1:$cntPlus1")
    debug(s"cntPlus2:$cntPlus2")

    val ans = Seq(cntEq, cntMinus1, cntPlus1, cntPlus2).maxBy(_.num)
    show(ans)
  }
}


Graph constructive problems are back! This time the graph you are asked to build should match the following properties.The graph is connected if and only if there exists a path between every pair of vertices.The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.The degree of a vertex is the number of edges incident to it.Given a sequence of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ construct a connected undirected graph of $$$n$$$ vertices such that:  the graph contains no self-loops and no multiple edges;  the degree $$$d_i$$$ of the $$$i$$$-th vertex doesn't exceed $$$a_i$$$ (i.e. $$$d_i \le a_i$$$);  the diameter of the graph is maximum possible. Output the resulting graph or report that no solution exists.

The first line contains a single integer $$$n$$$ ($$$3 \le n \le 500$$$) — the number of vertices in the graph. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n - 1$$$) — the upper limits to vertex degrees.

Print "NO" if no graph can be constructed under the given conditions. Otherwise print "YES" and the diameter of the resulting graph in the first line. The second line should contain a single integer $$$m$$$ — the number of edges in the resulting graph. The $$$i$$$-th of the next $$$m$$$ lines should contain two integers $$$v_i, u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$v_i \neq u_i$$$) — the description of the $$$i$$$-th edge. The graph should contain no multiple edges — for each pair $$$(x, y)$$$ you output, you should output no more pairs $$$(x, y)$$$ or $$$(y, x)$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val ms = 2 * (N - 1)
    if (A.sum < ms) {
      out.println("NO")
    } else {
      val mxIx = A.zipWithIndex.maxBy(_._1)._2
      val mxIx2 = A.zipWithIndex.filterNot(_._2 == mxIx).maxBy(_._1)._2

      val ones = A.zipWithIndex.filter(_._1 == 1).map(_._2)
      val twos = A.zipWithIndex.filter(_._1 > 1).map(_._2)

      if (A(mxIx2) == 1) {
        out.println(s"YES 2")
        out.println(N - 1)
        ones.foreach { v =>
          val u = mxIx
          out.println(s"${v+1} ${u+1}")
        }
      } else {
        val d = twos.length - 1 + min(2, ones.length) // 1-2-2-2-1
        out.println(s"YES $d")
        out.println(N - 1)

        val others = twos.filterNot(v => v == mxIx || v == mxIx2)
        val sorted = mxIx +: others :+ mxIx2
        sorted zip sorted.drop(1) foreach { case (v, u) =>
          out.println(s"${v+1} ${u+1}")
        }

        twos.foreach(v => A(v) -= 2)
        val it = Iterator(mxIx, mxIx2) ++ (for {
          v <- twos.iterator
          _ <- Iterator.fill(A(v))(v)
        } yield v)

        ones.foreach { v =>
          val u = it.next()
          out.println(s"${v+1} ${u+1}")
        }
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val ms = 2 * (N - 1)
    if (A.sum < ms) {
      out.println("NO")
    } else {
      val mxIx = A.zipWithIndex.maxBy(_._1)._2
      val mxIx2 = A.zipWithIndex.filterNot(_._2 == mxIx).maxBy(_._1)._2

      val ones = A.zipWithIndex.filter(_._1 == 1).map(_._2)
      val twos = A.zipWithIndex.filter(_._1 > 1).map(_._2)

      if (A(mxIx2) == 1) {
        out.println(s"YES 2")
        out.println(N - 1)
        ones.foreach { v =>
          val u = mxIx
          out.println(s"${v+1} ${u+1}")
        }
      } else {
        val d = twos.length - 1 + min(2, ones.length) // 1-2-2-2-1
        out.println(s"YES $d")
        out.println(N - 1)

        val others = twos.filterNot(v => v == mxIx || v == mxIx2)
        val sorted = mxIx +: others :+ mxIx2
        sorted zip sorted.drop(1) foreach { case (v, u) =>
          out.println(s"${v+1} ${u+1}")
        }

        A(mxIx) -= 1
        A(mxIx2) -= 1
        others.foreach(v => A(v) -= 2)
        val it = Iterator(mxIx, mxIx2) ++ (for {
          v <- twos.iterator
          _ <- Iterator.fill(A(v))(v)
        } yield v)

        ones.foreach { v =>
          val u = it.next()
          out.println(s"${v+1} ${u+1}")
        }
      }
    }
  }

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

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

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

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

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

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


Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.

The first line contains two space-separated integers x1, y1 ( - 106 ≤ x1, y1 ≤ 106) — the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≤ x2, y2 ≤ 106) — the coordinates of the university you are studying at. The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≤ ai, bi, ci ≤ 106; |ai| + |bi| > 0) — the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).

NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors):

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)

  case class Coord(x: Double, y: Double) {
    def ccw: Coord = Coord(-y, x)
    def +(o: Coord) = Coord(x + o.x, y + o.y)
  }

  val EPS = 1e-9
  def lt(x: Double, y: Double) = x < y - EPS
  def le(x: Double, y: Double) = x < y + EPS
  def gt(x: Double, y: Double) = x > y - EPS
  def ge(x: Double, y: Double) = x > y + EPS
  def eq(x: Double, y: Double) = abs(x - y) < EPS

  def solve(): Unit = {
    val H, U = Coord(ni(), ni())
    val N = ni()

    val INF = 1e9.toInt

    def y(a: Int, b: Int, c: Int, x: Int) = {
      -(a.toDouble * x + c) / b
    }

    var ans = 0
    REP(N) { _ =>
      import java.awt.geom.{Line2D, Point2D}
      val a, b, c = ni()

      // Y軸に平行
      if (b == 0) {
        val x = -c.toDouble / a
        if (le(min(H.x, U.x), x) && le(x, max(H.x, U.x))) ans += 1
      } else {
        val p1 = Coord(-INF, y(a, b, c, -INF))
        val p2 = Coord(INF, y(a, b, c, INF))
        if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, H.x, H.y, U.x, U.y)) ans += 1
      }
    }

    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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(x1, y1) = in.next().split(' ').map(_.toLong)
  var Array(x2, y2) = in.next().split(' ').map(_.toLong)
  val n = in.next().toInt
  println((1 to n).map(_ => in.next().split(' ').map(_.toInt)).count{
    case(Array(a, b, c)) =>
      val home = a * x1 + b * y1 + c
      val university = a * x2 + b * y2 + c
      (home > 0 && university < 0) || (home < 0 && university > 0)
  })
}

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)

  case class Coord(x: Double, y: Double) {
    def ccw: Coord = Coord(-y, x)
    def +(o: Coord) = Coord(x + o.x, y + o.y)
  }

  def solve(): Unit = {
    val H, U = Coord(ni(), ni())
    val N = ni()

    val INF = 1e9.toInt

    def y(a: Int, b: Int, c: Int, x: Int) = {
      -(a.toDouble * x + c) / b
    }

    var ans = 0
    REP(N) { _ =>
      import java.awt.geom.{Line2D, Point2D}
      val a, b, c = ni()

      // Y軸に平行
      if (b == 0) {
        val x = -c // 本当は-c/a なんだけどdoule精度が怖い
        if (min(H.x, U.x).toLong * a <= x && x <= max(H.x, U.x).toLong * a) ans += 1
      } else {
        val p1 = Coord(-INF, y(a, b, c, -INF))
        val p2 = Coord(INF, y(a, b, c, INF))
        if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, H.x, H.y, U.x, U.y)) ans += 1
      }
    }

    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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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)

  case class Coord(x: Double, y: Double) {
    def ccw: Coord = Coord(-y, x)
    def +(o: Coord) = Coord(x + o.x, y + o.y)
  }

  def solve(): Unit = {
    val H, U = Coord(ni(), ni())
    val N = ni()

    val INF = 1e9.toInt

    def y(a: Int, b: Int, c: Int, x: Int) = {
      -(a.toDouble * x + c) / b
    }

    var ans = 0
    REP(N) { _ =>
      import java.awt.geom.{Line2D, Point2D}
      val a, b, c = ni()
      val p1 = Coord(-INF, y(a, b, c, -INF))
      val p2 = Coord(INF, y(a, b, c, INF))
      if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, H.x, H.y, U.x, U.y)) ans += 1
    }

    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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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)

  case class Coord(x: Double, y: Double) {
    def ccw: Coord = Coord(-y, x)
    def +(o: Coord) = Coord(x + o.x, y + o.y)
  }

  def solve(): Unit = {
    val H, U = Coord(ni(), ni())
    val N = ni()

    val INF = 1e9.toInt

    def y(a: Int, b: Int, c: Int, x: Int) = {
      -(a.toDouble * x + c) / b
    }

    var ans = 0
    REP(N) { _ =>
      import java.awt.geom.{Line2D, Point2D}
      val a, b, c = ni()

      // Y軸に平行
      if (b == 0) {
        val x = -c // 本当は-c/a なんだけどdoule精度が怖い
        if (min(H.x, U.x).toLong * a <= x && x <= max(H.x, U.x).toLong) ans += 1
      } else {
        val p1 = Coord(-INF, y(a, b, c, -INF))
        val p2 = Coord(INF, y(a, b, c, INF))
        if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, H.x, H.y, U.x, U.y)) ans += 1
      }
    }

    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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(x1, y1) = in.next().split(' ').map(_.toInt)
  var Array(x2, y2) = in.next().split(' ').map(_.toInt)
  val n = in.next().toInt
  println((1 to n).map(_ => in.next().split(' ').map(_.toInt)).count{
    case(Array(a, b, c)) =>
      val home = a * x1 + b * y1 + c
      val university = a * x2 + b * y2 + c
      (home > 0 && university < 0) || (home < 0 && university > 0)
  })
}


You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves:   decrease $$$n$$$ by $$$1$$$;  divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. The only line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^{18}$$$, $$$2 \le k \le 10^{18}$$$).

For each query print the minimum number of steps to reach $$$0$$$ from $$$n$$$ in single line.

NoteSteps for the first test case are: $$$59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.In the second test case you have to divide $$$n$$$ by $$$k$$$ $$$18$$$ times and then decrease $$$n$$$ by $$$1$$$.

//package codeforces

/*
https://codeforces.com/contest/1175/problem/A
 */
object FromHeroToZero {

  def countStepsToZero(k: Long)(n: Long, result: Long): Long = {
    if (n == 0) result
    else {
      n % k match {
        case 0 => countStepsToZero(k)(n / k, result + 1)
        case r => countStepsToZero(k)(n - r, result + r)
      }
    }

  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, k) = io.StdIn.readLine().split(" ").map(_.toLong)

      println(countStepsToZero(k)(n, 0))

    }
  }

}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N, K = nl()

      def step(n: Long): Long = {
        if (n == 0) 0
        else {
          val r = n % K
          r + (if (n / K > 0) step(n / K) + 1 else 0)
        }
      }

      out.println(step(N))
    }
  }
}


Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of polygons in the market.  Each of the next $$$t$$$ lines contains a single integer $$$n_i$$$ ($$$3 \le n_i \le 10^9$$$): it means that the $$$i$$$-th polygon is a regular $$$n_i$$$-sided polygon.

For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).

NoteIn the example, there are $$$4$$$ polygons in the market. It's easy to see that an equilateral triangle (a regular $$$3$$$-sided polygon) is not beautiful, a square (a regular $$$4$$$-sided polygon) is beautiful and a regular $$$12$$$-sided polygon (is shown below) is beautiful as well.

import java.util.StringTokenizer

import scala.io.StdIn

object Main {
  object Scanner {
    private var st: StringTokenizer = _

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

    def nextInt: Int = nextToken().toInt
    def nextLong: Long = nextToken().toLong
    def nextShort: Short = nextToken().toShort
    def nextByte: Byte = nextToken().toByte
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to Scanner.nextInt) {
      if (Scanner.nextInt % 4 == 0) {
        println("YES")
      } else {
        println("NO")
      }
    }
  }
}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//    val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val m = in.nextInt()

      val t = m - 4
      if (t < 0) {
        println("NO")
      } else {
        if (t % 4 == 0) {
          println("YES")
        } else {
          println("NO")
        }
      }

    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()
  for (_ <- 1 to t) {
    val n = in.nextInt()
    val res = if (n % 4 == 0) {
      "YES"
    } else {
      "NO"
    }

    println(res)
  }

}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//    val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val m = in.nextInt()

      val t = m - 4
      if (t < 0) {
        println("NO")
      } else {
        if (t % 2 == 0) {
          println("YES")
        } else {
          println("NO")
        }
      }

    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()
  for (_ <- 1 to t) {
    val n = in.nextInt()
    val res = if (n % 2 == 0) {
      "YES"
    } else {
      "NO"
    }

    println(res)
  }

}


Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.

Print a single integer – the answer to the problem.

NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.

import java.util.StringTokenizer

object _462B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt
  val s = next
  val g = s.groupBy(ch => ch).toArray.sortBy(i => -i._2.length)

  def doit(i: Int, k: Int, acc: Long): Long = {
    if (k == 0) acc
    else {
      doit(i + 1, 0 max (k - g(i)._2.length), acc + (k min g(i)._2.length).toLong * (k min g(i)._2.length))
    }
  }
  println(doit(0, k, 0))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val str = in.next()
  var sorted = str.groupBy(x => x).map(x => x._2.length).toList.sorted.reverse
  var left = k
  var result = 0l
  while (left > 0) {
    val count = sorted.head
    sorted = sorted.tail
    val min = Math.min(left, count)
    result += min.toLong * min
    left -= min
  }
  println(result)
}

import scala.collection.mutable

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF263_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }
  val Array(n, k) = readInts(2)
  val inputStr = readLine()

  val map = for((k, v) <- inputStr.groupBy(identity)) yield {
    (k, v.length)
  }
  val l = map.toArray.sortBy(-_._2)
  var remaink:Long = k
  var i = 0
  var result = 0L
  while(remaink > 0) {
    val cantake:Long = remaink min l(i)._2
    result += (cantake * cantake)
    remaink -= cantake
    i += 1
  }
  println(result)

}

import java.util.StringTokenizer

object _462B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt
  val s = next
  val g = s.groupBy(ch => ch).toArray.sortBy(i => -i._2.length)

  def doit(i: Int, k: Int, acc: Int): Int = {
    if (k == 0) acc
    else {
      doit(i + 1, 0 max (k - g(i)._2.length), acc + (k min g(i)._2.length) * (k min g(i)._2.length))
    }
  }
  println(doit(0, k, 0))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val str = in.next()
  var sorted = str.groupBy(x => x).map(x => x._2.length).toList.sorted.reverse
  var left = k
  var result = 0
  while (left > 0) {
    val count = sorted.head
    sorted = sorted.tail
    val min = Math.min(left, count)
    result += min * min
    left -= min
  }
  println(result)
}

import scala.collection.mutable

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF263_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }
  val Array(n, k) = readInts(2)
  val inputStr = readLine()

  val map = for((k, v) <- inputStr.groupBy(identity)) yield {
    (k, v.length)
  }
  val l = map.toArray.sortBy(-_._2)
  var remaink = k
  var i = 0
  var result = 0
  while(remaink > 0) {
    val cantake = remaink min l(i)._2
    result += (cantake * cantake)
    remaink -= cantake
    i += 1
  }
  println(result)

}

import scala.collection.mutable

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF263_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }
  val Array(n, k) = readInts(2)
  val inputStr = readLine()

  val map = for((k, v) <- inputStr.groupBy(identity)) yield {
    (k, v.length)
  }
  val l = map.toArray.sortBy(-_._2)
  var remaink = k
  var i = 0
  var result = 0L
  while(remaink > 0) {
    val cantake = remaink min l(i)._2
    result += (cantake * cantake)
    remaink -= cantake
    i += 1
  }
  println(result)

}


Consider a conveyor belt represented using a grid consisting of $$$n$$$ rows and $$$m$$$ columns. The cell in the $$$i$$$-th row from the top and the $$$j$$$-th column from the left is labelled $$$(i,j)$$$. Every cell, except $$$(n,m)$$$, has a direction R (Right) or D (Down) assigned to it. If the cell $$$(i,j)$$$ is assigned direction R, any luggage kept on that will move to the cell $$$(i,j+1)$$$. Similarly, if the cell $$$(i,j)$$$ is assigned direction D, any luggage kept on that will move to the cell $$$(i+1,j)$$$. If at any moment, the luggage moves out of the grid, it is considered to be lost. There is a counter at the cell $$$(n,m)$$$ from where all luggage is picked. A conveyor belt is called functional if and only if any luggage reaches the counter regardless of which cell it is placed in initially. More formally, for every cell $$$(i,j)$$$, any luggage placed in this cell should eventually end up in the cell $$$(n,m)$$$. This may not hold initially; you are, however, allowed to change the directions of some cells to make the conveyor belt functional. Please determine the minimum amount of cells you have to change.Please note that it is always possible to make any conveyor belt functional by changing the directions of some set of cells.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n, m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$)  — the number of rows and columns, respectively. The following $$$n$$$ lines each contain $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th line, $$$a_{i,j}$$$ is the initial direction of the cell $$$(i, j)$$$. Please note that $$$a_{n,m}=$$$ C.

For each case, output in a new line the minimum number of cells that you have to change to make the conveyor belt functional.

4
3 3
RRD
DDR
RRC
1 4
DDDC
6 9
RDDDDDRRR
RRDDRRDDD
RRDRDRRDR
DDDDRDDRR
DRRDRDDDR
DDRDRRDDC
1 1
C

NoteIn the first case, just changing the direction of $$$(2,3)$$$ to D is enough.You can verify that the resulting belt is functional. For example, if we place any luggage at $$$(2,2)$$$, it first moves to $$$(3,2)$$$ and then to $$$(3,3)$$$. In the second case, we have no option but to change the first $$$3$$$ cells from D to R making the grid equal to RRRC.

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

    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val grid = Array.fill(n){nextLine}
      val res = grid.count(_(m - 1) == 'R') + grid.last.count(_ == 'D')

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


You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.

The first line contains single positive integer n (1 ≤ n ≤ 105) — the number of integers. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print the maximum length of an increasing subarray of the given array.

import scala.io.StdIn._

object Solution extends App {
  val n = readInt
  val a = readLine().split(" ").map(_.toInt)
  var ans = 1
  var len = 1
  for (right <- 0 until a.length) {
    if (right > 0) {
      if (a(right) > a(right - 1)) {
        len += 1
        ans = math.max(len, ans)
      } else {
        len = 1
      }
    }
  }
  println(ans)
}

/**
  * Created for cf
  */

import scala.io._

/**
  * Cheat Sheet:
  * Input: scala.io.StdIn
  * Output: println
  */
/*
object main {
  val n = StdIn.readInt()
  val arr = StdIn.readLine().split(' ').map(x => x.toInt).toSeq

  def bin_search(dp: Map[Int, Int], l: Int, r: Int, key: Int): Int = {
    if(l == r) l
    else {
      val mid = l + r >> 1
      dp.get(mid) match {
        case Some(x) =>
          if (x < key) math.max(mid, bin_search(dp, math.min(r, mid + 1), r, key))
          else bin_search(dp, l, math.max(mid - 1, l), key)
        case None => bin_search(dp, l, math.max(l, mid - 1), key)
      }
    }
  }

  def calc(n: Int): (Int, Map[Int, Int])= {
    if(n == 0) (1, Map(0 -> Int.MinValue, 1 -> arr.head) )
    else {
      val (len, dp) = calc(n - 1)
      val idx = bin_search(dp, 0, n + 1, arr(n))
      (idx + 1, dp.updated(idx + 1, math.min(dp.getOrElse(idx + 1, Int.MaxValue), arr(n))))
    }
  }

  def main(args: Array[String]): Unit = {
    println(s"${calc(n - 1)._1}")
  }
}
*/

object main {
  val n = StdIn.readInt()
  val arr = StdIn.readLine().split(' ').map(x => x.toInt).toSeq

  def main(args: Array[String]): Unit = {
    val ans = arr.tail.foldLeft( (arr.head, (1, 1) ) ) ((pr, x) => {
      val (last, (len, ans) ) = pr
      if(x > last) (x, (len + 1, math.max(ans, len + 1)))
      else (x, (1, ans))
    })
    println(s"${ans._2._2}")
  }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val (maxL, curL, _) = lines.next().split(' ').map(_.toInt).foldLeft(0, 0, -1) {
    case ((maxLength, currentLength, lastEl), el) if el > lastEl => (maxLength, currentLength + 1, el)
    case ((maxLength, currentLength, lastEl), el) => (Math.max(maxLength, currentLength), 1, el)
  }

  println(Math.max(maxL, curL))
}

object A702 {
  @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 ret = 1
    var curr = 1
    for(i <- input.indices) {
      if(i == 0) {
        ret = 1
        curr = 1
      } else {
        if(input(i) > input(i-1)) {
          curr += 1
          ret = math.max(ret, curr)
        } else {
          ret = math.max(ret, curr)
          curr = 1
        }
      }
    }

    println(ret)
  }
}

/**
  * Created for cf
  */

import scala.io._

/**
  * Cheat Sheet:
  * Input: scala.io.StdIn
  * Output: println
  */

object main {
  val n = StdIn.readInt()
  val arr = StdIn.readLine().split(' ').map(x => x.toInt).toSeq

  def main(args: Array[String]): Unit = {
    val ans = arr.tail.foldLeft( (arr.head, 1) ) ((pr, x) => {
      val (last, len) = pr
      if(x > last) (x, len + 1)
      else (x, 1)
    })
    println(s"${ans._2}")
  }
}


You are given an array of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. After you watched the amazing film "Everything Everywhere All At Once", you came up with the following operation.In one operation, you choose $$$n-1$$$ elements of the array and replace each of them with their arithmetic mean (which doesn't have to be an integer). For example, from the array $$$[1, 2, 3, 1]$$$ we can get the array $$$[2, 2, 2, 1]$$$, if we choose the first three elements, or we can get the array $$$[\frac{4}{3}, \frac{4}{3}, 3, \frac{4}{3}]$$$, if we choose all elements except the third.Is it possible to make all elements of the array equal by performing a finite number of such operations?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$)  — the number of integers. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$).

For each test case, if it is possible to make all elements equal after some number of operations, output $$$\texttt{YES}$$$. Otherwise, output $$$\texttt{NO}$$$. You can output $$$\texttt{YES}$$$ and $$$\texttt{NO}$$$ in any case (for example, strings $$$\texttt{yEs}$$$, $$$\texttt{yes}$$$, $$$\texttt{Yes}$$$ will be recognized as a positive response).

NoteIn the first test case, all elements are already equal.In the second test case, you can choose all elements except the third, their average is $$$\frac{1 + 2 + 4 + 5}{4} = 3$$$, so the array will become $$$[3, 3, 3, 3, 3]$$$.It's possible to show that it's impossible to make all elements equal in the third and fourth test cases.

// https://codeforces.com/contest/1686/problem/0
//package round_794

import scala.io.StdIn

object task_A extends App {
    def solving(a: Array[Int], n: Int): String = {
        val avg = a.sum.toFloat / n
        var i = 0
        while (i < n && a(i) != avg) {
            i += 1
        }
        if (i == n) {
            "NO"
        }
        else {
            "YES"
        }
    }

    val t = StdIn.readLine().toInt
    var sb = new StringBuilder()
    for (i <- 0 until(t)) {
        val n = StdIn.readLine().toInt
        val a: Array[Int] = StdIn.readLine().split(" ").map(x => x.toInt)
        sb.append(solving(a, n)).append("\n")
    }
    print(sb)

}


Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.Each spell consists of several lines. The line, whose first non-space character is character "#" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell.You came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning.The only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden.Note that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too).For now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too).The input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output.

The input contains multiple lines. All characters in the lines have codes from 32 to 127 (inclusive). Please note that the lines may begin with or end with one or more spaces. The size of the input does not exceed 1048576 ( = 220) bytes. Newlines are included in this size. In the Windows operating system used on the testing computer, a newline is a sequence of characters with codes #13#10. It is guaranteed that after each line of input there is a newline. In particular, the input ends with a newline. Note that the newline is the end of the line, and not the beginning of the next one. It is guaranteed that the input contains at least one character other than a newline. It is recommended to organize the input-output line by line, in this case the newlines will be processed correctly by the language means.

Print the text of the spell where all extra characters are deleted. Please note that each output line should be followed by a newline. Please be careful: your answers will be validated by comparing them to the jury's answer byte-by-byte. So, all spaces and newlines matter.

#   include <cstdio>

using namespace std;

int main     (   ){
puts("Hello # World"); #
#
}

#   include <cstdio>
usingnamespacestd;intmain(){puts("Hello#World");#
#
}

NoteIn the first sample the amplifying lines are lines 1 and 7. So, lines 2 to 6 are concatenated to each other, all spaces are deleted from them.In the second sample the amplifying lines are lines 1 and 3. So, no lines are concatenated to each other.

object MinSpell {

  def main(args: Array[String]): Unit = {
    var sb = new StringBuilder()
    var s = readLine()
    var hasLines = false;
    while (s != null){
      if (s.trim().startsWith("#")){
        if (hasLines) {
          print("%s\n".format(sb.toString()))
          sb.clear();
          hasLines = false;
        }
        print("%s\n".format(s))
      } else {
        hasLines = true;
        sb.append(s.replaceAll(" |\n",""));
      }
      s = readLine();
    }
    if (hasLines) {
      print("%s\n".format(sb.toString()))
    }
  }

}

object MinSpell {

  def main(args: Array[String]): Unit = {
    var sb = new StringBuilder()
    var s = readLine()
    while (s != null){
      if (s.trim().startsWith("#")){
        if (sb.length > 0) {
          print("%s\n".format(sb.toString()))
          sb.clear();
        }
        print("%s\n".format(s))
      } else {
        sb.append(s.replaceAll(" |\n",""));
      }
      s = readLine();
    }
    if (sb.length > 0) {
      print("%s\n".format(sb.toString()))
    }
  }

}


The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital — number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.

The first input line contains two integers n and m (2 ≤ n ≤ 100, ) — the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 ≤ vi, ui ≤ n, vi ≠ ui) — the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.  It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.

Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.

NoteIn the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make .In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal .

import collection.mutable
import io.Source
import java.util.StringTokenizer

object Runner extends App {

  val input = Source.fromInputStream(System.in).bufferedReader();
  var token: StringTokenizer = null;

  def TOKEN() = {
    while (token == null || !token.hasMoreTokens)
      token = new StringTokenizer(input.readLine());
    token.nextToken()
  }
  def INT() = TOKEN().toInt

  val n = INT()
  val m = INT()
  val matrix = Array.ofDim[Boolean](n,n)
  for (i <- 1 to m) {
    val a = INT() - 1
    val b = INT() - 1
    matrix(a)(b) = true
    matrix(b)(a) = true
  }

  solve(matrix)

  def solve(matrix : Array[Array[Boolean]]) {
    val N = matrix.length

    def bfs(start:Int) : Array[Int] = {
      val dists = Array.fill(N)(Int.MaxValue/2)
      val visited = Array.fill(N)(false)
      val queue = new mutable.Queue[Int]()

      dists(start) = 0
      queue += start
      visited(start) = true

      while(!queue.isEmpty) {
        val next = queue.dequeue()
        for (neighbor <- (0 until N).filter(matrix(next)(_))) {
          if (!visited(neighbor)) {
            visited(neighbor) = true
            dists(neighbor) = math.min(dists(neighbor), dists(next) + 1)
            queue += neighbor
          }
        }
      }

      dists
    }

    val distsLeft = bfs(0)
    val distsRight = bfs(N-1)

    def countPaths(dists : Array[Int]) = {

      val start = dists.indexOf(0)
      val queue = new mutable.Queue[Int]()
      val found = Array.fill(N)(false)
      val paths = new Array[Long](N)

      queue.enqueue(start)
      paths(start) = 1

      while(!queue.isEmpty) {
        val next = queue.dequeue()
        for (i <- (0 until N).filter(x => matrix(next)(x) && dists(next) < dists(x))) {
          paths(i) += paths(next)
          if (!found(i)) {
            queue.enqueue(i)
            found(i) = true
          }
        }
      }

      paths
    }

    val pathsLeft = countPaths(distsLeft)
    val pathsRight = countPaths(distsRight)
    val paths = for(i <- (0 until N)) yield {
      if(distsLeft(i)+distsRight(i) == distsRight(0))
        pathsLeft(i) * pathsRight(i) * (if (i > 0 && i < N-1) 2 else 1)
      else
        0
    }

    println(paths.max.toDouble / paths(N-1).toDouble)

  }

}

import collection.mutable
import io.Source
import java.util.StringTokenizer

object Runner extends App {

  val input = Source.fromInputStream(System.in).bufferedReader();
  var token: StringTokenizer = null;

  def TOKEN() = {
    while (token == null || !token.hasMoreTokens)
      token = new StringTokenizer(input.readLine());
    token.nextToken()
  }
  def INT() = TOKEN().toInt

  val n = INT()
  val m = INT()
  val matrix = Array.ofDim[Boolean](n,n)
  for (i <- 1 to m) {
    val a = INT() - 1
    val b = INT() - 1
    matrix(a)(b) = true
    matrix(b)(a) = true
  }

  solve(matrix)

  def solve(matrix : Array[Array[Boolean]]) {
    val N = matrix.length

    def bfs(start:Int) : Array[Int] = {
      val dists = Array.fill(N)(Int.MaxValue/2)
      val visited = Array.fill(N)(false)
      val queue = new mutable.Queue[Int]()

      dists(start) = 0
      queue += start
      visited(start) = true

      while(!queue.isEmpty) {
        val next = queue.dequeue()
        for (neighbor <- (0 until N).filter(matrix(next)(_))) {
          if (!visited(neighbor)) {
            visited(neighbor) = true
            dists(neighbor) = math.min(dists(neighbor), dists(next) + 1)
            queue += neighbor
          }
        }
      }

      dists
    }

    val distsLeft = bfs(0)
    val distsRight = bfs(N-1)

    def countPaths(dists : Array[Int]) = {

      val start = dists.indexOf(0)
      val queue = new mutable.Queue[Int]()
      val found = Array.fill(N)(false)
      val paths = new Array[Int](N)

      queue.enqueue(start)
      paths(start) = 1

      while(!queue.isEmpty) {
        val next = queue.dequeue()
        for (i <- (0 until N).filter(x => matrix(next)(x) && dists(next) < dists(x))) {
          paths(i) += paths(next)
          if (!found(i)) {
            queue.enqueue(i)
            found(i) = true
          }
        }
      }

      paths
    }

    val pathsLeft = countPaths(distsLeft)
    val pathsRight = countPaths(distsRight)
    val paths = for(i <- (0 until N)) yield {
      if(distsLeft(i)+distsRight(i) == distsRight(0))
        pathsLeft(i) * pathsRight(i) * (if (i > 0 && i < N-1) 2 else 1)
      else
        0
    }

    println(paths.max.toDouble / paths(N-1).toDouble)

  }

}

import collection.mutable
import io.Source
import java.util.StringTokenizer

object Runner extends App {

  val input = Source.fromInputStream(System.in).bufferedReader();
  var token: StringTokenizer = null;

  def TOKEN() = {
    while (token == null || !token.hasMoreTokens)
      token = new StringTokenizer(input.readLine());
    token.nextToken()
  }
  def INT() = TOKEN().toInt

  val n = INT()
  val m = INT()
  val matrix = Array.ofDim[Boolean](n,n)
  for (i <- 1 to m) {
    val a = INT() - 1
    val b = INT() - 1
    matrix(a)(b) = true
    matrix(b)(a) = true
  }

  solve(matrix);

  def solve(matrix : Array[Array[Boolean]]) = {
    val N = matrix.length

    def bfs(start:Int) : Array[Int] = {
      val dists = Array.fill(N)(Int.MaxValue/2)
      val visited = Array.fill(N)(false)
      val queue = new mutable.Queue[Int]()

      dists(start) = 0
      queue += start
      visited(start) = true

      while(!queue.isEmpty) {
        val next = queue.dequeue()
        for (neighbor <- (0 until N).filter(matrix(next)(_))) {
          if (!visited(neighbor)) {
            visited(neighbor) = true
            dists(neighbor) = math.min(dists(neighbor), dists(next) + 1)
            queue += neighbor
          }
        }
      }

      dists
    }

    val distsLeft = bfs(0);
    val distsRight = bfs(N-1);

    def countPaths(dists : Array[Int]) = {

      val start = dists.indexOf(0);
      val queue = new mutable.Queue[Int]();
      val found = Array.fill(N)(false);
      val paths = new Array[Int](N);

      queue.enqueue(start)
      paths(start) = 1

      while(!queue.isEmpty) {
        val next = queue.dequeue();
        for (i <- (0 until N).filter(x => matrix(next)(x) && dists(next) < dists(x))) {
          paths(i) += paths(next)
          if (!found(i)) {
            queue.enqueue(i)
            found(i) = true
          }
        }
      }

      paths
    }

    val pathsLeft = countPaths(distsLeft);
    val pathsRight = countPaths(distsRight);
    val paths = for(i <- (0 until N)) yield {
      pathsLeft(i) * pathsRight(i) * (if (i > 0 && i < N-1) 2 else 1);
    }

    println(paths.max.toDouble / paths(N-1).toDouble)

  }

}