Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.In his favorite math class, the teacher taught him the following interesting definitions.A parenthesis sequence is a string, containing only characters "(" and ")".A correct parenthesis sequence is a parenthesis sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, parenthesis sequences "()()", "(())" are correct (the resulting expressions are: "(1+1)+(1+1)", "((1+1)+1)"), while ")(" and ")" are not. Note that the empty string is a correct parenthesis sequence by definition.We define that $$$|s|$$$ as the length of string $$$s$$$. A strict prefix $$$s[1\dots l]$$$ $$$(1\leq l< |s|)$$$ of a string $$$s = s_1s_2\dots s_{|s|}$$$ is string $$$s_1s_2\dots s_l$$$. Note that the empty string and the whole string are not strict prefixes of any string by the definition.Having learned these definitions, he comes up with a new problem. He writes down a string $$$s$$$ containing only characters "(", ")" and "?". And what he is going to do, is to replace each of the "?" in $$$s$$$ independently by one of "(" and ")" to make all strict prefixes of the new sequence not a correct parenthesis sequence, while the new sequence should be a correct parenthesis sequence.After all, he is just a primary school student so this problem is too hard for him to solve. As his best friend, can you help him to replace the question marks? If there are many solutions, any of them is acceptable.

The first line contains a single integer $$$|s|$$$ ($$$1\leq |s|\leq 3 \cdot 10^5$$$), the length of the string. The second line contains a string $$$s$$$, containing only "(", ")" and "?".

A single line contains a string representing the answer. If there are many solutions, any of them is acceptable. If there is no answer, print a single line containing ":(" (without the quotes).

NoteIt can be proved that there is no solution for the second sample, so print ":(".

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 private final 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 private final 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 solve(): Unit = {
    val n = ni()
    val s = ns(n)
    var bal = 0

    val bals = Array.ofDim[Int](n)
    val cum = cumSum(s.map {
      case '(' => 1
      case ')' => -1
      case '?' => 0
    })
    val cumQ = cumSum(s.map {
      case '?' => 1
      case _ => 0
    })

    REP(n) { i =>
      if (s(i) == '(') {
        bal += 1
      } else if (s(i) == ')') {
        bal -= 1
      } else {
        if (bal + 1 + cum(n) - cum(i + 1) <= cumQ(n) - cumQ(i + 1)) {
          s(i) = '('
          bal += 1
        } else {
          s(i) = ')'
          bal -= 1
        }
      }
      bals(i) = bal
    }

    debug(bals)
    val ok = bal == 0 && bals.dropRight(1).forall(a => a > 0)

    if (ok) out.println(s.mkString)
    else out.println(":(")
  }
}

import java.io.FileInputStream
import scala.collection.mutable.TreeSet

object HelloWorld {

    import scala.io.StdIn.{readInt, readLine}

    def main(args: Array[String]): Unit = {
        val n = readInt
        val str = readLine

        val ls = str.count(p => p == '(')

        var newLs = n / 2 - ls
        val newStr = str.map(c => {
            if (c == '?') {
                if (newLs > 0) {
                    newLs -= 1
                    '('
                }
                else ')'
            } else c
        })

        var st = 0
        for ((c, i) <- newStr.zipWithIndex) {
            if (c == '(') st += 1
            else {
                st -= 1
                if (st <= 0 && i < n-1) {
                    println(":(")
                    System.exit(0)
                }
            }
        }

        if (st == 0) println(newStr)
        else println(":(")

    }
}


You are given $$$n$$$ segments on a coordinate axis $$$OX$$$. The $$$i$$$-th segment has borders $$$[l_i; r_i]$$$. All points $$$x$$$, for which $$$l_i \le x \le r_i$$$ holds, belong to the $$$i$$$-th segment.Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.Two segments $$$[l_i; r_i]$$$ and $$$[l_j; r_j]$$$ are non-intersecting if they have no common points. For example, segments $$$[1; 2]$$$ and $$$[3; 4]$$$, $$$[1; 3]$$$ and $$$[5; 5]$$$ are non-intersecting, while segments $$$[1; 2]$$$ and $$$[2; 3]$$$, $$$[1; 2]$$$ and $$$[2; 2]$$$ are intersecting.The segment $$$[l_i; r_i]$$$ lies inside the segment $$$[l_j; r_j]$$$ if $$$l_j \le l_i$$$ and $$$r_i \le r_j$$$. For example, segments $$$[2; 2]$$$, $$$[2, 3]$$$, $$$[3; 4]$$$ and $$$[2; 4]$$$ lie inside the segment $$$[2; 4]$$$, while $$$[2; 5]$$$ and $$$[1; 4]$$$ are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3000$$$) — the number of segments. The next $$$n$$$ lines describe segments. The $$$i$$$-th segment is given as two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 2 \cdot 10^5$$$), where $$$l_i$$$ is the left border of the $$$i$$$-th segment and $$$r_i$$$ is the right border of the $$$i$$$-th segment. Additional constraint on the input: there are no duplicates in the list of segments. It is guaranteed that the sum of $$$n$$$ does not exceed $$$3000$$$ ($$$\sum n \le 3000$$$).

For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.

//package codeforces.contests._1399

import scala.collection.mutable.ArrayBuffer

object YetAnotherSegmentsSubset {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()
      val input: Array[Array[Int]] = new Array[Array[Int]](n) // l and r
      input.indices.foreach(input(_) = io.StdIn.readLine.split(" ").map(_.toInt))

      val pairs = {
        val sorted = input.sortWith { (first, second) => // in place
          val fr = first(1)
          val sr = second(1)
          if (fr == sr) {
            val fl = first(0)
            val sl = second(0)
            fl >= sl
          } else fr < sr
        }

        val result = new Array[(Int, Int, Int)](n)
        (0 until n).foreach(i => result(i) = (sorted(i)(0), sorted(i)(1), i))
        result
      }

      val subSegments: Array[Array[(Int, Int, Int)]] = {
        val subs = Array.fill[ArrayBuffer[(Int, Int, Int)]](n)(ArrayBuffer.empty)

        for (i <- 0 until n) {
          val fi = pairs(i)._1
          var j = i - 1
          while (j >= 0 && pairs(j)._2 >= fi) {
            if (pairs(j)._1 >= fi) subs(i) += pairs(j)
            j -= 1
          }
        }

        subs.map(_.toArray.reverse)
      }

      val cache = Array.fill[Int](n + 1)(-1) // sub-segment result for each interval

      def solveAndCacheAtIdx(seq: Array[(Int, Int, Int)], idx: Int): Int = {
        if (seq.isEmpty) 0
        else if (cache(idx) != -1) cache(idx)
        else {
          val dp = new Array[Int](seq.length)
          for (i <- seq.indices) {
            val pos = seq(i)._3
            dp(i) = 1 + solveAndCacheAtIdx(subSegments(pos), pos) + {

              val key = seq(i)._1

              var l = 0
              var j = i - 1

              while (l <= j) {
                val m = (l + j) / 2
                if (seq(m)._2 >= key) j = m - 1
                else l = m + 1
              }

              if (j >= 0) dp(j) else 0
            }

            dp(i) = dp(i) max (if (i > 0) dp(i - 1) else 0)
          }
          val result = dp.max
          cache(idx) = result
          result
        }
      }

      println(solveAndCacheAtIdx(pairs, n))
    }
  }
}

//package codeforces.contests._1399

import scala.collection.mutable.ArrayBuffer

object YetAnotherSegmentsSubset {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()
      val input: Array[Array[Int]] = new Array[Array[Int]](n) // l and r
      input.indices.foreach(input(_) = io.StdIn.readLine.split(" ").map(_.toInt))

      val pairs = {
        val sorted = input.sortWith { (first, second) =>
          val fr = first(1)
          val sr = second(1)
          if (fr == sr) {
            val fl = first(0)
            val sl = second(0)
            fl >= sl
          } else fr < sr
        }

        val result = new Array[(Int, Int, Int)](n)
        (0 until n).foreach(i => result(i) = (sorted(i)(0), sorted(i)(1), i))
        result
      }

      val subSegments: Array[Array[(Int, Int, Int)]] = {
        val subs = Array.fill[ArrayBuffer[(Int, Int, Int)]](n)(ArrayBuffer.empty)

        for (i <- 0 until n) {
          val fi = pairs(i)._1
          var j = i - 1
          while (j >= 0 && pairs(j)._2 >= fi) {
            if (pairs(j)._1 >= fi) subs(i) += pairs(j)
            j -= 1
          }
        }

        subs.map(_.toArray.reverse)
      }

      val cache = Array.fill[Int](n + 1)(-1) // sub-segment result for each interval

      def solveAndCache(seq: Array[(Int, Int, Int)], idx: Int): Int = {
        if (seq.isEmpty) 0
        else if (cache(idx) != -1) cache(idx)
        else {
          val dp = new Array[Int](seq.length)
          for (i <- seq.indices) {
            val l = seq(i)._1
            val pos = seq(i)._3
            dp(i) = 1 + solveAndCache(subSegments(pos), pos) + {
              var j = i - 1
              while (j >= 0 && seq(j)._2 >= l) j -= 1
              if (j >= 0) dp(j) else 0
            }
          }
          val result = dp.max
          cache(idx) = result
          result
        }
      }

      println(solveAndCache(pairs, n))
    }
  }
}


There are three sticks with integer lengths $$$l_1, l_2$$$ and $$$l_3$$$.You are asked to break exactly one of them into two pieces in such a way that:   both pieces have positive (strictly greater than $$$0$$$) integer length;  the total length of the pieces is equal to the original length of the stick;  it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides. A square is also considered a rectangle.Determine if it's possible to do that.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains three integers $$$l_1, l_2, l_3$$$ ($$$1 \le l_i \le 10^8$$$) — the lengths of the sticks.

For each testcase, print "YES" if it's possible to break one of the sticks into two pieces with positive integer length in such a way that it's possible to construct a rectangle from the resulting four sticks. Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as a positive answer).

NoteIn the first testcase, the first stick can be broken into parts of length $$$1$$$ and $$$5$$$. We can construct a rectangle with opposite sides of length $$$1$$$ and $$$5$$$.In the second testcase, breaking the stick of length $$$2$$$ can only result in sticks of lengths $$$1, 1, 2, 5$$$, which can't be made into a rectangle. Breaking the stick of length $$$5$$$ can produce results $$$2, 3$$$ or $$$1, 4$$$ but neither of them can't be put into a rectangle.In the third testcase, the second stick can be broken into parts of length $$$2$$$ and $$$2$$$. The resulting rectangle has opposite sides $$$2$$$ and $$$2$$$ (which is a square).In the fourth testcase, the third stick can be broken into parts of length $$$2$$$ and $$$2$$$. The resulting rectangle has opposite sides $$$2$$$ and $$$5$$$.

import scala.io.StdIn
import java.util.Scanner

object Main {
    def sort2(a: Array[Int], i: Int, j: Int) = {
        if(a(i) > a(j)){
            val tmp = a(i)
            a(i) = a(j)
            a(j) = tmp
        }
    }

    def solve() = {
        var a = new Array[Int](3)
        val inp = StdIn.readLine()
        val line = new Scanner(inp)
        for (i <- 0 to 2){
            a(i) = line.nextInt()
        }
        // sort
        sort2(a, 0, 1)
        sort2(a, 1, 2)
        sort2(a, 0, 1)

        if(a(0) + a(1) == a(2)
                || (a(0) == a(1) && 0 == (a(2) % 2))
                || (a(1) == a(2) && 0 == (a(0) % 2))){
            println("YES")
        }else{
            println("NO")
        }
    }

    def main(args: Array[String]) = {
        val tc = StdIn.readInt()
        for (i <- 1 to tc) {
            solve()
        }
    }
}

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

    for (_ <- 1 to nextInt) {
      val ls = nextInts(3).sorted
      val ok = (ls(0) + ls(1) == ls(2)) || (ls(0) == ls(1) && ls(2) % 2 == 0) ||
        (ls(0) == ls(2) && ls(1) % 2 == 0) || (ls(2) == ls(1) && ls(0) % 2 == 0)

      out.println(if(ok) "YES" else "NO")
    }

    out.flush()
  }

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


You are given a forest — an undirected graph with $$$n$$$ vertices such that each its connected component is a tree.The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.If there are multiple correct answers, print any of them.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 1000$$$, $$$0 \le m \le n - 1$$$) — the number of vertices of the graph and the number of edges, respectively. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$, $$$v \ne u$$$) — the descriptions of the edges. It is guaranteed that the given graph is a forest.

In the first line print the diameter of the resulting tree. Each of the next $$$(n - 1) - m$$$ lines should contain two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$, $$$v \ne u$$$) — the descriptions of the added edges. The resulting graph should be a tree and its diameter should be minimal possible. For $$$m = n - 1$$$ no edges are added, thus the output consists of a single integer — diameter of the given tree. If there are multiple correct answers, print any of them.

NoteIn the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.Edge (1, 2) is the only option you have for the second example. The diameter is 1.You can't add any edges in the third example. The diameter is already 2.

import java.util
import java.util.Collections

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, M = ni()
    val (from, to) = na2(M, -1)
    val g = packUGraph(N, from, to)

    // 半径が一番でかいのに全部つなげるのがおとく
    val trees = centersOfForest(g).toArray
    Sorting.quickSort(trees)(Ordering.by(-_._2))

    val t1 = trees.head
    val newEdges = trees.drop(1) map { t2 =>
      t1._1.head -> t2._1.head
    }

    val newFrom, newTo = Array.ofDim[Int](N - 1)
    System.arraycopy(from, 0, newFrom, 0, M)
    System.arraycopy(to, 0, newTo, 0, M)
    REP(N - 1 - M) { i =>
      newFrom(i + M) = newEdges(i)._1
      newTo(i + M) = newEdges(i)._2
    }
    val newTree = packUGraph(N, newFrom, newTo)
    val (_, d, _) = centerOfTree(newTree)
    out.println(d)
    newEdges.foreach { case (u, v) =>
      out.println(s"${u+1} ${v+1}")
    }
  }

  /**
    * すでに直径、直径のノードがわかっている場合は、直径の半分だけ親をたどればいいのでもっと楽にできる
    * todo *注意* エッジが空のときに動かない
    * @return (木の中心１こor２個, 直径, 半径)
    */
  def centerOfTree(t: Array[Array[Int]]): (Array[Int], Int, Int) = {
    val n = t.length

    var cur = 0
    var p = 0
    val queue = Array.ofDim[Int](n)
    val degree = Array.ofDim[Int](n)
    val lvl = Array.ofDim[Int](n)
    REP(n) { i =>
      degree(i) = t(i).length
      if (degree(i) == 1) {
        queue(p) = i
        p += 1
      }
    }

    while(cur < p) {
      val v = queue(cur)
      cur += 1
      REP(t(v).length) { i =>
        val u = t(v)(i)

        // parentを探す
        if (degree(u) > 0) {
          degree(u) -= 1
          if (degree(u) == 1) {
            lvl(u) = lvl(v) + 1
            queue(p) = u
            p += 1
          }
        }
      }
      degree(v) -= 1
    }

    val c1 = queue(n - 1)
    if (n >= 2 && lvl(c1) == lvl(queue(n - 2))) {
      val c2 = queue(n - 2)
      (Array(c1, c2), lvl(c1) * 2 + 1, lvl(c1) + 1)
    } else {
      (Array(c1), lvl(c1) * 2, lvl(c1))
    }
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  // (centers, redius)
  type Tree = (Array[Int], Int)

  def centersOfForest(g: Array[Array[Int]]): ArrayBuffer[Tree] = {
    val n = g.length

    var cur = 0
    var p = 0
    val queue = Array.ofDim[Int](n)
    val degree = Array.ofDim[Int](n)
    val lvl = Array.ofDim[Int](n)
    val last = Array.ofDim[Int](n) // 最後にエッジを削除したときの対になるノード
    val res = ArrayBuffer[Tree]()

    REP(n) { i =>
      degree(i) = g(i).length
      if (degree(i) == 1) {
        queue(p) = i
        p += 1

      // どこともつながっていないノードもツリーとみなす
      } else if (degree(i) == 0) {
        res += ((Array(i), 0))
      }
    }

    while(cur < p) {
      val v = queue(cur)
      cur += 1
      var parent = -1
      REP(g(v).length) { i =>
        val u = g(v)(i)
        // parentを探す
        if (degree(u) > 0) parent = u
      }
      if (parent != -1) {
        val u = parent
        degree(u) -= 1
        if (degree(u) == 1) {
          lvl(u) = lvl(v) + 1
          queue(p) = u
          last(u) = v
          p += 1
        }
      } else {
        val c1 = v
        if (n >= 2 && lvl(c1) == lvl(last(v))) {
          val c2 = last(v)
          res += ((Array(c1, c2), lvl(c1) + 1))
        } else {
          res += ((Array(c1), lvl(c1)))
        }
      }
      degree(v) -= 1
    }

    res
  }

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

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

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

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

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

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

import java.util

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, M = ni()
    val (from, to) = na2(M, -1)
    val g = packUGraph(N, from, to)

    val centers = centersOfForest(g)
    val newEdges = centers zip centers.drop(1) map { case (t1, t2) =>
      t1._1.head -> t2._1.head
    }

    val newFrom, newTo = Array.ofDim[Int](N - 1)
    System.arraycopy(from, 0, newFrom, 0, M)
    System.arraycopy(to, 0, newTo, 0, M)
    REP(N - 1 - M) { i =>
      newFrom(i + M) = newEdges(i)._1
      newTo(i + M) = newEdges(i)._2
    }
    val newTree = packUGraph(N, newFrom, newTo)
    val (_, d, _) = centerOfTree(newTree)
    out.println(d)
    newEdges.foreach { case (u, v) =>
      out.println(s"${u+1} ${v+1}")
    }
  }

  /**
    * すでに直径、直径のノードがわかっている場合は、直径の半分だけ親をたどればいいのでもっと楽にできる
    * todo *注意* エッジが空のときに動かない
    * @return (木の中心１こor２個, 直径, 半径)
    */
  def centerOfTree(t: Array[Array[Int]]): (Array[Int], Int, Int) = {
    val n = t.length

    var cur = 0
    var p = 0
    val queue = Array.ofDim[Int](n)
    val degree = Array.ofDim[Int](n)
    val lvl = Array.ofDim[Int](n)
    REP(n) { i =>
      degree(i) = t(i).length
      if (degree(i) == 1) {
        queue(p) = i
        p += 1
      }
    }

    while(cur < p) {
      val v = queue(cur)
      cur += 1
      REP(t(v).length) { i =>
        val u = t(v)(i)

        // parentを探す
        if (degree(u) > 0) {
          degree(u) -= 1
          if (degree(u) == 1) {
            lvl(u) = lvl(v) + 1
            queue(p) = u
            p += 1
          }
        }
      }
      degree(v) -= 1
    }

    val c1 = queue(n - 1)
    if (n >= 2 && lvl(c1) == lvl(queue(n - 2))) {
      val c2 = queue(n - 2)
      (Array(c1, c2), lvl(c1) * 2 + 1, lvl(c1) + 1)
    } else {
      (Array(c1), lvl(c1) * 2, lvl(c1))
    }
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  type Tree = (Array[Int], Int)

  def centersOfForest(g: Array[Array[Int]]): ArrayBuffer[Tree] = {
    val n = g.length

    var cur = 0
    var p = 0
    val queue = Array.ofDim[Int](n)
    val degree = Array.ofDim[Int](n)
    val lvl = Array.ofDim[Int](n)
    val last = Array.ofDim[Int](n) // 最後にエッジを削除したときの対になるノード
    val res = ArrayBuffer[Tree]()

    REP(n) { i =>
      degree(i) = g(i).length
      if (degree(i) == 1) {
        queue(p) = i
        p += 1

      // どこともつながっていないノードもツリーとみなす
      } else if (degree(i) == 0) {
        res += ((Array(i), 0))
      }
    }

    while(cur < p) {
      val v = queue(cur)
      cur += 1
      var parent = -1
      REP(g(v).length) { i =>
        val u = g(v)(i)
        // parentを探す
        if (degree(u) > 0) parent = u
      }
      if (parent != -1) {
        val u = parent
        degree(u) -= 1
        if (degree(u) == 1) {
          lvl(u) = lvl(v) + 1
          queue(p) = u
          last(u) = v
          p += 1
        }
      } else {
        val c1 = v
        if (n >= 2 && lvl(c1) == lvl(last(v))) {
          val c2 = last(v)
          res += ((Array(c1, c2), lvl(c1) * 2 + 1))
        } else {
          res += ((Array(c1), lvl(c1) * 2))
        }
      }
      degree(v) -= 1
    }

    res
  }

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

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

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

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

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

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


There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.

The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads.

Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.

import scala.collection.mutable.ArrayBuffer

object Journey {
  var res=0D
  var graph:Array[ArrayBuffer[Int]]=null
  var vis:Array[Boolean]=null
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var n=in.readInt()
    graph=Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer[Int]())
    for(_<- 0 until n-1){
      val edges=in.readLine().split(" ").map(_.toInt-1)
      graph(edges(0))+=edges(1)
      graph(edges(1))+=edges(0)
    }
    vis=Array.fill[Boolean](n)(false)
    dfs(0,1.0,0.0)
    println(res)
  }
  def dfs(u:Int,prob:Double,depth:Double):Unit={
    if(!vis(u)){
      vis(u)=true
      if(graph(u).length==1)
        res += depth * prob

      for(v<- 0 until graph(u).length){
        if(u==0)
          dfs(graph(u)(v),prob/(graph(u).length+0.0),depth+1)
        else
          dfs(graph(u)(v),prob/(graph(u).length-1.0),depth+1)
      }
    }
  }
}

//package codeforces

/*

http://codeforces.com/problemset/problem/839/C

 */
object Journeyy {

  type Graph = Map[Int, Set[Int]]

  def update(graph: Graph, x: Int, y: Int): Graph = {
    val setX: Set[Int] = graph.withDefaultValue(Set())(x)
    val setY: Set[Int] = graph.withDefaultValue(Set())(y)
    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val graph: Graph = (1 until n).foldLeft[Graph](Map[Int, Set[Int]](1 -> Set(0)))((acc, _) => {
      val Array(x, y) = io.StdIn.readLine.split(" ").map(_.toInt)
      update(acc, x, y)
    })

    println(calculateExpectedValue(1, 0, 0, 1.0))

    def calculateExpectedValue(me: Int, parent: Int, distance: Int, probability: Double): Double = {
      if (graph(me).size == 1) {
        probability * distance
      } else {
        val count = graph(me).size - 1
        val updatedProbability = probability * (1.0/count)

        graph(me).filter(_ != parent)
          .foldLeft[Double](0.0)((acc, child) => acc + calculateExpectedValue(child, parent = me, distance + 1, updatedProbability))
      }
    }
  }

}


Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.

The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s. The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only. The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.

Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.

NoteIn the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.


You are given two arrays of integers $$$a_1, a_2, \ldots, a_n$$$ and $$$b_1, b_2, \ldots, b_n$$$.Let's define a transformation of the array $$$a$$$:  Choose any non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$.  Choose $$$k$$$ distinct array indices $$$1 \le i_1 < i_2 < \ldots < i_k \le n$$$.  Add $$$1$$$ to each of $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$, all other elements of array $$$a$$$ remain unchanged.  Permute the elements of array $$$a$$$ in any order. Is it possible to perform some transformation of the array $$$a$$$ exactly once, so that the resulting array is equal to $$$b$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Descriptions of test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \le a_i \le 100$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$-100 \le b_i \le 100$$$).

For each test case, print "YES" (without quotes) if it is possible to perform a transformation of the array $$$a$$$, so that the resulting array is equal to $$$b$$$. Print "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case, we can make the following transformation:  Choose $$$k = 2$$$.  Choose $$$i_1 = 1$$$, $$$i_2 = 2$$$.  Add $$$1$$$ to $$$a_1$$$ and $$$a_2$$$. The resulting array is $$$[0, 2, 0]$$$.  Swap the elements on the second and third positions. In the second test case there is no suitable transformation.In the third test case we choose $$$k = 0$$$ and do not change the order of elements.

import scala.io.StdIn

object ProblemC extends App {
  type TestCase = (Array[Int], Array[Int])
  type Result = String

  start()

  def start() = {
    println(parseInput(testCases).map(s => solve(s).mkString).mkString("\n"))
  }

  def testCases = StdIn.readLine.stripLineEnd.toInt

  def parseInput(testCases: Int): List[TestCase] = {
    var result: List[TestCase] = Nil
    for (_ <- 0.until(testCases)) {
      StdIn.readLine()
      val a = StdIn.readLine().split(" ").map(_.stripLineEnd.trim.toInt).toArray
      val b = StdIn.readLine().split(" ").map(_.stripLineEnd.trim.toInt).toArray
      result = (a,b) :: result
    }
    result.reverse
  }

  def solve(testCase: TestCase): Result = {
    (testCase._1.sorted zip testCase._2.sorted).map(ab => ab._1 - ab._2).forall(d => d == 0 || d == -1) match {
      case true => "YES"
      case false => "NO"
    }
  }

}

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

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

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

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

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

    val t = readInt()
    for (tt <- 1 to t) {
        var n = readInt()
        var a = new Array[Int](n)
        var b = new Array[Int](n)
        for (i <- 1 to n)
            a(i-1) = readInt()
        for (i <- 1 to n)
            b(i-1) = readInt()
        quickSort(a)
        quickSort(b)
        var ans  = "YES"
        for (i <- 0 until n) {
            if (b(i) < a(i) || b(i) > a(i) + 1)
                ans = "NO"
            //writer.println(b(i) + " " + a(i))
        }
        writer.println(ans)
    }
    writer.flush()
}

import scala.io.StdIn

object ProblemC extends App {
  type TestCase = (Array[Int], Array[Int])
  type Result = String

  start()

  def start() = {
    println(parseInput(testCases).map(s => solve(s).mkString).mkString("\n"))
  }

  def testCases = StdIn.readLine.stripLineEnd.toInt

  def parseInput(testCases: Int): List[TestCase] = {
    var result: List[TestCase] = Nil
    for (_ <- 0.until(testCases)) {
      StdIn.readLine()
      val a = StdIn.readLine().split(" ").map(_.stripLineEnd.trim.toInt).toArray
      val b = StdIn.readLine().split(" ").map(_.stripLineEnd.trim.toInt).toArray
      result = (a,b) :: result
    }
    result.reverse
  }

  def solve(testCase: TestCase): Result = {
    (testCase._1.sorted zip testCase._2.sorted).map(ab => ab._1 - ab._2).forall(diff => math.abs(diff) <= 1) match {
      case true => "YES"
      case false => "NO"
    }
  }

}


You are given a string $$$s$$$. You need to find two non-empty strings $$$a$$$ and $$$b$$$ such that the following conditions are satisfied:  Strings $$$a$$$ and $$$b$$$ are both subsequences of $$$s$$$.  For each index $$$i$$$, character $$$s_i$$$ of string $$$s$$$ must belong to exactly one of strings $$$a$$$ or $$$b$$$.  String $$$a$$$ is lexicographically minimum possible; string $$$b$$$ may be any possible string. Given string $$$s$$$, print any valid $$$a$$$ and $$$b$$$.Reminder:A string $$$a$$$ ($$$b$$$) is a subsequence of a string $$$s$$$ if $$$a$$$ ($$$b$$$) can be obtained from $$$s$$$ by deletion of several (possibly, zero) elements. For example, "dores", "cf", and "for" are subsequences of "codeforces", while "decor" and "fork" are not.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds:  $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$;  in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains one string $$$s$$$ ($$$2 \le |s| \le 100$$$ where $$$|s|$$$ means the length of $$$s$$$). String $$$s$$$ consists of lowercase Latin letters.

For each test case, print the strings $$$a$$$ and $$$b$$$ that satisfy the given conditions. If there are multiple answers, print any.

NoteIn the first test case, there are only two choices: either $$$a =$$$ f and $$$b = $$$ c or $$$a = $$$ c and $$$b = $$$ f. And $$$a = $$$c is lexicographically smaller than $$$a = $$$ f.In the second test case, a is the only character in the string.In the third test case, it can be proven that b is the lexicographically smallest subsequence of $$$s$$$. The second string can be of two variants; one of them is given here.

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

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

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val s = readString()
        var a = (65535).toChar
        var ind = -1
        for (i <- 0 until s.length) {
            if (s(i) < a) {
                a = s(i)
                ind = i
            }
        }
        val b = s.substring(0, ind) + s.substring(ind+1, s.length)
        writer.println(a + " " + b)
    }
    writer.flush()
}


Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $$$x$$$, and the shorter rabbit is currently on position $$$y$$$ ($$$x \lt y$$$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $$$a$$$, and the shorter rabbit hops to the negative direction by $$$b$$$.  For example, let's say $$$x=0$$$, $$$y=10$$$, $$$a=2$$$, and $$$b=3$$$. At the $$$1$$$-st second, each rabbit will be at position $$$2$$$ and $$$7$$$. At the $$$2$$$-nd second, both rabbits will be at position $$$4$$$.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Each test case contains exactly one line. The line consists of four integers $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$ ($$$0 \le x \lt y \le 10^9$$$, $$$1 \le a,b \le 10^9$$$) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.

For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position. If the two rabbits will never be at the same position simultaneously, print $$$-1$$$.

NoteThe first case is explained in the description.In the second case, each rabbit will be at position $$$3$$$ and $$$7$$$ respectively at the $$$1$$$-st second. But in the $$$2$$$-nd second they will be at $$$6$$$ and $$$4$$$ respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

import scala.io.StdIn

object Main extends App {

  private val getSec: (Int, Int, Int, Int) => Int =
    (x, y, a, b) => {
      if ((y - x) % (a + b) == 0)
        (y - x) / (a + b)
      else
        -1
    }

  var n: Int = StdIn.readLine().toInt

  while (n != 0) {
    val line = StdIn.readLine().split("\\s")

    val x = line(0).toInt
    val y = line(1).toInt
    val a = line(2).toInt
    val b = line(3).toInt

    println(getSec(x, y, a, b))

    n -= 1
  }

}


NIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to $$$\operatorname{or} z$$$. Can you solve this problem too?You are given a 1-indexed array of $$$n$$$ integers, $$$a$$$, and an integer $$$z$$$. You can do the following operation any number (possibly zero) of times:  Select a positive integer $$$i$$$ such that $$$1\le i\le n$$$. Then, simutaneously set $$$a_i$$$ to $$$(a_i\operatorname{or} z)$$$ and set $$$z$$$ to $$$(a_i\operatorname{and} z)$$$. In other words, let $$$x$$$ and $$$y$$$ respectively be the current values of $$$a_i$$$ and $$$z$$$. Then set $$$a_i$$$ to $$$(x\operatorname{or}y)$$$ and set $$$z$$$ to $$$(x\operatorname{and}y)$$$. Here $$$\operatorname{or}$$$ and $$$\operatorname{and}$$$ denote the bitwise operations OR and AND respectively.Find the maximum possible value of the maximum value in $$$a$$$ after any number (possibly zero) of operations.

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 $$$z$$$ ($$$1\le n\le 2000$$$, $$$0\le z<2^{30}$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$,$$$a_2$$$,$$$\ldots$$$,$$$a_n$$$ ($$$0\le a_i<2^{30}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case, print one integer — the answer to the problem.

NoteIn the first test case of the sample, one optimal sequence of operations is:  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(3\operatorname{or}3)=3$$$ and $$$z$$$ becomes $$$(3\operatorname{and}3)=3$$$.  Do the operation with $$$i=2$$$. Now $$$a_2$$$ becomes $$$(4\operatorname{or}3)=7$$$ and $$$z$$$ becomes $$$(4\operatorname{and}3)=0$$$.  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(3\operatorname{or}0)=3$$$ and $$$z$$$ becomes $$$(3\operatorname{and}0)=0$$$. After these operations, the sequence $$$a$$$ becomes $$$[3,7]$$$, and the maximum value in it is $$$7$$$. We can prove that the maximum value in $$$a$$$ can never exceed $$$7$$$, so the answer is $$$7$$$.In the fourth test case of the sample, one optimal sequence of operations is:  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(7\operatorname{or}7)=7$$$ and $$$z$$$ becomes $$$(7\operatorname{and}7)=7$$$.  Do the operation with $$$i=3$$$. Now $$$a_3$$$ becomes $$$(30\operatorname{or}7)=31$$$ and $$$z$$$ becomes $$$(30\operatorname{and}7)=6$$$.  Do the operation with $$$i=5$$$. Now $$$a_5$$$ becomes $$$(27\operatorname{or}6)=31$$$ and $$$z$$$ becomes $$$(27\operatorname{and}6)=2$$$.

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      var cou = 0
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val z = tokenizer.nextToken().toInt
      val A = new Array[Long](n)
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 0 until n) {
        A(i) = (tokenizer.nextToken().toInt | z)
      }
      println(A.max)
    }
  }
}


A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.Determine if it is possible for the islanders to arrange the statues in the desired order.

The first line contains a single integer n (2 ≤ n ≤ 200 000) — the total number of islands. The second line contains n space-separated integers ai (0 ≤ ai ≤ n - 1) — the statue currently placed on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≤ bi ≤ n - 1) — the desired statues of the ith island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct.

Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise.

NoteIn the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.In the second sample, the islanders can simply move statue 1 from island 1 to island 2.In the third sample, no sequence of movements results in the desired position.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt - 1
  val data = in.next().split(' ').map(_.toInt).filter(_ > 0)
  val data1 = in.next().split(' ').map(_.toInt).filter(_ > 0)
  val index = data1.indexOf(data.head)
  if (data.take(n - index).mkString(" ") == data1.drop(index).mkString(" ") &&
      data.drop(n - index).mkString(" ") == data1.take(index).mkString(" "))
    println("YES")
  else
    println("NO")
}

/**
  * Created by octavian on 28/02/2016.
  */
object Island {

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

    //System.setIn(new FileInputStream("./src/island.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/island.out")))

    var n = readInt()
    var a = readLine.split(" ").map(_.toInt).filter(_ != 0)
    var b = readLine.split(" ").map(_.toInt).filter(_ != 0)

    if(a.length != n - 1 || b.length != n - 1) {
      println("NO")
    }
    else {
      println(checkRotation(a, b, n))
    }
  }

  def checkRotation(a: Array[Int], b: Array[Int], n: Int): String = {
    val pos = posFirstElem(a(0), b)
    //println("pos is: " + pos)
    for(i <- 0 until n - 1) {
      //println("pos + i mod n: " + ((pos + i)%(n-1)))
      if(a(i) != b((pos + i)%(n - 1))) {
        return "NO"
      }
    }
    return "YES"
  }

  def posFirstElem(a0: Int, b: Array[Int]): Int = {
    for(i <- 0 until b.length) {
      if(a0 == b(i)) {
        return i
      }
    }
    return 0
  }

}

import java.util

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n).filter(_ != 0)
  val bs = readInts(n).filter(_ != 0)

  val ai = as.indexWhere(_ == 1)
  val bi = bs.indexWhere(_ == 1)

  val a2 = as.drop(ai) ++ as.take(ai)
  val b2 = bs.drop(bi) ++ bs.take(bi)

  val res = util.Arrays.equals(a2, b2)
  //println(a2.mkString(" "))
  //println(b2.mkString(" "))

  println(if (res) "YES" else "NO")
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _635B extends CodeForcesApp {
  override type Result = Boolean

  override def solve(read: InputReader) = {
    val n = read[Int]
    val a, b = read[IndexedSeq, Int](n).filter(_ != 0)
    (a ++: a) containsSlice b
  }

  override def format(result: Result) = if (result) "YES" else "NO"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _635B extends CodeForcesApp {
  override type Result = Boolean

  override def solve(read: InputReader) = {
    val n = read[Int]
    val a = read[IndexedSeq, Int](n).filter(_ != 0)
    val b = read[IndexedSeq, Int](n).filter(_ != 0)
    (a ++: a) containsSlice b
  }

  override def format(result: Result) = if (result) "YES" else "NO"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).filter(_ > 0)
  val data1 = in.next().split(' ').map(_.toInt).filter(_ > 0)
  val index = data1.indexOf(data.head)
  println(index)
  if (data.take(n - index).mkString(" ") == data1.drop(index).mkString(" ") &&
      data.drop(n - index).mkString(" ") == data1.take(index).mkString(" "))
    println("YES")
  else
    println("NO")
}


Kolya got an integer array $$$a_1, a_2, \dots, a_n$$$. The array can contain both positive and negative integers, but Kolya doesn't like $$$0$$$, so the array doesn't contain any zeros.Kolya doesn't like that the sum of some subsegments of his array can be $$$0$$$. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum $$$0$$$. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, $$$0$$$, any by absolute value, even such a huge that they can't be represented in most standard programming languages).Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of elements in Kolya's array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^{9} \le a_i \le 10^{9}, a_i \neq 0$$$) — the description of Kolya's array.

Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.

NoteConsider the first example. There is only one subsegment with the sum $$$0$$$. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer $$$1$$$ between second and third elements of the array.There are no subsegments having sum $$$0$$$ in the second example so you don't need to do anything.

//package codeforces.contests._1426

object NonZeroSegments {

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val arr = io.StdIn.readLine.split(" ").map(_.toLong)

    val prefix = arr.scanLeft(0L)(_ + _)
    val groups = collection.mutable.Map((0 to n).groupBy(prefix).toSeq: _*)
    val result = {
      (1 to n).foldLeft((0, 0)) { case ((acc, lastIndex), i) =>

        val sum = prefix(i)
        val indices = groups.getOrElse(sum, IndexedSeq.empty)

        val x = lastIndex - 1
        val y = i - 1

        @scala.annotation.tailrec
        def binarySearch(l: Int, r: Int): Boolean = {
          if (l > r) false else {
            val m = (l + r) / 2
            val key = indices(m)
            if (x <= key && key <= y) true
            else if (key < x) binarySearch(m + 1, r)
            else binarySearch(l, m - 1)
          }
        }

        if (binarySearch(0, indices.length - 1))
          (acc + 1, i)
        else
          (acc, lastIndex)

      }._1
    }
    println(result)
  }
}


You are given two strings $$$s$$$ and $$$t$$$, both consisting only of lowercase Latin letters.The substring $$$s[l..r]$$$ is the string which is obtained by taking characters $$$s_l, s_{l + 1}, \dots, s_r$$$ without changing the order.Each of the occurrences of string $$$a$$$ in a string $$$b$$$ is a position $$$i$$$ ($$$1 \le i \le |b| - |a| + 1$$$) such that $$$b[i..i + |a| - 1] = a$$$ ($$$|a|$$$ is the length of string $$$a$$$).You are asked $$$q$$$ queries: for the $$$i$$$-th query you are required to calculate the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.

The first line contains three integer numbers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 10^3$$$, $$$1 \le q \le 10^5$$$) — the length of string $$$s$$$, the length of string $$$t$$$ and the number of queries, respectively. The second line is a string $$$s$$$ ($$$|s| = n$$$), consisting only of lowercase Latin letters. The third line is a string $$$t$$$ ($$$|t| = m$$$), consisting only of lowercase Latin letters. Each of the next $$$q$$$ lines contains two integer numbers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the arguments for the $$$i$$$-th query.

Print $$$q$$$ lines — the $$$i$$$-th line should contain the answer to the $$$i$$$-th query, that is the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.

NoteIn the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively.

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, M, Q = ni()
    val S = ns()
    val T = ns()
    val cum = Array.ofDim[Int](N + 1) // 1-index

    if (N >= M) {
      rep(N - M + 1) { i =>
        cum(i + 1) = cum(i)
        if (S.substring(i, i + M) == T) cum(i + 1) += 1
      }
    }

    rep(Q) { _ =>
      val l, r = ni()
      val ri = r - M + 1
      val li = l - 1
      val ans = if (ri >= li) cum(ri) - cum(li) else 0
      out.println(ans)
    }
  }

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

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

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

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

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

object Main {

  import java.io.{BufferedReader, InputStreamReader}

  val mod = (1e9 + 7).toLong

  var d = new Array[Long](1005)

  var powResult = new Array[Long](1005)

  var answer = new Array[Long](1005)

  var strMod: Long = 0

  /*
  快速幂
   */
  def power(a: Long, b: Int): Long = {
    val ans = if (b == 0) 1 else {
      var res = 1.toLong
      var x = a
      var y = b
      while (y != 0) {
        if ((y & 1) == 1) {
          res *= x
          res %= mod
        }
        x *= x
        x %= mod
        y >>= 1
      }
      res
    }
    ans
  }

  def getPowerResult(): Unit = {
    (0 to 1000).foreach(i => {
      powResult(i) = power(131, i)
    })
  }

  def getHash(str: String): Unit = {
    (0 until str.length).foreach(index => {
      strMod *= 131
      strMod += str.charAt(index).toInt
      strMod %= mod
    })
  }

  def getMoroHashSum(str: String): Unit = {
    d(0) = 0.toLong
    (0 until str.length).foreach(i => {
      d(i + 1) = (d(i) + powResult(i) * str.charAt(i).toInt % mod) % mod
    })
  }

  def result(x: Int, y: Int, z: Int): Int = {
    var ans = 0
    (x to y - z + 1).foreach(i => {
      val temp1 = (d(i + z - 1) - d(i - 1) + mod) % mod
      val temp2 = (strMod * powResult(i - 1) % mod) % mod
      if (temp1 == temp2) ans += 1
    })
    ans
  }

  def getResultInit(x: Int, y: Int): Unit = {
    (1 to x - y + 1).foreach(i => {
      val temp1 = (d(i + y - 1) - d(i - 1) + mod) % mod
      val temp2 = (strMod * powResult(i - 1) % mod) % mod
      if (temp1 == temp2) answer(i) = answer(i - 1) + 1
      else answer(i) = answer(i - 1)
    })
  }

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val line = br.readLine().split(" ")
    val x = line(0).toInt
    val y = line(1).toInt
    val z = line(2).toInt
    val str1 = br.readLine()
    val str2 = br.readLine()
    getPowerResult()
    getHash(str2.reverse)
    getMoroHashSum(str1)
    getResultInit(x, y)
    var a = 0
    for (a <- 1 to z) {
      val line = br.readLine().split(" ")
      val p = line(0).toInt - 1
      val q = line(1).toInt - y + 1
      if (p > q) println("0")
      else println(answer(q) - answer(p))
    }
    br.close()
  }
}

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

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

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

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

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

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

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

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

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

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

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val m = nextInt
        val q = nextInt
        val start = Array.ofDim[Int](n)
        val end = Array.ofDim[Int](n)
        val s = nextString
        val t = nextString
        var is = 0
        var ie = 0
        var cur_s = 0
        var cur_e = 0

        while(is < n) {
            var idx = s.indexOf(t, is)
            if(idx == -1) idx = n
            while(is < n && is <= idx) {
                if(is == idx) cur_s += 1
                start(is) = cur_s
                is += 1
            }

            while(ie < n && ie < idx + m) {
                if(ie == idx + m - 1) cur_e += 1
                end(ie) = cur_e
                ie += 1
            }
        }

        for(i <- 1 to q) {
            val l = nextInt - 1
            val r = nextInt - 1
            val res = math.max(end(r) - (if(l == 0) 0 else start(l - 1)), 0)
            println(res)
        }
    }

  }

}

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

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

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

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

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

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

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

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

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

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

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val m = nextInt
        val q = nextInt
        val start = Array.ofDim[Int](n)
        val end = Array.ofDim[Int](n)
        val s = nextString
        val t = nextString
        var i = 0
        var cur_s = 0
        var cur_e = 0
        while(i < n) {
            var idx = s.indexOf(t, i)
            if(idx == -1) idx = n
            while(i < n && i < idx + m) {
                if(i == idx) cur_s += 1
                if(i == idx + m - 1) cur_e += 1
                start(i) = cur_s
                end(i) = cur_e
                i += 1
            }
        }

        for(i <- 1 to q) {
            val l = nextInt - 1
            val r = nextInt - 1
            val res = math.max(end(r) - (if(l == 0) 0 else start(l - 1)), 0)
            println(res)
        }
    }

  }

}


Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers $$$a$$$ and $$$b$$$ using the following algorithm:  If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length.  The numbers are processed from right to left (that is, from the least significant digits to the most significant).  In the first step, she adds the last digit of $$$a$$$ to the last digit of $$$b$$$ and writes their sum in the answer.  At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the left side of the answer.  For example, the numbers $$$a = 17236$$$ and $$$b = 3465$$$ Tanya adds up as follows:$$$$$$ \large{ \begin{array}{r} + \begin{array}{r} 17236\\ 03465\\ \end{array} \\ \hline \begin{array}{r} 1106911 \end{array} \end{array}} $$$$$$  calculates the sum of $$$6 + 5 = 11$$$ and writes $$$11$$$ in the answer.  calculates the sum of $$$3 + 6 = 9$$$ and writes the result to the left side of the answer to get $$$911$$$.  calculates the sum of $$$2 + 4 = 6$$$ and writes the result to the left side of the answer to get $$$6911$$$.  calculates the sum of $$$7 + 3 = 10$$$, and writes the result to the left side of the answer to get $$$106911$$$.  calculates the sum of $$$1 + 0 = 1$$$ and writes the result to the left side of the answer and get $$$1106911$$$. As a result, she gets $$$1106911$$$.You are given two positive integers $$$a$$$ and $$$s$$$. Find the number $$$b$$$ such that by adding $$$a$$$ and $$$b$$$ as described above, Tanya will get $$$s$$$. Or determine that no suitable $$$b$$$ exists.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of a single line containing two positive integers $$$a$$$ and $$$s$$$ ($$$1 \le a \lt s \le 10^{18}$$$) separated by a space.

For each test case print the answer on a separate line. If the solution exists, print a single positive integer $$$b$$$. The answer must be written without leading zeros. If multiple answers exist, print any of them. If no suitable number $$$b$$$ exists, output -1.

NoteThe first test case is explained in the main part of the statement.In the third test case, we cannot choose $$$b$$$ that satisfies the problem statement.

object C extends App {
  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val a = nextLong()
    val s = nextLong()

    s.augend(a) match {
      case Some(b) => out.println(b)
      case _       => out.println(-1)
    }
  }

  out.flush()

  implicit final class LongOps(private val sum: Long) extends AnyVal {
    def digits: List[Byte] = sum.toString().split("").map(_.toByte).toList

    def augend(addend: Long): Option[Long] = {

      @annotation.tailrec
      def go(sumDigits: List[Byte], addendDigits: List[Byte], augendDigits: List[Byte]): Option[List[Byte]] =
        (sumDigits, addendDigits) match {
          case (sumHead :: sumTail, addendHead :: addendTail) if addendHead <= sumHead =>
            go(sumTail, addendTail, (sumHead - addendHead).toByte :: augendDigits)
          case (sumFirst :: sumSecond :: sumTail, addendHead :: addendTail)            =>
            val sumHead = sumSecond * 10 + sumFirst
            if (sumHead > 18 || addendHead > sumHead) None
            else go(sumTail, addendTail, (sumHead - addendHead).toByte :: augendDigits)
          case (sumHead :: sumTail, _)                                                 =>
            go(sumTail, addendDigits, sumHead :: augendDigits)
          case _                                                                       =>
            if (addendDigits.isEmpty) Some(augendDigits) else None
        }

      go(sum.digits.reverse, addend.digits.reverse, List.empty[Byte]).map(_.mkString("").toLong)
    }
  }

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

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

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

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

    def nextLine() = in.readLine()

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

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

object C extends App {

  val digits: Long => List[Int] = _.toString().split("").map(_.toInt).reverse.toList

  def wrongAddition(s: Long, a: Long): Option[Long] = {

    @annotation.tailrec
    def go(s: List[Int], a: List[Int], b: List[Int]): Option[List[Int]] = (s, a) match {
      case (shead :: stail, ahead :: atail) if ahead <= shead => go(stail, atail, (shead - ahead) :: b)
      case (sfirst :: ssecond :: stail, ahead :: atail)       =>
        val shead = ssecond * 10 + sfirst
        if (shead > 18 || ahead > shead) None else go(stail, atail, (shead - ahead) :: b)
      case (shead :: stail, Nil)                              => go(stail, a, shead :: b)
      case (Nil, Nil)                                         => Some(b)
      case _                                                  => None
    }

    go(digits(s), digits(a), List.empty[Int]).map(_.mkString("").toLong)
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val a = nextLong()
    val s = nextLong()

    wrongAddition(s, a) match {
      case Some(b) => out.println(b)
      case _       => out.println(-1)
    }
  }

  out.flush()

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

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

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

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

    def nextLine() = in.readLine()

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

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


You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.For the i-th query find any position pi (li ≤ pi ≤ ri) so that api ≠ xi.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the number of elements in a and the number of queries. The second line contains n integers ai (1 ≤ ai ≤ 106) — the elements of the array a. Each of the next m lines contains three integers li, ri, xi (1 ≤ li ≤ ri ≤ n, 1 ≤ xi ≤ 106) — the parameters of the i-th query.

Print m lines. On the i-th line print integer pi — the position of any number not equal to xi in segment [li, ri] or the value  - 1 if there is no such number.

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

object ER_7_C {

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

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

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

    val line2 = readLine
    val arr = new Array[Int](n + 1)
    for (i <- 1 to n) {
      arr(i) = line2.int
    }
    val arrNext = new Array[Int](n + 1)
    var next = n + 1
    var nextVal = arr(n)
    for (i <- n to 1 by -1) {
      if (nextVal != arr(i)) {
        next = i + 1
        nextVal = arr(i)
      }
      arrNext(i) = next
    }
//    db(arrNext.mkString(","))

    val result = new StringBuilder()

    for (i <- 1 to m) {
      val qqLine = readLine()
      val l = qqLine.int
      val r = qqLine.int
      val x = qqLine.int
      if (arr(l) != x) {
        printRes(l)
      } else {
        val next = arrNext(l)
        if (next > n || next > r) {
          printRes(-1)
        } else {
          printRes(next)
        }
      }
    }

    def printRes(r:Int) = {
      result.append(r + "\n")
     //println(r)
    }
    println(result.toString())

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

  }

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

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

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

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

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

def big() = {
  val n = 200000
  val m = 200000
  val res = new StringBuilder(n + " " + m + "\n");
  for (i <- 0 to n) {
    res.append("1 ")
  }
  res.append("\n")
  for (i <- 0 to m) {
    res.append("1 200000 1\n")
  }
  res.toString()
}

}

}


Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).

The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 1000). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 1000) — the number of students. Then n lines follow. Each line contains two integer li, ri (1 ≤ li ≤ ri ≤ 5000) — the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea. It is guaranteed that for every  condition li - 1 ≤ li holds. The sum of n over all test cases doesn't exceed 1000. Note that in hacks you have to set t = 1.

For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.

NoteThe example contains 2 tests:  During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second.  During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea.

object CF920B extends App{
  val sc = new java.util.Scanner(System.in)
  val t = sc.nextInt
  tea(t)
  def tea(tt: Int): Unit ={
    val n = sc.nextInt
    val lr = Seq.fill[(Int, Int)](n)(sc.nextInt, sc.nextInt)
    println(teapod(lr, 1, Seq.empty) mkString " ")
    if(tt != 1) tea(tt-1)
  }

  def teapod(lr: Seq[(Int,Int)], time: Int, result:Seq[Int] ): Seq[Int] = {
    val (l,r) = lr.head
    //println(l, r, time, (if (time > r) 0 else if (time < l) l else time))
    val newtime =  (if (time > r) 0 else Math.max(l, time))
    val newresult = result :+ newtime
    if(lr.length == 1) return newresult else teapod(lr.tail, if(newtime==0) time else newtime + 1, newresult)
  }
}

object CF920B extends App{
  val sc = new java.util.Scanner(System.in)
  val t = sc.nextInt
  tea(t)
  def tea(tt: Int): Unit ={
    val n = sc.nextInt
    val lr = Seq.fill[(Int, Int)](n)(sc.nextInt, sc.nextInt)
    println(teapod(lr, 1, Seq.empty) mkString " ")
    if(tt != 1) tea(tt-1)
  }

  def teapod(lr: Seq[(Int,Int)], time: Int, result:Seq[Int] ): Seq[Int] = {
    val (l,r) = lr.head
    //println(l, r, time, (if (time >= r) 0 else if (time < l) l else time))
    val newtime =  (if (time >= r) 0 else Math.max(l, time))
    val newresult = result :+ newtime
    if(lr.length == 1) return newresult else teapod(lr.tail, newtime + 1, newresult)
  }
}

object CF920B extends App{
  val sc = new java.util.Scanner(System.in)
  val t = sc.nextInt
  tea(t)
  def tea(tt: Int): Unit ={
    val n = sc.nextInt
    val lr = Seq.fill[(Int, Int)](n)(sc.nextInt, sc.nextInt)
    println(teapod(lr, 1, Seq.empty) mkString " ")
    if(tt != 1) tea(tt-1)
  }

  def teapod(lr: Seq[(Int,Int)], time: Int, result:Seq[Int] ): Seq[Int] = {
    val (l,r) = lr.head
    //println(l, r, time, (if (time >= r) 0 else if (time < l) l else time))
    val newtime =  (if (time > r) 0 else Math.max(l, time))
    val newresult = result :+ newtime
    if(lr.length == 1) return newresult else teapod(lr.tail, newtime + 1, newresult)
  }
}