You are fed up with your messy room, so you decided to clean it up.Your room is a bracket sequence $$$s=s_{1}s_{2}\dots s_{n}$$$ of length $$$n$$$. Each character of this string is either an opening bracket '(' or a closing bracket ')'.In one operation you can choose any consecutive substring of $$$s$$$ and reverse it. In other words, you can choose any substring $$$s[l \dots r]=s_l, s_{l+1}, \dots, s_r$$$ and change the order of elements in it into $$$s_r, s_{r-1}, \dots, s_{l}$$$.For example, if you will decide to reverse substring $$$s[2 \dots 4]$$$ of string $$$s=$$$"((()))" it will be equal to $$$s=$$$"()(())".A regular (aka balanced) bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.A prefix of a string $$$s$$$ is a substring that starts at position $$$1$$$. For example, for $$$s=$$$"(())()" there are $$$6$$$ prefixes: "(", "((", "(()", "(())", "(())(" and "(())()".In your opinion, a neat and clean room $$$s$$$ is a bracket sequence that:  the whole string $$$s$$$ is a regular bracket sequence;  and there are exactly $$$k$$$ prefixes of this sequence which are regular (including whole $$$s$$$ itself). For example, if $$$k = 2$$$, then "(())()" is a neat and clean room.You want to use at most $$$n$$$ operations to make your room neat and clean. Operations are applied one after another sequentially.It is guaranteed that the answer exists. Note that you do not need to minimize the number of operations: find any way to achieve the desired configuration in $$$n$$$ or less operations.

The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le \frac{n}{2}, 2 \le n \le 2000$$$, $$$n$$$ is even) — length of $$$s$$$ and required number of regular prefixes. The second line of a test case contains $$$s$$$ of length $$$n$$$ — the given bracket sequence. It contains only '(' and ')'. It is guaranteed that there are exactly $$$\frac{n}{2}$$$ characters '(' and exactly $$$\frac{n}{2}$$$ characters ')' in the given string. The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$2000$$$.

For each test case print an answer. In the first line print integer $$$m$$$ ($$$0 \le m \le n$$$) — the number of operations. You do not need to minimize $$$m$$$, any value is suitable. In the following $$$m$$$ lines print description of the operations, each line should contain two integers $$$l,r$$$ ($$$1 \le l \le r \le n$$$), representing single reverse operation of $$$s[l \dots r]=s_{l}s_{l+1}\dots s_{r}$$$. Operations are applied one after another sequentially. The final $$$s$$$ after all operations should be a regular, also it should be exactly $$$k$$$ prefixes (including $$$s$$$) which are regular. It is guaranteed that the answer exists. If there are several possible answers you can print any.

NoteIn the first example, the final sequence is "()(()())", where two prefixes are regular, "()" and "()(()())". Note, that all the operations except "5 8" in the example output are useless (they do not change $$$s$$$).

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

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 mkT(N: Int, K: Int): String = {
    val str = StringBuilder.newBuilder
    REP(K - 1) { _ =>
      str.append("()")
    }
    REP(N/2 - (K-1)) { _ =>
      str.append("(")
    }
    REP(N/2 - (K-1)) { _ =>
      str.append(")")
    }
    str.toString
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N, K = ni()
      val S = ns(N)
      val T = mkT(N, K).toCharArray
      debug(S.mkString)
      debug(T.mkString)
      val ans = ArrayBuffer[(Int, Int)]()
      val pos1, pos2 = new java.util.ArrayDeque[Int]()
      def pos(i: Int) = if (S(i) == '(') pos1 else pos2
      def pos_rev(i: Int) = if (S(i) == '(') pos2 else pos1
      REP(N) { i =>
        pos(i).addLast(i)
      }
      REP(N) { i =>
        if (S(i) == T(i)) {
          pos(i).poll()
        }
        if (S(i) != T(i)) {
          pos(i).poll()
          val j = pos_rev(i).poll()
          pos(i).addFirst(j)
          debug(s"$i,$j")
          ans += ((i, j))
          if (j - i > 2) ans += ((i + 1, j - 1))
          val t = S(j)
          S(j) = S(i)
          S(i) = t
        }
      }
      out.println(ans.length)
      REP(ans.length) { i =>
        out.println(s"${ans(i)._1+1} ${ans(i)._2+1}")
      }
    }
  }
}

import scala.collection.mutable

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

  val t = nextInt
  def expected(i: Int): Char = if (i % 2 == 0) '(' else ')'

  for (_ <- 1 to t) {

    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = 0
    var r = n - 1
    val res = new mutable.ArrayBuffer[String]

    while (l < r) {
      while (l < r && s(l) == expected(l)) l += 1
      while (l < r && s(r) == expected(r)) r -= 1
      if (l < r) {
        var rr = r
        var ll = l
        while (s(rr) != expected(l)) rr -= 1
        res += s"${ll + 1} ${rr + 1}"
        while (ll < rr) {
          val tmp = s(ll)
          s(ll) = s(rr)
          s(rr) = tmp
          ll += 1
          rr -= 1
        }
      }
    }

    for (i <- 0 until n / 2 - k) {
      val l = 2 * i + 1
      val r = l + 1
      res += s"${l + 1} ${r + 1}"
    }

    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) pCount += 1
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    val l = s.indexOfSlice("((")
    val r = s.indexOf(')', l)
    s(l + 1) = ')'
    s(r) = '('
    s"${l + 1} $r"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' =>
          x += 1
          if (x == 1 && l > 0) done = true
        case ')' =>
          x -= 1
      }
      l += 1
    }
    l -= 2
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) pCount += 1
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    val l = s.indexOfSlice("((")
    val r = s.indexOf(')', l)
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' =>
          x += 1
          if (x == 1 && l > 0) done = true
        case ')' =>
          x -= 1
      }
      l += 1
    }
    l -= 2
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    while (s(l) != ')' || s(l + 1) != '(') l += 1
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    if (s.length == 2000) {
      println(s.drop(1533).mkString)
      System.exit(0)
    }
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  for (_ <- 1 to t) {

    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = 0
    val res = new mutable.ArrayBuffer[String]

    while (l < n) {
      val left = if (l % 2 == 0) '(' else ')'
      if (s(l) != left) {
        var r = n - 1
        while (s(r) != left) r -= 1
        res += s"${l + 1} ${r + 1}"
        var ll = l
        var rr = r
        while (ll < rr) {
          val tmp = s(ll)
          s(ll) = s(rr)
          s(rr) = tmp
          ll += 1
          rr -= 1
        }
      }
      l += 1
    }

    for (i <- 0 until n / 2 - k) {
      val l = 2 * i + 1
      val r = l + 1
      res += s"${l + 1} ${r + 1}"
    }

    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    while (s(l) != ')' || s(l + 1) != '(') l += 1
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    if (s.length == 2000) {
      println(s.mkString)
      System.exit(0)
    }
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    while (s(l) != ')' || s(l + 1) != '(') l += 1
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    if (s.length == 2000) {
      println(s.drop(511).mkString)
      System.exit(0)
    }
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    while (s(l) != ')' || s(l + 1) != '(') l += 1
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    if (s.length == 2000) {
      println(s.drop(1022).mkString)
      System.exit(0)
    }
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  for (_ <- 1 to t) {

    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = 0
    var r = n - 1
    val res = new mutable.ArrayBuffer[String]

    while (l < r) {
      val left = if (l % 2 == 0) '(' else ')'
      if (s(l) != left) {
        while (s(r) != left) r -= 1
        res += s"${l + 1} ${r + 1}"
        var ll = l
        var rr = r
        while (ll < rr) {
          val tmp = s(ll)
          s(ll) = s(rr)
          s(rr) = tmp
          ll += 1
          rr -= 1
        }
      }
      l += 1
    }

    for (i <- 0 until n / 2 - k) {
      val l = 2 * i + 1
      val r = l + 1
      res += s"${l + 1} ${r + 1}"
    }

    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

import scala.collection.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' =>
          x += 1
          if (x == 1 && l > 0) {
            done = true
          }
        case ')' =>
          x -= 1
      }
      l += 1
    }
    l -= 2
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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


A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient X — the coefficient of income growth during one year. This coefficient should satisfy the equation:A·Xn = B.Surely, the king is not going to do this job by himself, and demands you to find such number X.It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient X must be integers. The number X may be zero or negative.

The input contains three integers A, B, n (|A|, |B| ≤ 1000, 1 ≤ n ≤ 10).

Output the required integer coefficient X, or «No solution», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.

object P030A {
  def errorOut():Unit = {
    println("No solution")
    System.exit(0)
  }
  def earlyOut(x: Int): Unit = {
    println(x);
    System.exit(0);
  }
  def solve(y: Int, n: Int): Int = {
    return math.round(math.exp(math.log(y)/n)).toInt;
  }
  def pow(x: Int, n: Int):Int = {
    var y = 1
    for (i <- 1 to n) y *= x
    return y
  }
  def main(args: Array[String]) = {
    val Array(a, b, n) = readLine.split(" ").map(_.toInt)
    if (a == 0 && b != 0) errorOut();
    if (a == 0 && b == 0) earlyOut(1);
    if (b % a != 0) errorOut();
    val y = b/a;
    if (y == 0) earlyOut(0);
    if (y < 0 && n % 2 == 0) errorOut();
    val x = if (y > 0) solve(y, n) else -solve(-y, n)
    if (pow(x, n) != y) errorOut();
    println(x)
  }
}


You are given a permutation $$$p_1, p_2, \dots, p_n$$$. A permutation of length $$$n$$$ is a sequence such that each integer between $$$1$$$ and $$$n$$$ occurs exactly once in the sequence.Find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \dots, p_r$$$ is exactly the given number $$$m$$$.The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if $$$a=[4, 2, 7, 5]$$$ then its median is $$$4$$$ since after sorting the sequence, it will look like $$$[2, 4, 5, 7]$$$ and the left of two middle elements is equal to $$$4$$$. The median of $$$[7, 1, 2, 9, 6]$$$ equals $$$6$$$ since after sorting, the value $$$6$$$ will be in the middle of the sequence.Write a program to find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \dots, p_r$$$ is exactly the given number $$$m$$$.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le m \le n$$$) — the length of the given sequence and the required value of the median. The second line contains a permutation $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). Each integer between $$$1$$$ and $$$n$$$ occurs in $$$p$$$ exactly once.

NoteIn the first example, the suitable pairs of indices are: $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$ and $$$(2, 4)$$$.

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, mid = ni()
    val A = map(N) { _ =>
      ni() match {
        case a if a > mid => 1
        case `mid` => 0
        case a if a < mid => -1
      }
    }
    val ix = A.indexWhere(_ == 0)

    val L = A.slice(0, ix + 1).reverse
    val R = A.slice(ix, N)

    def mkCount(nums: Array[Int]) = {
      val cum = cumSum(nums)
      val cnt = mutable.Map[Int, Int]().withDefaultValue(0)
      // index0に０個カウントするものが入っているので除外する
      REP(nums.length, 1) { i =>
        val n = cum(i)
        cnt(n) = cnt(n) + 1
      }
      cnt
    }

    val cntL = mkCount(L)
    val cntR = mkCount(R)

    var ans = 0L
    cntL.foreach { case (l, cnt) =>
      // 合計が0か1なら中間値になる
      ans += cntR(-l) * cnt.toLong + cntR(-l + 1) * cnt.toLong
    }

    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[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, mid = ni()
    val A = map(N) { _ =>
      ni() match {
        case a if a > mid => 1
        case `mid` => 0
        case a if a < mid => -1
      }
    }
    val ix = A.indexWhere(_ == 0)

    val L = A.slice(0, ix + 1).reverse
    val R = A.slice(ix, N)

    def mkCount(nums: Array[Int]) = {
      val cum = cumSum(nums)
      val cnt = mutable.Map[Int, Int]().withDefaultValue(0)
      // index0に０個カウントするものが入っているので除外する
      REP(nums.length, 1) { i =>
        val n = cum(i)
        cnt(n) = cnt(n) + 1
      }
      cnt
    }

    val cntL = mkCount(L)
    val cntR = mkCount(R)

    var ans = 0L
    cntL.foreach { case (l, cnt) =>
      // 合計が0か1なら中間値になる
      ans += cntR(-l) * cnt + cntR(-l + 1) * cnt
    }

    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[Int](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


Little X and Little Z are good friends. They always chat online. But both of them have schedules.Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time 0, he will be online at any moment of time between c1 and d1, between c2 and d2, ..., between cq and dq (all borders inclusive). But if he gets up at time t, these segments will be shifted by t. They become [ci + t, di + t] (for all i).If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between l and r (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment [l, r] suit for that?

The first line contains four space-separated integers p, q, l, r (1 ≤  p, q ≤ 50; 0 ≤ l ≤ r ≤ 1000). Each of the next p lines contains two space-separated integers ai, bi (0 ≤ ai < bi ≤ 1000). Each of the next q lines contains two space-separated integers cj, dj (0 ≤ cj < dj ≤ 1000). It's guaranteed that bi < ai + 1 and dj < cj + 1 for all valid i and j.

Output a single integer — the number of moments of time from the segment [l, r] which suit for online conversation.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(p, q, l, r) = in.next().split(" ").map(_.toInt)
  val first = (1 to p).map{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt)
    (a, b)
  }
  val second = (1 to q).map{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt)
    (a, b)
  }

  def intersect(a: Seq[(Int, Int)], b: Seq[(Int, Int)]): Boolean = {
    if (a.isEmpty || b.isEmpty) false
    else if ((a.head._1 >= b.head._1 && a.head._1 <= b.head._2) ||
      (a.head._2 >= b.head._1 && a.head._2 <= b.head._2) ||
      (b.head._1 >= a.head._1 && b.head._1 <= a.head._2) ||
      (b.head._2 >= a.head._1 && b.head._2 <= a.head._2)) {
      true
    } else {
      if (b.head._2 > a.head._2)
        intersect(a.tail, b)
      else
        intersect(a, b.tail)
    }
  }

  val res = (l to r).count(i => intersect(first, second.map(t => (t._1 + i, t._2 + i))))
  println(res)
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object ChatOnline {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def overlap(i1 : (Int,Int), i2: (Int,Int)) : Boolean = {
     return Math.max(i1._1,i2._1) <=  Math.min(i1._2,i2._2)
   }

   def main(args: Array[String]) {
     val (p,q,l,r) = readQuad()
     val ab = for {
       i <- 1 to p
       t = readTuple()
     } yield t
     val cd = for {
       i <- 1 to q
       t = readTuple()
     } yield t
    /* val zschedule = new Array[Boolean](ab.last._2 + 1)
     for (i <- 1 to zschedule.size) {
       val cur = ab(i)
       for (j <- cur._1 to cur._2) zschedule(j) = true
     }
     val xschedule = new Array[Boolean](ab.last._2 + 1)
     for (i <- 1 to xschedule.size) {
       val cur = cd(i)
       for (j <- cur._1 to cur._2) zschedule(j) = true
     }*/
     var t = l
     var sum = 0
     var bool = false
     while (t <= r) {
       var i = 0
       var ok = false
       while (i < ab.size && !ok) {
         var j = 0
         while (j < cd.size && !ok) {
           val ccd = (cd(j)._1+t, cd(j)._2+t)
           if (overlap(ab(i),ccd)) {
             sum += 1
             ok = true
           }
           j +=1
         }
         i += 1
       }
       t+=1

     }
     println(sum)

   }

}

object Main extends App {
  val Array(p, q, l, r) = readLine.split(" ").map(_.toInt)

  def readSegments(count: Int) = {
    (1 to count).map(i => {
      val Array(v1, v2) = readLine.split(" ").map(_.toInt)
      (v1, v2)
    })
  }

  val pSegments = readSegments(p)
  val qSegments = readSegments(q)

  def intersect(seg1: (Int, Int), seg2: (Int, Int)) = {
    seg1._1 <= seg2._2 && seg1._2 >= seg2._1
  }

  def commonMoment(shift: Int) = {
    qSegments.map(x => (x._1 + shift, x._2 + shift))
      .exists(qSeg => pSegments.exists(pSeg => intersect(pSeg, qSeg)))
  }

  println((l to r).count(commonMoment))
}


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$ and an integer $$$k$$$, such that $$$1 \leq k \leq n$$$. A permutation means that every number from $$$1$$$ to $$$n$$$ is contained in $$$p$$$ exactly once.Let's consider all partitions of this permutation into $$$k$$$ disjoint segments. Formally, a partition is a set of segments $$$\{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}$$$, such that:  $$$1 \leq l_i \leq r_i \leq n$$$ for all $$$1 \leq i \leq k$$$;  For all $$$1 \leq j \leq n$$$ there exists exactly one segment $$$[l_i, r_i]$$$, such that $$$l_i \leq j \leq r_i$$$. Two partitions are different if there exists a segment that lies in one partition but not the other.Let's calculate the partition value, defined as $$$\sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}$$$, for all possible partitions of the permutation into $$$k$$$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $$$998\,244\,353$$$.

The first line contains two integers, $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 200\,000$$$) — the size of the given permutation and the number of segments in a partition. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the given permutation.

Print two integers — the maximum possible partition value over all partitions of the permutation into $$$k$$$ disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo $$$998\,244\,353$$$. Please note that you should only find the second value modulo $$$998\,244\,353$$$.

NoteIn the first test, for $$$k = 2$$$, there exists only two valid partitions: $$$\{[1, 1], [2, 3]\}$$$ and $$$\{[1, 2], [3, 3]\}$$$. For each partition, the partition value is equal to $$$2 + 3 = 5$$$. So, the maximum possible value is $$$5$$$ and the number of partitions is $$$2$$$.In the third test, for $$$k = 3$$$, the partitions with the maximum possible partition value are $$$\{[1, 2], [3, 5], [6, 7]\}$$$, $$$\{[1, 3], [4, 5], [6, 7]\}$$$, $$$\{[1, 4], [5, 5], [6, 7]\}$$$, $$$\{[1, 2], [3, 6], [7, 7]\}$$$, $$$\{[1, 3], [4, 6], [7, 7]\}$$$, $$$\{[1, 4], [5, 6], [7, 7]\}$$$. For all of them, the partition value is equal to $$$7 + 5 + 6 = 18$$$. The partition $$$\{[1, 2], [3, 4], [5, 7]\}$$$, however, has the partition value $$$7 + 3 + 6 = 16$$$. This is not the maximum possible value, so we don't count it.

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  val MOD = 998244353L
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val k = in.nextInt()
    val p = ListBuffer.empty[Int]
    var res = 0L
    (1 to n).foreach{ i =>
      val ai = in.nextInt()
      if(ai>(n-k)){
        p.append(i)
        res+=ai
      }
    }
    var acum = 1L
    val items = p.toList
    items.zip(items.tail).foreach{ case (i,j) =>

      acum = (acum*(j-i))%MOD
    }
    out.println(s"$res $acum")
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  val MOD = 998244353L
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val k = in.nextInt()
    val p = ListBuffer.empty[Int]
    var res = 0
    (1 to n).foreach{ i =>
      val ai = in.nextInt()
      if(ai>(n-k)){
        p.append(i)
        res+=ai
      }
    }
    var acum = 1L
    val items = p.toList
    items.zip(items.tail).foreach{ case (i,j) =>

      acum = (acum*(j-i))%MOD
    }
    out.println(s"$res $acum")
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.

The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.

Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.

import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._

object _764C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val edges = newMultiMap[Int, Int]
    repeat(n - 1) {
      val u, v = read[Int]
      edges(u) += v
      edges(v) += u
    }
    val colors = read[Vector, Int](n)
    /************************************/

    val cache = mutable.Map.empty[(Int, Int), Option[Int]]

    def singleColor(u: Int, parent: Int): Option[Int] = cache.getOrElseUpdate((u, parent), {
      val myColor = colors(u - 1)
      val isOkay = edges(u).forall(v => v == parent || singleColor(v, parent = u).contains(myColor))
      //debug(parent, u, isOkay)
      when(isOkay)(myColor)
    })

    def isOkay(root: Int) = edges(root).forall(u => singleColor(u, parent = root).isDefined)

    val out = (1 to n).find(isOkay) match {
      case Some(i) => s"YES\n$i"
      case _ => "NO"
    }

    write(out)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

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

/**
 * Created by dmitry on 11.02.17.
 */
object Main3 {
  def main(args: Array[String]) {
    val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()
    /*graphMap += (1 -> graph)*/
    val n: Int = StdIn.readInt()
    for (i <- 0 until n - 1) {
      val input: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
      formGraph(graphMap, input.head, input.last)
      formGraph(graphMap, input.last, input.head)
    }
    val inputColors: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
    val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()
    var j: Int = 1
    for (i <- inputColors) {
      colorsMap += (j -> i)
      j += 1
    }
    for (entry <- graphMap) {
      for (connectedVert <- entry._2) {
        if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {
          var rz = solve(graphMap, colorsMap, entry._1, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          }
          rz = solve(graphMap, colorsMap, connectedVert, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          } else {
            println("NO")
            return
          }
        }
      }
    }
    for (entry <- graphMap) {
      for (connectedVert <- entry._2) {
        println("YES\n" + connectedVert)
        return
      }
    }
  }

  def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {
    if (!graphMap.contains(a))
      graphMap += (a -> (new mutable.MutableList[Int] += b))
    else {
      val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get
      listOfVertex += b
    }
  }

  def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): (String, Int) = {
    //usedVertexes(start) = true
    val linkedVertexes = new mutable.Queue[Int]
    linkedVertexes ++= graphMap.get(start).get
    val q: mutable.Queue[Int] = new mutable.Queue[Int]
    val setOfColors: mutable.HashSet[Int] = new mutable.HashSet
    val usedVertexes: Array[Boolean] = new Array(size + 1)
    while (linkedVertexes.nonEmpty) {
      usedVertexes(start) = true
      q.clear()
      setOfColors.clear()
      q.enqueue(linkedVertexes.dequeue())
      while (q.nonEmpty) {
        val vert = q.dequeue()
        if (!usedVertexes(vert)) {
          setOfColors += colorGraph.get(vert).get
          if (setOfColors.size > 1)
            return ("NO", -1)
          val lv = graphMap.get(vert).get
          for (v <- lv)
            q.enqueue(v)
          usedVertexes(vert) = true
        }
      }
    }
    ("YES", start)
  }
}

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

/**
 * Created by dmitry on 11.02.17.
 */
object Main3 {
  def main(args: Array[String]) {
    val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()
    /*graphMap += (1 -> graph)*/
    val n: Int = StdIn.readInt()
    for (i <- 0 until n - 1) {
      val input: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
      formGraph(graphMap, input.head, input.last)
      formGraph(graphMap, input.last, input.head)
    }
    for (entry <- graphMap) {
      //println(entry._1 + " " + entry._2.toString())
    }
    val inputColors: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
    val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()
    var j: Int = 1
    for (i <- inputColors) {
      colorsMap += (j -> i)
      j += 1
    }
    for (entry <- colorsMap) {
      //println(entry._1 + " " + entry._2.toString())
    }
    for (entry <- graphMap) {
      for (connectedVert <- entry._2) {
        if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {
          var rz = solve(graphMap, colorsMap, entry._1, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          }
          rz = solve(graphMap, colorsMap, connectedVert, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          } else {
            println("NO")
            return
          }
        }

      }
    }
  }

  def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {
    if (!graphMap.contains(a))
      graphMap += (a -> (new mutable.MutableList[Int] += b))
    else {
      val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get
      listOfVertex += b
    }
  }

  def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): Tuple2[String, Int] = {
    var q: mutable.Queue[Int] = new mutable.Queue[Int]
    q += start
    val usedVertexes: Array[Boolean] = Array.fill(size + 1)(false)
    usedVertexes(start) = true
    val linkedVertexes = graphMap.get(start).get
    for (v <- linkedVertexes)
      q.enqueue(v)
    val setOfColors: mutable.HashSet[Int] = new mutable.HashSet
    while (q.nonEmpty) {
      val vert = q.dequeue()
      if (!usedVertexes(vert)) {
        setOfColors += colorGraph.get(vert).get
        if (setOfColors.size > 1)
          return ("NO", -1)
        val linkedVertexes = graphMap.get(vert).get
        for (v <- linkedVertexes)
          q.enqueue(v)
        usedVertexes(vert) = true
      }
    }
    ("YES", start)
  }
}

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

/**
 * Created by dmitry on 11.02.17.
 */
object Main3 {
  def main(args: Array[String]) {
    val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()
    /*graphMap += (1 -> graph)*/
    val n: Int = StdIn.readInt()
    for (i <- 0 until n - 1) {
      val input: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
      formGraph(graphMap, input.head, input.last)
      formGraph(graphMap, input.last, input.head)
    }
    for (entry <- graphMap) {
      //println(entry._1 + " " + entry._2.toString())
    }
    val inputColors: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
    val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()
    var j: Int = 1
    for (i <- inputColors) {
      colorsMap += (j -> i)
      j += 1
    }
    for (entry <- colorsMap) {
      //println(entry._1 + " " + entry._2.toString())
    }
    for (entry <- graphMap) {
      for (connectedVert <- entry._2) {
        if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {
          var rz = solve(graphMap, colorsMap, entry._1, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          }
          rz = solve(graphMap, colorsMap, connectedVert, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          } else {
            println("NO")
            return
          }
        }
      }
    }
  }

  def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {
    if (!graphMap.contains(a))
      graphMap += (a -> (new mutable.MutableList[Int] += b))
    else {
      val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get
      listOfVertex += b
    }
  }

  def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): Tuple2[String, Int] = {
    //usedVertexes(start) = true
    val linkedVertexes = new mutable.Queue[Int]
    linkedVertexes ++= graphMap.get(start).get
    while (linkedVertexes.nonEmpty) {
      val usedVertexes: Array[Boolean] = Array.fill(size + 1)(false)
      usedVertexes(start) = true
      val q: mutable.Queue[Int] = new mutable.Queue[Int]
      val setOfColors: mutable.HashSet[Int] = new mutable.HashSet
      q.enqueue(linkedVertexes.dequeue())
      while (q.nonEmpty) {
        val vert = q.dequeue()
        if (!usedVertexes(vert)) {
          setOfColors += colorGraph.get(vert).get
          if (setOfColors.size > 1)
            return ("NO", -1)
          val lv = graphMap.get(vert).get
          for (v <- lv)
            q.enqueue(v)
          usedVertexes(vert) = true
        }
      }
    }
    ("YES", start)
  }

}


You are given a grid with $$$n$$$ rows and $$$m$$$ columns, where each cell has a positive integer written on it. Let's call a grid good, if in each row the sequence of numbers is sorted in a non-decreasing order. It means, that for each $$$1 \le i \le n$$$ and $$$2 \le j \le m$$$ the following holds: $$$a_{i,j} \ge a_{i, j-1}$$$.You have to to do the following operation exactly once: choose two columns with indexes $$$i$$$ and $$$j$$$ (not necessarily different), $$$1 \le i, j \le m$$$, and swap them.You are asked to determine whether it is possible to make the grid good after the swap and, if it is, find the columns that need to be swapped.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of rows and columns respectively. Each of the next $$$n$$$ rows contains $$$m$$$ integers, $$$j$$$-th element of $$$i$$$-th row is $$$a_{i,j}$$$ ($$$1 \le a_{i,j} \le 10^9$$$) — the number written in the $$$j$$$-th cell of the $$$i$$$-th row. It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

If after the swap it is impossible to get a good grid, output $$$-1$$$. In the other case output $$$2$$$ integers — the indices of the columns that should be swapped to get a good grid. If there are multiple solutions, print any.

NoteIn the first test case the grid is initially good, so we can, for example, swap the first column with itself.In the second test case it is impossible to make the grid good.In the third test case it is needed to swap the first and the second column, then the grid becomes good.

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

object Main {

  def findNotSortedRow(a: Array[Array[Int]]): Option[Int] = {
    a.indices.find { i =>
      (1 until a(i).length).exists { j =>
        a(i)(j - 1) > a(i)(j)
      }
    }
  }

  def swapColumns(a: Array[Array[Int]], i: Int, j: Int) = {
    a.foreach { row =>
      val temp = row(i)
      row(i) = row(j)
      row(j) = temp
    }
  }

  def main(args: Array[String]): Unit = {
    val reader = new InputReader()
    val t = reader.nextInt()
    (1 to t).foreach { i =>
      val n = reader.nextInt()
      val m = reader.nextInt()
      val a = new Array[Array[Int]](n)
      a.indices.foreach(a(_) = new Array[Int](m))
      a.foreach { row =>
        row.indices.foreach(row(_) = reader.nextInt())
      }
      findNotSortedRow(a) match {
        case Some(rowId) =>
            val sortedRow = a(rowId).sorted
            val differentValues = new util.ArrayList[Int]()
            sortedRow.indices.foreach { i =>
              if (sortedRow(i) != a(rowId)(i)) differentValues.add(i)
            }
            if (differentValues.size() == 2) {
              swapColumns(a, differentValues.get(0), differentValues.get(1))
              if (findNotSortedRow(a).isEmpty) {
                System.out.println((differentValues.get(0) + 1) + " " + (differentValues.get(1) + 1))
              } else {
                System.out.println("-1")
              }
            } else {
              System.out.println("-1")
            }
        case None => System.out.println("1 1")
      }

    }

  }

  class InputReader() {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var line: Array[String] = null
    var cur: Int = 0

    def nextString(): String = {
      while (line == null || cur >= line.length) {
        cur = 0
        line = reader.readLine().split(""" """)
      }
      cur += 1
      line(cur - 1)
    }

    def nextInt(): Int = {
      nextString().toInt
    }

    def nextLong(): Int = {
      nextString().toInt
    }

  }

}

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

object Main {

  def findNotSortedRow(a: Array[Array[Int]]): Option[Int] = {
    a.indices.find { i =>
      (1 until a(i).length).exists { j =>
        a(i)(j - 1) > a(i)(j)
      }
    }
  }

  def swapColumns(a: Array[Array[Int]], i: Int, j: Int) = {
    a.foreach { row =>
      val temp = row(i)
      row(i) = row(j)
      row(j) = temp
    }
  }

  def main(args: Array[String]): Unit = {
    val reader = new InputReader()
    val t = reader.nextInt()
    (1 to t).foreach { i =>
      val n = reader.nextInt()
      val m = reader.nextInt()
      val a = new Array[Array[Int]](n)
      a.indices.foreach(a(_) = new Array[Int](m))
      a.foreach { row =>
        row.indices.foreach(row(_) = reader.nextInt())
      }
      findNotSortedRow(a) match {
        case Some(rowId) =>
            val sortedRow = a(rowId).sorted
            val differentValues = new util.ArrayList[Int]()
            sortedRow.indices.foreach { i =>
              if (sortedRow(i) != a(rowId)(i)) differentValues.add(i)
            }
            if (differentValues.size() == 2) {
              swapColumns(a, differentValues.get(0), differentValues.get(1))
              if (findNotSortedRow(a).isEmpty) {
                System.out.println((differentValues.get(0) + 1) + " " + (differentValues.get(1) + 1))
              } else {
                System.out.println("-1")
              }
            } else {
              System.out.println("1 1")
            }
        case None => System.out.println("1 1")
      }

    }

  }

  class InputReader() {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var line: Array[String] = null
    var cur: Int = 0

    def nextString(): String = {
      while (line == null || cur >= line.length) {
        cur = 0
        line = reader.readLine().split(""" """)
      }
      cur += 1
      line(cur - 1)
    }

    def nextInt(): Int = {
      nextString().toInt
    }

    def nextLong(): Int = {
      nextString().toInt
    }

  }

}


Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.

The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people. Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw.

Print one integer — the total number of alive people after the bell rings.

NoteIn first sample the last person kills everyone in front of him.

object B extends App {
  val n = scala.io.StdIn.readLine().toInt
  val L = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val l = L.length - 1

  def survivors(i: Int = l, j: Int = l, s: Int = 0): Int = {
    if (j <= 0) L.length - s
    else {
      val t = 0 max (i - L(i))
      if (j >= t) survivors(i - 1, t, s + (j min i) - t)
      else survivors(i - 1, j, s)
    }
  }

  println(survivors())
}

object B extends App {
  val n = scala.io.StdIn.readLine().toInt
  val L = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val l = L.length - 1

  def survivors(i: Int = l, j: Int = l, s: Int = 0): Int = {
    if (j <= 0) L.length - s
    else {
      val t = 0 max (i - L(i))
      if (t < j) survivors(i - 1, t, s + (j min i - t) max 0)
      else survivors(i - 1, j, s)
    }
  }

  println(survivors())
}


You've got an array a, consisting of n integers a1, a2, ..., an. You are allowed to perform two operations on this array:  Calculate the sum of current array elements on the segment [l, r], that is, count value al + al + 1 + ... + ar.  Apply the xor operation with a given number x to each array element on the segment [l, r], that is, execute . This operation changes exactly r - l + 1 array elements. Expression  means applying bitwise xor operation to numbers x and y. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as "^", in Pascal — as "xor".You've got a list of m operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get.

The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the original array. The third line contains integer m (1 ≤ m ≤ 5·104) — the number of operations with the array. The i-th of the following m lines first contains an integer ti (1 ≤ ti ≤ 2) — the type of the i-th query. If ti = 1, then this is the query of the sum, if ti = 2, then this is the query to change array elements. If the i-th operation is of type 1, then next follow two integers li, ri (1 ≤ li ≤ ri ≤ n). If the i-th operation is of type 2, then next follow three integers li, ri, xi (1 ≤ li ≤ ri ≤ n, 1 ≤ xi ≤ 106). The numbers on the lines are separated by single spaces.

For each query of type 1 print in a single line the sum of numbers on the given segment. Print the answers to the queries in the order in which the queries go in the input. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams, or the %I64d specifier.

object A extends App {
  class Tree(a: Array[Int]) {
    var n = a.size

    val s = new Array[Int](n * 2)
    val inv = new Array[Boolean](n * 2)

    build(0, n)

    def propagate(l: Int, r: Int) {
      if (inv(l+r)) {
        val m = (l+r) / 2
        inv(l+m) ^= inv(l+r)
        inv(m+r) ^= inv(l+r)
        inv(l+r) = false
      }
    }

    def sum(l: Int, r: Int, ll: Int, rr: Int): Int = {
      if (ll <= l && r <= rr)
        return if (inv(l+r)) r-l-s(l+r) else s(l+r)
      propagate(l, r)
      val m = (l+r) / 2
      var res = 0
      if (ll < m) res += sum(l, m, ll, rr)
      if (m < rr) res += sum(m, r, ll, rr)
      s(l+r) = sum(l, m, l, m) + sum(m, r, m, r)
      res
    }

    def invert(l: Int, r: Int, ll: Int, rr: Int) {
      if (ll <= l && r <= rr) {
        inv(l+r) ^= true
        return
      }
      propagate(l, r)
      val m = (l+r) / 2
      var res = 0
      if (ll < m) invert(l, m, ll, rr)
      if (m < rr) invert(m, r, ll, rr)
      s(l+r) = sum(l, m, l, m) + sum(m, r, m, r)
    }

    def build(l: Int, r: Int) {
      if (l == r-1)
        s(l+r) = a(l)
      else {
        val m = (l+r) / 2
        build(l, m)
        build(m, r)
        s(l+r) = s(l+m) + s(m+r)
      }
    }
  }

  val n = readInt
  var nn = n
  while ((nn & nn-1) > 0)
    nn += nn & -nn

  val a = readLine split ' ' map (_.toInt)
  val b = new Array[Int](nn)
  val trees = new Array[Tree](20)

  for (i <- 0 until 20) {
    for (j <- 0 until nn)
      b(j) = if (j < n && (a(j) & 1 << i) != 0) 1 else 0
    trees(i) = new Tree(b)
  }

  val m = readInt
  val res = new StringBuffer
  for (i <- 0 until m) {
    val o = readLine split ' ' map (_.toInt)
    if (o(0) == 1) {
      var s = 0L
      for (j <- 0 until 20)
        s += trees(j).sum(0, nn, o(1)-1, o(2)).toLong << j
      res append (s + "\n")
    } else {
      for (j <- 0 until 20)
        if ((o(3) & 1 << j) != 0)
          trees(j).invert(0, nn, o(1)-1, o(2))
    }
  }
  print(res)
}

object A extends App {
  class Tree(a: Array[Int]) {
    var n = a.size

    val s = new Array[Int](n * 2)
    val inv = new Array[Boolean](n * 2)

    build(0, n)

    def propagate(l: Int, r: Int) {
      if (inv(l+r)) {
        val m = (l+r) / 2
        inv(l+m) ^= inv(l+r)
        inv(m+r) ^= inv(l+r)
        inv(l+r) = false
      }
    }

    def sum(l: Int, r: Int, ll: Int, rr: Int): Int = {
      if (ll <= l && r <= rr)
        return if (inv(l+r)) r-l-s(l+r) else s(l+r)
      propagate(l, r)
      val m = (l+r) / 2
      var res = 0
      if (ll < m) res += sum(l, m, ll, rr)
      if (m < rr) res += sum(m, r, ll, rr)
      res
    }

    def invert(l: Int, r: Int, ll: Int, rr: Int) {
      if (ll <= l && r <= rr) {
        inv(l+r) ^= true
        return
      }
      propagate(l, r)
      val m = (l+r) / 2
      var res = 0
      if (ll < m) invert(l, m, ll, rr)
      if (m < rr) invert(m, r, ll, rr)
      s(l+r) = sum(l, m, l, m) + sum(m, r, m, r)
    }

    def build(l: Int, r: Int) {
      if (l == r-1)
        s(l+r) = a(l)
      else {
        val m = (l+r) / 2
        build(l, m)
        build(m, r)
        s(l+r) = s(l+m) + s(m+r)
      }
    }
  }

  val n = readInt
  var nn = n
  while ((nn & nn-1) > 0)
    nn += nn & -nn

  val a = readLine split ' ' map (_.toInt)
  val b = new Array[Int](nn)
  val trees = new Array[Tree](20)

  for (i <- 0 until 20) {
    for (j <- 0 until nn)
      b(j) = if (j < n && (a(j) & 1 << i) != 0) 1 else 0
    trees(i) = new Tree(b)
  }

  val m = readInt
  val res = new StringBuffer
  for (i <- 0 until m) {
    val o = readLine split ' ' map (_.toInt)
    if (o(0) == 1) {
      var s = 0L
      for (j <- 0 until 20)
        s += trees(j).sum(0, nn, o(1)-1, o(2)).toLong << j
      res append (s + "\n")
    } else {
      for (j <- 0 until 20)
        if ((o(3) & 1 << j) != 0)
          trees(j).invert(0, nn, o(1)-1, o(2))
    }
  }
  print(res)
}


Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows:  You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes.

The first line contains two integers n and q (1 ≤ n ≤ 1018, 1 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers xi (1 ≤ xi ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes.

For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.

NoteThe first example is shown in the picture.In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7].

object dTask4 {
  import scala.io.StdIn.{readLine,readLong}

  def main(args: Array[String]): Unit = {
    val n::q::Nil = readLine.split(" ").map(_.toLong).toList
    def getNum(x: Long): Long = {
      if((x & 1) == 0) getNum(x/2 + n)
      else (x + 1) / 2
    }
    val arr = (0 until q.toInt).map(_ => readLong)
    println(arr.map(x => getNum(x)).mkString("\n"))
  }
}


A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $$$k$$$-balanced if every substring of size $$$k$$$ of this bitstring has an equal amount of 0 and 1 characters ($$$\frac{k}{2}$$$ of each).You are given an integer $$$k$$$ and a string $$$s$$$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $$$k$$$-balanced bitstring by replacing every ? characters in $$$s$$$ with either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ is even)  — the length of the string and the parameter for a balanced bitstring. The next line contains the string $$$s$$$ ($$$|s| = n$$$). It is given that $$$s$$$ consists of only 0, 1, and ?. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print YES if we can replace every ? in $$$s$$$ with 0 or 1 such that the resulting bitstring is $$$k$$$-balanced, or NO if it is not possible.

NoteFor the first test case, the string is already a $$$4$$$-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val sn          = readLine()

    def isBalanced: Boolean = {
      var mk = Array.fill(k)('?')

      @annotation.tailrec
      def go(i: Int): Boolean =
        if (i == n) true
        else if (sn(i) == '?') go(i + 1)
        else if (mk(i % k) == '?') {
          mk(i % k) = sn(i)
          go(i + 1)
        } else mk(i % k) == sn(i) && go(i + 1)

      go(0) && mk.count(_ == '1') <= k / 2 && mk.count(_ == '0') <= k / 2
    }

    val ans = isBalanced match {
      case true => "YES"
      case _    => "NO"
    }

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val sn          = readLine()

    def isBalanced: Boolean = {
      var mk = Array.fill(k)('?')

      @annotation.tailrec
      def go(i: Int): Boolean =
        if (i == n) true
        else if (mk(i % k) == '?') {
          mk(i % k) = sn(i)
          go(i + 1)
        } else mk(i % k) == sn(i) && go(i + 1)

      go(0) && {
        mk.count(_ == '1') <= k / 2 && mk.count(_ == '0') <= k / 2
      }
    }

    val ans = isBalanced match {
      case true => "YES"
      case _    => "NO"
    }

    println(ans)
  }
}