Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:   the graph contains exactly 2n + p edges;  the graph doesn't contain self-loops and multiple edges;  for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices.

The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; ) — the number of vertices in the graph and the interest value for the appropriate test.  It is guaranteed that the required graph exists.

For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.  Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object A extends App {

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

  val t = readInt

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

  for (test <- 1 to t) {
    val Array(n, p) = readInts(2)
    var c = 2 * n + p
    var step = 1
    while (c > 0) {
      var u = 0
      while (u < n && c > 0) {
        val v = (u + step) % n
        println(s"${u + 1} ${v + 1}")
        u += 1
        c -= 1
      }
      step += 1
    }
  }

  Console.flush
}


Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him оf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.

The first line contains four integers k, x, n, m (3 ≤ k ≤ 50; 0 ≤ x ≤ 109; 1 ≤ n, m ≤ 100).

In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them. If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val List(k0, x0, n0, m0) = input.next().split(" ").toList
    val k = k0.toInt
    val x = x0.toLong
    val n = n0.toInt
    val m = m0.toInt
    val res = new Array[Long](k)
    for (sc0 <- List(true, false))
      for (sc1 <- List(true, false))
        for (ea0 <- List(true, false))
          for (ea1 <- List(true, false)) {
            if (n > 1 || !(sc0 && ea0))
              if (m > 1 || !(sc1 && ea1)) {
                def calmax(sc: Boolean, ea: Boolean, len: Int) = {
                  var a = len
                  if (sc) a-= 1
                  if (ea) a-= 1
                  a.max(0) / 2
                }
                val acn0max = calmax(sc0, ea0, n)
                val acn1max = calmax(sc1, ea1, m)
                for (acn0 <- 0 to acn0max)
                  for (acn1 <- 0 to acn1max) {
                    res(0) = acn0
                    res(1) = acn1
                    for (n <- 2 until res.length) {
                      res(n) = (if ((if (n == 2) ea0 else ea1) && (if (n % 2 == 0) sc1 else sc0)) 1 else 0) + res(n-1) + res(n-2)
                    }
                    if (res.last == x) {
                      val s0 =
                          (if (sc0) "C" else "") + (0 until acn0).map(_ => "AC").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => "X").mkString + (if (ea0) "A" else "")
                      val s1 =
                          (if (sc1) "C" else "") + (0 until acn1).map(_ => "AC").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => "X").mkString + (if (ea1) "A" else "")
                      println(s0)
                      println(s1)
                      System.exit(0)
                    }
                  }
              }
          }
    print("Happy new year!")
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val List(k, x, n, m) = input.next().split(" ").map(_.toInt).toList
    /*

    val sc "start with c" = Array[Boolean](k)
    val ea "end with a" = Array[Boolean](k)

    val acn "ac number" = Array[Int](k)

    acn[n] = [sc[n-1] && ea[n-2]] + acn[n-1] + acn[n-2]
    sc[n] = sc[n-2] = n % 2 == 0 ? sc[2] else sc[1]
    ea[n] = ea[n-1] = ... ea[2] | if n == 1 ea[1]

    if (sc[1] && sc[2] && ea[2] && ea[1])
      acn[n] = 1 + acn[n-1] + acn[n-2]

      n + a n-1 = c(n-1 + a n-2)
      n a-c -ac
      1 -1 -1

      I do not think it will work...
     */
    val res = new Array[Int](k)
    // sc1 sc2 ea2 ea1
    for (sc0 <- List(true, false))
      for (sc1 <- List(true, false))
        for (ea0 <- List(true, false))
          for (ea1 <- List(true, false)) {
            if (n > 1 || !(sc0 && ea0))
              if (m > 1 || !(sc1 && ea1)) {
                def calmax(sc: Boolean, ea: Boolean, len: Int) = {
                  var a = len
                  if (sc) a-= 1
                  if (ea) a-= 1
                  a.max(0) / 2
                }
                val acn0max = calmax(sc0, ea0, n)
                val acn1max = calmax(sc1, ea1, m)
                for (acn0 <- 0 to acn0max)
                  for (acn1 <- 0 to acn1max) {
                    res(0) = acn0
                    res(1) = acn1
                    for (n <- 2 until res.length) {
                      // what is () + + !!!
                      res(n) = (if ((if (n == 2) ea0 else ea1) && (if (n % 2 == 0) sc0 else sc1)) 1 else 0) + res(n-1) + res(n-2)
                    }
                    if (res.last == x) {
                      val s0 =
                          (if (sc0) "C" else "") + (0 until acn0).map(_ => "AC").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => "X").mkString + (if (ea0) "A" else "")
                      val s1 =
                          (if (sc1) "C" else "") + (0 until acn1).map(_ => "AC").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => "X").mkString + (if (ea1) "A" else "")
                      println(s0)
                      println(s1)
                      System.exit(0)
                    }
                  }
              }
          }
    print("Happy new year!")
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val List(k, x, n, m) = input.next().split(" ").map(_.toInt).toList
    /*

    val sc "start with c" = Array[Boolean](k)
    val ea "end with a" = Array[Boolean](k)

    val acn "ac number" = Array[Int](k)

    acn[n] = [sc[n-1] && ea[n-2]] + acn[n-1] + acn[n-2]
    sc[n] = sc[n-2] = n % 2 == 0 ? sc[2] else sc[1]
    ea[n] = ea[n-1] = ... ea[2] | if n == 1 ea[1]

    if (sc[1] && sc[2] && ea[2] && ea[1])
      acn[n] = 1 + acn[n-1] + acn[n-2]

      n + a n-1 = c(n-1 + a n-2)
      n a-c -ac
      1 -1 -1

      I do not think it will work...
     */
    val res = new Array[Int](k)
    // sc1 sc2 ea2 ea1
    for (sc0 <- List(true, false))
      for (sc1 <- List(true, false))
        for (ea0 <- List(true, false))
          for (ea1 <- List(true, false)) {
            if (n > 1 || !(sc0 && ea0))
              if (m > 1 || !(sc1 && ea1)) {
                def calmax(sc: Boolean, ea: Boolean, len: Int) = {
                  var a = len
                  if (sc) a-= 1
                  if (ea) a-= 1
                  a.max(0) / 2
                }
                val acn0max = calmax(sc0, ea0, n)
                val acn1max = calmax(sc1, ea1, m)
                for (acn0 <- 0 to acn0max)
                  for (acn1 <- 0 to acn1max) {
                    res(0) = acn0
                    res(1) = acn1
                    for (n <- 2 until res.length) {
                      // what is () + + !!!
                      res(n) = (if ((if (n == 2) ea0 else ea1) && (if (n % 2 == 0) sc1 else sc0)) 1 else 0) + res(n-1) + res(n-2)
                    }
                    if (res.last == x) {
                      val s0 =
                          (if (sc0) "C" else "") + (0 until acn0).map(_ => "AC").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => "X").mkString + (if (ea0) "A" else "")
                      val s1 =
                          (if (sc1) "C" else "") + (0 until acn1).map(_ => "AC").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => "X").mkString + (if (ea1) "A" else "")
                      println(s0)
                      println(s1)
                      System.exit(0)
                    }
                  }
              }
          }
    print("Happy new year!")
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val List(k, x, n, m) = input.next().split(" ").map(_.toInt).toList
    /*

    val sc "start with c" = Array[Boolean](k)
    val ea "end with a" = Array[Boolean](k)

    val acn "ac number" = Array[Int](k)

    acn[n] = [sc[n-1] && ea[n-2]] + acn[n-1] + acn[n-2]
    sc[n] = sc[n-2] = n % 2 == 0 ? sc[2] else sc[1]
    ea[n] = ea[n-1] = ... ea[2] | if n == 1 ea[1]

    if (sc[1] && sc[2] && ea[2] && ea[1])
      acn[n] = 1 + acn[n-1] + acn[n-2]

      n + a n-1 = c(n-1 + a n-2)
      n a-c -ac
      1 -1 -1

      I do not think it will work...
     */
    val res = new Array[Int](k)
    // sc1 sc2 ea2 ea1
    for (sc0 <- List(true, false))
      for (sc1 <- List(true, false))
        for (ea0 <- List(true, false))
          for (ea1 <- List(true, false)) {
            if (n > 1 || !(sc0 && ea0))
              if (m > 1 || !(sc1 && ea1)) {
                def calmax(sc: Boolean, ea: Boolean, len: Int) = {
                  var a = len
                  if (sc) a-= 1
                  if (ea) a-= 1
                  a.max(0) / 2
                }
                val acn0max = calmax(sc0, ea0, n)
                val acn1max = calmax(sc1, ea1, m)
                for (acn0 <- 0 to acn0max)
                  for (acn1 <- 0 to acn1max) {
                    res(0) = acn0
                    res(1) = acn1
                    for (n <- 2 until res.length) {
                      // what is () + + !!!
                      res(n) = (if (ea1 && (if (n % 2 == 0) sc1 else sc0)) 1 else 0) + res(n-1) + res(n-2)
                    }
                    if (res.last == x) {
                      val s0 =
                          (if (sc0) "C" else "") + (0 until acn0).map(_ => "AC").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => "X").mkString + (if (ea0) "A" else "")
                      val s1 =
                          (if (sc1) "C" else "") + (0 until acn1).map(_ => "AC").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => "X").mkString + (if (ea1) "A" else "")
                      println(s0)
                      println(s1)
                      System.exit(0)
                    }
                  }
              }
          }
    print("Happy new year!")
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val List(k, x, n, m) = input.next().split(" ").map(_.toInt).toList
    /*

    val sc "start with c" = Array[Boolean](k)
    val ea "end with a" = Array[Boolean](k)

    val acn "ac number" = Array[Int](k)

    acn[n] = [sc[n-1] && ea[n-2]] + acn[n-1] + acn[n-2]
    sc[n] = sc[n-2] = n % 2 == 0 ? sc[2] else sc[1]
    ea[n] = ea[n-1] = ... ea[2] | if n == 1 ea[1]

    if (sc[1] && sc[2] && ea[2] && ea[1])
      acn[n] = 1 + acn[n-1] + acn[n-2]

      n + a n-1 = c(n-1 + a n-2)
      n a-c -ac
      1 -1 -1

      I do not think it will work...
     */
    val res = new Array[Int](k)
    // sc1 sc2 ea2 ea1
    for (sc0 <- List(true, false))
      for (sc1 <- List(true, false))
        for (ea0 <- List(true, false))
          for (ea1 <- List(true, false)) {
            if (n > 1 || !(sc0 && ea0))
              if (m > 1 || !(sc1 && ea1)) {
                def calmax(sc: Boolean, ea: Boolean, len: Int) = {
                  var a = len
                  if (sc) a-= 1
                  if (ea) a-= 1
                  a.max(0) / 2
                }
                val acn0max = calmax(sc0, ea0, n)
                val acn1max = calmax(sc1, ea1, m)
                for (acn0 <- 0 to acn0max)
                  for (acn1 <- 0 to acn1max) {
                    res(0) = acn0
                    res(1) = acn1
                    for (n <- 2 until res.length) {
                      // what is () + + !!!
                      res(n) = (if (ea1 && (if (n % 2 == 0) sc0 else sc1)) 1 else 0) + res(n-1) + res(n-2)
                    }
                    if (res.last == x) {
                      val s0 =
                          (if (sc0) "C" else "") + (0 until acn0).map(_ => "AC").mkString + (0 until (n - (if (sc0) 1 else 0) - (if (ea0) 1 else 0) - acn0 * 2)).map(_ => "X").mkString + (if (ea0) "A" else "")
                      val s1 =
                          (if (sc1) "C" else "") + (0 until acn1).map(_ => "AC").mkString + (0 until (m - (if (sc1) 1 else 0) - (if (ea1) 1 else 0) - acn1 * 2)).map(_ => "X").mkString + (if (ea1) "A" else "")
                      println(s0)
                      println(s1)
                      System.exit(0)
                    }
                  }
              }
          }
    print("Happy new year!")
  }
}


CQXYM wants to create a connected undirected graph with $$$n$$$ nodes and $$$m$$$ edges, and the diameter of the graph must be strictly less than $$$k-1$$$. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most one edge).The diameter of a graph is the maximum distance between any two nodes.The distance between two nodes is the minimum number of the edges on the path which endpoints are the two nodes.CQXYM wonders whether it is possible to create such a graph.

The input consists of multiple test cases.  The first line contains an integer $$$t (1 \leq t \leq 10^5)$$$ — the number of test cases. The description of the test cases follows. Only one line of each test case contains three integers $$$n(1 \leq n \leq 10^9)$$$, $$$m$$$, $$$k$$$ $$$(0 \leq m,k \leq 10^9)$$$.

For each test case, print YES if it is possible to create the graph, or print NO if it is impossible. You can print each letter in any case (upper or lower).

NoteIn the first test case, the graph's diameter equal to 0.In the second test case, the graph's diameter can only be 2.In the third test case, the graph's diameter can only be 1.

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

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

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

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        val k = readInt()-2
        val edges = n.toLong*(n.toLong-1L)/2L
        if (m > edges || m < n-1)
            writer.println("NO")
        else if ((k == 0 && n > 1) || (k == 1 && m != edges) || (k < 0))
            writer.println("NO")
        else
            writer.println("YES")
    }
    writer.flush()
}


You are given three positive integers $$$n$$$, $$$a$$$ and $$$b$$$. You have to construct a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters such that each substring of length $$$a$$$ has exactly $$$b$$$ distinct letters. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.Recall that the substring $$$s[l \dots r]$$$ is the string $$$s_l, s_{l+1}, \dots, s_{r}$$$ and its length is $$$r - l + 1$$$. In this problem you are only interested in substrings of length $$$a$$$.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains three space-separated integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le a \le n \le 2000, 1 \le b \le \min(26, a)$$$), where $$$n$$$ is the length of the required string, $$$a$$$ is the length of a substring and $$$b$$$ is the required number of distinct letters in each substring of length $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each test case, print the answer — such a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters that each substring of length $$$a$$$ has exactly $$$b$$$ distinct letters. If there are multiple valid answers, print any of them. It is guaranteed that the answer exists.

NoteIn the first test case of the example, consider all the substrings of length $$$5$$$:  "tleel": it contains $$$3$$$ distinct (unique) letters,  "leelt": it contains $$$3$$$ distinct (unique) letters,  "eelte": it contains $$$3$$$ distinct (unique) letters.

import scala.io.StdIn

object Solution_B extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val input = StdIn.readLine().split(" ").map{_.toInt}
    val N = input(0)
    val A = input(1)
    val B = input(2)
    val result = new StringBuilder()
    val pattern = Array.fill[Char](A)('a')
    for (c <- A - B + 1 until A) {
      pattern(c) = (pattern(c - 1) + 1).toChar
    }
    var offset = 0
    for (c <- 0 until N) {
      result.append(pattern(offset))
      offset += 1
      offset %= A
    }
    println(result.toString())
  }
}

object Main extends App {
  import scala.io.StdIn._
  val t = readInt
  val alphabets = ('a' to 'z').mkString
  for(_ <- 0 until t) {
    val Array(n, a, b) = readLine.trim.split(' ').map(_.toInt)
    println(((alphabets.take(b) + "a" * (a - b)) * ((n + a - 1) / a)).take(n))
  }
}

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

  (0 until t).foreach { _ =>
    val Array(n, _, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val s = (('a' to 'z').take(b).mkString("") * (1 + n / b)).take(n)

    println(s)
  }
}

object B extends App {
  case class Sub(n: Int, a: Int, b: Int)

  private def construct(s: Sub): String =
    (Range('a', 'z' + 1).take(s.b).map(_.toChar).mkString("") * (1 + s.n / s.b))
      .take(s.n)

  val t = scala.io.StdIn.readInt()

  val input = (0 until t)
    .foldLeft(List.empty[Sub]) { (acc, _) =>
      val Array(n, a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      Sub(n, a, b) :: acc
    }
    .reverse

  val output = input.map(construct)

  output.foreach(println)
}

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

  (0 until t).foreach { _ =>
    val Array(n, _, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val s = (0 until n).map(i => ('a' + i % b).toChar).mkString("")

    println(s)
  }
}

object B extends App {
  case class Sub(n: Int, a: Int, b: Int)

  private def construct(s: Sub): String =
    (Range('a', 'z').take(s.b).map(_.toChar).mkString("") * (s.n / s.b + 1))
      .take(s.n)

  val t = scala.io.StdIn.readInt()

  val input = (0 until t)
    .foldLeft(List.empty[Sub]) { (acc, _) =>
      val Array(n, a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      Sub(n, a, b) :: acc
    }
    .reverse

  val output = input.map(construct)

  output.foreach(println)
}


Learn, learn and learn again — Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of n numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by  - 1. The second operation is to take some suffix and multiply all numbers in it by  - 1. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations?

The first line contains integer n (1 ≤ n ≤ 105) — amount of elements in the sequence. The second line contains n integers ai ( - 104 ≤ ai ≤ 104) — the sequence itself.

The first and the only line of the output should contain the answer to the problem.

object P033C extends App {
  val n = readInt
  val a = readLine.split(' ').map(_.toInt)
  val f = (a: Array[Int]) => a.map(-_*2).scan(0)(_+_).scan(0)(math.max(_,_)).drop(1)
  val pb = f(a)
  val sb = f(a.reverse).reverse
  println(a.fold(0)(_+_) + pb.zip(sb).map(x => x._1+x._2).max)
}


Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors. Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.

First line of input consists of one integer n (1 ≤ n ≤ 3000). Next line consists of n integers ai (1 ≤ ai ≤ n), which stand for coolness factor of each badge.

Output single integer — minimum amount of coins the colonel has to pay.

NoteIn first sample test we can increase factor of first badge by 1.In second sample test we can increase factors of the second and the third badge by 1.

object Main {
  def main(args:Array[String]) {
    val sc = new java.util.Scanner(System.in)
    var pre, ans = 0
    Array.fill(sc.nextInt)(sc.nextInt).sorted.foreach { cur =>
      val up = Seq(cur - pre - 1, 0).min.abs
      ans += up
      pre = cur + up
    }
    println(ans)
  }
}

import java.util.StringTokenizer

object _546B extends App {
  var token = new StringTokenizer("")

  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val cnt = Array.fill(2 * n + 10)(0)
  a.foreach(i => cnt(i) += 1)

  def doit(i: Int, acc: Int): Int = {
//    println(cnt.toList)
    if (i == cnt.length) acc
    else {
      val delta = (cnt(i) - 1) max 0
      cnt(i) -= delta
      if (i + 1 < cnt.length) cnt(i + 1) += delta
      doit(i + 1, acc + delta)
    }
  }

  println(doit(0, 0))
}

import scala.collection.JavaConversions._
import scala.collection.mutable._

object Codeforces546B {
    def main(args: Array[String]) {
        val n = scala.io.StdIn.readLine().toInt
        val ar = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted
        var coins = 0
        for (i <- 1 until n) {
            if (ar(i) <= ar(i-1)) {
                coins += (ar(i-1) + 1 - ar(i))
                ar(i) = ar(i-1) + 1
            }
        }
        println(coins)
    }
}

/**
 * Created by r on 5/23/15.
 */
object badge {
  def main (args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt //最初の整数が読み込まれる
    var ar = new Array[Int](n)
    for (i <- 0 to n-1)
      ar(i) = sc.nextInt
    scala.util.Sorting.quickSort(ar)
    var coin = 0
    var flg = false
    do {
      flg = false
      for (i <- 0 to n-2) {
        if (ar(i) >= ar(i + 1)) {
          ar(i + 1) = ar(i + 1) + 1
          coin = coin + 1
          flg = true
        }
      }
    } while(flg == true)

    println(coin)
  }
}

object R304_SoldierAndBadges extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextLine().toInt
  val a = sc.nextLine().split(" ").map(_.toInt).sorted

  var ans = 0
  var bef = a(0)
  (1 to a.length - 1).foreach { i =>
    var tmp = 0
    while (bef >= a(i) + tmp)  {
      tmp += 1
      ans += 1
    }
    bef = a(i) + tmp
  }
  println(ans)
}

import scala.annotation.tailrec

object _546B extends CodeForcesApp {
  import scala.collection.mutable

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

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

  override def solve(input: Input) = {
    val used = mutable.Set.empty[Int]
    @tailrec
    def f(badges: List[Int], acc: Int): Int = badges match {
      case Nil => acc
      case x :: xs if used contains x =>
        val y = (Stream.from(x+1) find {i => !(used contains i)}).head
        f(y :: xs, (y - x) + acc)
      case x :: xs =>
        used += x
        f(xs, acc)
    }
    f(input, 0)
  }

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

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

object _546B extends CodeForcesApp {
  import scala.collection.mutable

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

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

  override def solve(input: Input) = {
    val used = mutable.Set.empty[Int]

    def f(badges: List[Int]): Int = badges match {
      case Nil => 0
      case (x :: xs) if used contains x =>
        val y = ((x+1 to 10000) find (i => !(used contains i))).get
        used += y
        (y - x) + f(xs)
      case (x :: xs) =>
        used += x
        f(xs)
    }
    f(input)
  }

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

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

object _546B extends CodeForcesApp {
  import scala.collection.mutable

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

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

  override def solve(input: Input) = {
    val used = mutable.Set.empty[Int]

    def f(badges: List[Int]): Int = badges match {
      case Nil => 0
      case x :: xs if used contains x =>
        val y = (Stream.from(x+1) find {i => !(used contains i)}).head
        (y - x) + f(y :: xs)
      case x :: xs =>
        used += x
        f(xs)
    }
    f(input)
  }

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

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

import scala.io.StdIn

object Main {
  val a = Array.fill(6001)(0);
  var r = 0;

  def main(args: Array[String]): Unit = {
    StdIn.readLine(); // ignore
    StdIn.readLine().split(" ").map(Integer.parseInt).foreach(a(_)+=1);

    for(i <- 0 to 6000) {
      if ( a(i) > 1 ) {
        val d = a(i) - 1;
        a(i+1) += d;
        r += d;
      }
    }

    println(r);
  }
}

import scala.io.StdIn
import scala.collection.SeqView

object Main {
  val a = Array.fill(6001)(0);
  var r = 0;

  def main(args: Array[String]): Unit = {
    StdIn.readLine(); // ignore
    StdIn.readLine().split(" ").map(Integer.parseInt).foreach(a(_)+=1);

    for(i <- (0 to 6000).view if (a(i) > 1); d = a(i) - 1) {
      a(i+1) += d;
      r += d;
    }

    println(r);
  }
}

import scala.io.StdIn._

object B extends App {
  readInt()
  val input = readLine().split(" ").map(_.toInt).sorted
  val counter = new Array[Boolean](3000 * 3000 + 1)

  def solve() = {
    var answer = 0
    for (i <- input) {
      if (!counter(i)) counter(i) = true
      else {
        var find = i
        while (counter(find)) {
          answer += 1
          find += 1
        }
        counter(find) = true
      }
    }
    answer
  }

  println(solve())
}

import scala.io.StdIn._

/**
 * Created by przemek on 23.05.15.
 */
object Badges {
  def main(args: Array[String]) = {
    val N = readInt()
    val badges = readLine().split(" ").map(_.toInt).sortWith(_ < _)
    solve(N, badges)
  }

  def solve(N: Int, badges: Array[Int]) {
    var c = 0
    for (i <- 1 to N - 1) {
      if (badges(i) <= badges(i-1)) {
        c += badges(i-1) + 1 - badges(i)
        badges(i) = badges(i-1) + 1
      }
    }
    println(c)
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n =nextInt
    val a=Array.fill(n)(0)
    for(i<-0 until n){a(i)=nextInt}
    scala.util.Sorting.quickSort(a)
    var sum=0
    for(i<-0 until n-1){
      var l=1+i
      while(l<n&& a(l)==a(i)){
        a(l)+=1
        sum+=1
        l+=1
      }

    }
    out.println(sum)
    //code ends here
    out.flush
    out.close
  }
}

import java.util.StringTokenizer

object _546B extends App {
  var token = new StringTokenizer("")

  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val a = (1 to n).map(i => next.toInt)

  def doit(a: List[Int], acc: Int): Int =
    if (a == Nil) acc
    else if (a.count(i => i == a.head) > 1) doit(a.head + 1 :: a.tail, acc + 1)
    else doit(a.tail, acc)

  println(doit(a.toList, 0))
}

import java.util.StringTokenizer

object _546B extends App {
  var token = new StringTokenizer("")

  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).sorted

  def doit(a: List[Int], acc: Int): Int = {
    if (a == Nil) acc
    else if (a.count(i => i == a.head) > 1) doit(a.head + 1 :: a.tail, acc + 1)
    else doit(a.tail, acc)
  }

  println(doit(a.toList, 0))
}

object _546B extends CodeForcesApp {
  import scala.collection.mutable

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

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

  override def solve(input: Input) = {
    def f(badges: List[Int]): Int = badges match {
      case Nil => 0
      case (x :: xs) if xs contains x =>
        val y = ((x+1 to 10000) find (i => !(xs contains i))).get
        (y - x) + f(y :: xs)
      case (x :: xs) => f(xs)
    }
    f(input)
  }

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

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

import scala.io.StdIn

object Main {
  val a = Array.fill(6001)(0);
  var r = 0;

  def main(args: Array[String]): Unit = {
    StdIn.readLine(); // ignore
    StdIn.readLine().split(" ").map(Integer.parseInt).foreach(a(_)+=1);

    for(i <- 0 to 6000 if a(i) > 1) {
      a(i+1) += 1;
      r += 1;
    }

    println(r);
  }
}

import scala.io.StdIn

object Main {
  val a = Array.fill(6001)(0);
  var r = 0;

  def main(args: Array[String]): Unit = {
    StdIn.readLine(); // ignore
    StdIn.readLine().split(" ").map(Integer.parseInt).foreach(a(_)+=1);

    for(i <- 0 to 6000 if a(i) > 1; d = a(i) - 1) {
      a(i+1) += d;
      r += d;
    }

    println(r);
  }
}

import scala.io.StdIn._

/**
 * Created by przemek on 23.05.15.
 */
object Badges {
  def main(args: Array[String]) = {
    val N = readInt()
    val badges = readLine().split(" ").map(_.toInt).sortWith(_ < _)
    println(badges.mkString(" "))
    solve(N, badges)
  }

  def solve(N: Int, badges: Array[Int]) {
    var c = 0
    for (i <- 1 to N - 1) {
      if (badges(i) <= badges(i-1)) {
        c += badges(i-1) + 1 - badges(i)
        badges(i) = badges(i-1) + 1
      }
    }
    println(c)
  }
}

import scala.io.StdIn._

/**
 * Created by przemek on 23.05.15.
 */
object Badges {
  def main(args: Array[String]) = {
    val N = readInt()
    val badges = readLine().split(" ").map(_.toInt).sortWith(_ < _)

    var prev = 0
    var c = 0
    for (i <- 0 to N - 1) {
      if (badges(i) == prev) {
        badges(i) += 1
        c += 1
      }
      prev = badges(i)
    }
    println(c)
  }

}

import scala.io.StdIn._

/**
 * Created by przemek on 23.05.15.
 */
object Badges {
  def main(args: Array[String]) = {
    val N = readInt()
    val badges = readLine().split(" ").map(_.toInt).sortWith(_ < _)

    var prev = 0
    var c = 0
    for (i <- 0 to N - 1) {
      if (badges(i) <= prev) {
        badges(i) = prev +1
        c += badges(i) - prev
      }
      prev = badges(i)
    }
    println(c)
  }

}


SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is  for SmallR while  for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.

Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(a, b, c, d) = in.next().split(' ').map(_.toDouble)
  val ab = a / b
  val cd = c / d * (1 - ab)
  println(ab / (ab + cd))
}

object Main {
  def main(args: Array[String]) {
    val Array(a, b, c, d) = readLine().split(" ").map(_.toDouble)
    val p1 = a / b
    val p2 = c / d
    println(p1 / (1 - (1 - p1) * (1 - p2)))
  }
}

object P312B extends App {
  var str = readLine();
  var data_str = str.split(" ");
  var datas = new Array[Integer](4);
  for (i <- 0 to 3) {
    datas.update(i, data_str(i).toInt);
  }
  var p = Array(1.0 * datas(0) / datas(1),1.0 * datas(2) / datas(3));
  //無限等比数列でした。。
  var answer =p(0)/(1-(1-p(0))*(1-p(1)))
  print(answer);
}

object Main {
  def main(args: Array[String]) {
    val Array(a, b, c, d) = readLine().split(" ").map(_.toInt)
    val p1 = a.toFloat / b.toFloat
    val p2 = c.toFloat / d.toFloat
    println(p1 / (1 - (1 - p1) * (1 - p2)))
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(a, b, c, d) = readLine().split(" ").map(_.toInt)
    val p1 = a.toFloat / b.toFloat
    val p2 = c.toFloat / d.toFloat
    println(p1 / (1 - p1 * p2))
  }
}


Recently, the bear started studying data structures and faced the following problem.You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer to the query li, ri is the sum: , where S(li, ri) is a set of prime numbers from segment [li, ri] (both borders are included in the segment).Help the bear cope with the problem.

The first line contains integer n (1 ≤ n ≤ 106). The second line contains n integers x1, x2, ..., xn (2 ≤ xi ≤ 107). The numbers are not necessarily distinct. The third line contains integer m (1 ≤ m ≤ 50000). Each of the following m lines contains a pair of space-separated integers, li and ri (2 ≤ li ≤ ri ≤ 2·109) — the numbers that characterize the current query.

Print m integers — the answers to the queries on the order the queries appear in the input.

NoteConsider the first sample. Overall, the first sample has 3 queries.  The first query l = 2, r = 11 comes. You need to count f(2) + f(3) + f(5) + f(7) + f(11) = 2 + 1 + 4 + 2 + 0 = 9.  The second query comes l = 3, r = 12. You need to count f(3) + f(5) + f(7) + f(11) = 1 + 4 + 2 + 0 = 7.  The third query comes l = 4, r = 4. As this interval has no prime numbers, then the sum equals 0.

import java.util
import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]) {
    val max = 1e7.toInt
    val cnt, sum = Array.fill(max + 1)(0)
    val (primes, fact) = getPrimes(max)

    val n = readToken().toInt
    for (i <- 0 until n) {
      var x = readToken().toInt
      var prev = -1
      while (x != 1) {
        if (fact(x) != prev) {
          cnt(fact(x)) += 1
          prev = fact(x)
        }
        x /= fact(x)
      }
    }

    (2 to max).foreach(i => sum(i) = sum(i - 1) + cnt(i))

    val m = readToken().toInt
    for (i <- 0 until m) {
      val t = readLine.split(" ").map(_.toInt)
      val l = t(0).min(max + 1)
      val r = t(1).min(max)
      println(sum(r) - sum(l - 1))
    }
  }

  def getPrimes(n: Int): (Array[Int], Array[Int]) = {
    val primes = ArrayBuffer.empty[Int]
    val maxFact = Array.fill(n + 1)(1)

    for (i <- 2 to n; if maxFact(i) == 1) {
      (i to n by i).foreach(maxFact(_) = i)
      primes += i
    }

    (primes.toArray, maxFact)
  }

  var st = new util.StringTokenizer("")

  def readToken() = {
    while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)
    st.nextToken
  }
}

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

object Main {
  def main(args: Array[String]) {
    val max = 1e7.toInt
    val cnt, sum = Array.ofDim[Int](max + 1)
    val (primes, fact) = getPrimes(max)

    val n = readToken().toInt
    for (i <- readLine.split(" ")) {
      var x = i.toInt
      var prev = -1
      while (x != 1) {
        val t = fact(x)
        if (t != prev) {
          cnt(t) += 1
          prev = t
        }
        x /= t
      }
    }

    (2 to max).foreach(i => sum(i) = sum(i - 1) + cnt(i))

    val m = readToken().toInt
    (0 until m).foreach(i => {
      val t = readLine.split(" ").map(_.toInt)
      val l = t(0).min(max + 1)
      val r = t(1).min(max)
      println(sum(r) - sum(l - 1))
    })
  }

  def getPrimes(n: Int): (Array[Int], Array[Int]) = {
    val primes = ArrayBuffer.empty[Int]
    val maxFact = Array.ofDim[Int](n + 1)

    for (i <- 2 to n; if maxFact(i) == 0) {
      (i to n by i).foreach(maxFact(_) = i)
      primes += i
    }

    (primes.toArray, maxFact)
  }

  var st = new util.StringTokenizer("")

  def readToken() = {
    while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)
    st.nextToken
  }
}


Just to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y.  Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.

The first line contains integers n, m and w (1  ≤  n  ≤  1000, , 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.

Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.

NoteIn the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.

object B741 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m, w) = readInts(3)
    val wi = readInts(n)
    val bi = readInts(n)
    val G = {
      val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])
      (1 to m).foreach{ _ =>
        val Array(a, b) = readInts(2).map(_-1)
        _G(a).append(b)
        _G(b).append(a)
      }
      _G.map(_.toArray)
    }
    // All connected groups
    val groups = {
      val _groups = cu.ArrayBuffer.empty[Array[Int]]
      val vis = Array.fill(n)(false)

      def dfs(i: Int): cu.ArrayBuffer[Int] = {
        val ret = cu.ArrayBuffer.empty[Int]
        if (!vis(i)) {
          vis(i) = true

          ret.append(i)
          for (a <- G(i))
            ret.appendAll(dfs(a))
        }
        ret
      }

      for (i <- 0 until n if !vis(i)) {
        val g = dfs(i).toArray
        _groups.append(g)
      }
      _groups
    }
    val gW = groups.map(_.map(wi).sum)
    val gB = groups.map(_.map(bi).sum)
    //knapsack
    val dp = Array.ofDim[Int](groups.length, w+1)
    for(i <- groups.indices; j <- 0 to w)
      dp(i)(j) = -1
    def solve(pos: Int, wLeft: Int): Int = {
      if(pos >= groups.length)
        0
      else if (dp(pos)(wLeft) != -1)
        dp(pos)(wLeft)
      else {
        var res = 0
        for(a <- groups(pos)) {
          if(wi(a) <= wLeft) {
            res = math.max(res, solve(pos+1, wLeft-wi(a)) + bi(a))
          }
        }
        if(gW(pos) <= wLeft) {
          res = math.max(res, solve(pos+1, wLeft-gW(pos)) + gB(pos))
        }
        res = math.max(res, solve(pos+1, wLeft))
        dp(pos)(wLeft) = res
        res
      }
    }
    println(solve(0, w))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B741 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m, w) = readInts(3)
    val wi = readInts(n)
    val bi = readInts(n)
    val G = {
      val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])
      (1 to m).foreach{ _ =>
        val Array(a, b) = readInts(2).map(_-1)
        _G(a).append(b)
        _G(b).append(a)
      }
      _G.map(_.toArray)
    }
    // All connected groups
    val groups = {
      val _groups = cu.ArrayBuffer.empty[Array[Int]]
      val vis = Array.fill(n)(false)

      def dfs(i: Int): cu.ArrayBuffer[Int] = {
        val ret = cu.ArrayBuffer.empty[Int]
        if (!vis(i)) {
          vis(i) = true

          ret.append(i)
          for (a <- G(i))
            ret.appendAll(dfs(a))
        }
        ret
      }

      for (i <- 0 until n if !vis(i)) {
        val g = dfs(i).toArray
        _groups.append(g)
      }
      _groups.map(_.map(i => (wi(i), bi(i)))).map{ arr =>
        arr ++ Array((arr.map(_._1).sum, arr.map(_._2).sum))
      }.toArray
    }
    //knapsack
    val dp = Array.ofDim[Int](groups.length, w+1)
    for(i <- groups.indices; j <- 0 to w)
      dp(i)(j) = -1
    def solve(pos: Int, wLeft: Int): Int = {
      if(pos >= groups.length)
        0
      else if (dp(pos)(wLeft) != -1)
        dp(pos)(wLeft)
      else {
        var res = 0
        res = math.max(res, solve(pos+1, wLeft))
        for((w, b) <- groups(pos)) {
          if(w <= wLeft) {
            res = math.max(res, solve(pos+1, wLeft-w) + b)
          }
        }
        dp(pos)(wLeft) = res
        res
      }
    }
    println(solve(0, w))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B741 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m, w) = readInts(3)
    val wi = readInts(n)
    val bi = readInts(n)
    val G = {
      val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])
      (1 to m).foreach{ _ =>
        val Array(a, b) = readInts(2).map(_-1)
        _G(a).append(b)
        _G(b).append(a)
      }
      _G.map(_.toArray)
    }
    // All connected groups
    val groups = {
      val _groups = cu.ArrayBuffer.empty[Array[Int]]
      val vis = Array.fill(n)(false)

      def dfs(i: Int): cu.ArrayBuffer[Int] = {
        val ret = cu.ArrayBuffer.empty[Int]
        if (!vis(i)) {
          vis(i) = true

          ret.append(i)
          for (a <- G(i))
            ret.appendAll(dfs(a))
        }
        ret
      }

      for (i <- 0 until n if !vis(i)) {
        val g = dfs(i).toArray
        _groups.append(g)
      }
      _groups
    }
    val gW = groups.map(_.map(wi).sum)
    val gB = groups.map(_.map(bi).sum)
    //knapsack
    val dp = Array.ofDim[Int](groups.length, w+1)
    for(i <- groups.indices; j <- 0 to w)
      dp(i)(j) = -1
    def solve(pos: Int, wLeft: Int): Int = {
      if(pos >= groups.length)
        0
      else if (dp(pos)(wLeft) != -1)
        dp(pos)(wLeft)
      else {
        var res = 0
        res = math.max(res, solve(pos+1, wLeft))
        for(a <- groups(pos)) {
          if(wi(a) <= wLeft) {
            res = math.max(res, solve(pos+1, wLeft-wi(a)) + bi(a))
          }
        }
        if(gW(pos) <= wLeft) {
          res = math.max(res, solve(pos+1, wLeft-gW(pos)) + gB(pos))
        }
        dp(pos)(wLeft) = res
        res
      }
    }
    println(solve(0, w))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view):  Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.

The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.

Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.

NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled:   In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher:   In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:

import scala.collection.mutable

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

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

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

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

  def main(args: Array[String]): Unit = {
    val input = scala.io.StdIn.readLine
    val stack = mutable.Stack[Char]()
    for(i <- input.indices) {
      if(stack.nonEmpty && stack.top == input(i)) {
        stack.pop()
      } else {
        stack.push(input(i))
      }
    }
    if(stack.isEmpty) {
      println("Yes")
    } else {
      println("No")
    }
  }
}

object D extends App {

  var prev = ' '
  var cnt = 0

  for (c <- Console.readLine)
    if (cnt == 0) {
      prev = c
      cnt = 1
    } else {
      if (c == prev) cnt -= 1 else cnt += 1
      prev = if (prev == '-') '+' else '-'
    }

  println(if (cnt == 0) "Yes" else "No")
}

import scala.collection._

object D extends App {

  def readString = Console.readLine

  val s = readString

  val st = mutable.Stack[Char]()

  for (c <- s) {
    if (st.nonEmpty && st.head == c) {
      st.pop
    } else {
      st.push(c)
    }
  }

  println(if (st.isEmpty) "Yes" else "No")
}

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val stack = mutable.Stack(line.head)

  line.tail.foreach { i =>
    if (stack.isEmpty)
      stack.push(i)
    else if (stack.top != i) {
      stack.push(i)
    } else {
      stack.pop()
    }
  }

  if (stack.isEmpty)
    println("Yes")
  else
    println("No")

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  if (line.length % 2 == 1 || (0 until line.length / 2).exists(i => line(i) != line(line.length - 1 - i)))
    println("No")
  else
    println("Yes")

}

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val stack = mutable.Stack(line.head)

  line.tail.foreach { i =>
    if (stack.nonEmpty && stack.top != i) {
      val top = stack.pop()
      if (stack.nonEmpty && stack.top == top) {
        while (stack.nonEmpty && stack.top == top) {
          stack.pop()
        }
      } else {
        stack.push(top)
      }
    }
    stack.push(i)
  }

  if (stack.nonEmpty) {
    val top = stack.pop()
    if (stack.nonEmpty && stack.top == top) {
      while (stack.nonEmpty && stack.top == top) {
        stack.pop()
      }
    } else {
      stack.push(top)
    }
  }

  if (stack.isEmpty)
    println("Yes")
  else
    println("No")

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  if (line.length == 1 || (0 until line.length / 2).exists(i => line(i) != line(line.length - 1 - i)))
    println("No")
  else
    println("Yes")

}


For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:  Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.

The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).

If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.

NoteIn the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5 In the second example, g(1) = g(2) = g(3) = 1

object C extends App {

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

  val Array(n, a, b) = readInts(3)

  var aX = 0
  var bX = (n - aX * a) / b
  while (aX * a <= n && aX * a + bX * b != n) {
    aX += 1
    bX = (n - aX * a) / b
  }

  if (aX * a + bX * b != n || bX < 0) println(-1)
  else {

    val as = Array.ofDim[Int](aX * a)
    var offset = 0

    for (aPos <- 0 until aX) {
      as(aPos * a) = a + offset
      var i = 1
      while (i < a) {
        as(aPos * a + i) = i + offset
        i += 1
      }
      offset += a
    }

    val bs = Array.ofDim[Int](bX * b)

    for (bPos <- 0 until bX) {
      bs(bPos * b) = b + offset
      var i = 1
      while (i < b) {
        bs(bPos * b + i) = i + offset
        i += 1
      }
      offset += b
    }

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

    println((as ++ bs).mkString(" "))

    Console.flush
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ ($$$n \ge 3$$$) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array $$$[4, 11, 4, 4]$$$ all numbers except one are equal to $$$4$$$).Print the index of the element that does not equal others. The numbers in the array are numbered from one.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$). It is guaranteed that all the numbers except one in the $$$a$$$ array are the same.

For each test case, output a single integer — the index of the element that is not equal to others.

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

object A1512 {
    def main(args: Array[String]){
        val t = readInt()

        for(i <- 1 to t) {
            val n = readInt()
            var arr = readLine.split(" ").map(_.toInt)
            println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.indexOf(arr.max) + 1
                    else arr.indexOf(arr.min) + 1)
        }
    }
}

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

object CodeForces extends App {
  val t = readLine.toInt
  for( _ <- (1 to t)){
    val n = readLine.toInt
    val list = readLine.split(' ').map(x => x.toInt).toList.zipWithIndex
    val a = list(0)._1
    val b = list(1)._1
    val c = list(2)._1
    val mode = if (a == b) a else (if (a == c) a else b)
    val spy = list.find(x => x._1 != mode)
    println(spy.get._2 + 1)
  }

}

import scala.util.control._
object Main{
    def main(args : Array[String]):Unit = {
        var t = scala.io.StdIn.readInt()
        val outloop = new Breaks;
        val inloop = new Breaks;
        outloop.breakable{
            for (i<-1 to t){
                var n = scala.io.StdIn.readInt()
                var arr = scala.io.StdIn.readLine().split(" ").map(_.toInt)
                inloop.breakable{
                    if ((arr(0)!=arr(1))&&(arr(0)!=arr(2))){
                        println(1)
                    }
                    else if((arr(n-1)!=arr(n-2)) && (arr(n-1)!=arr(n-3))){
                        println(n)
                    }
                    else{
                        for (j<-1 to (n-2)){
                            if((arr(j)!=arr(j-1)) && (arr(j)!=arr(j+1))){
                                println(j+1)
                                inloop.break
                            }
                        }
                    }
                }
            }
        }
    }
}

import scala.:+
import scala.+:
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {
  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val numbers = readInts()
    val (a, b)  = numbers.zipWithIndex.partition { case (value, _) => value == numbers(0)}
    val answer = 1 + (if (a.length == 1) a(0)._2 else b(0)._2)
    println(answer)
  }
}

import scala.io.StdIn

object Main {
  def test(): Unit = {
    val n = StdIn.readLine().toInt
    val arr = StdIn.readLine().split(" ").map(_.toInt).zipWithIndex
    val a = arr(0)
    lazy val b = arr.find { _._1 != a._1 }.toRight()
    if (arr.count(_._1 == a._1) > 1)
      System.out.println(b.getOrElse((0, 0))._2 + 1)
   else
      System.out.println(a._2 + 1)
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().toInt
    (1 to t) foreach {
      _ => test()
    }
  }
}

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

object A1512 {
    def main(args: Array[String]){
        val t = readInt()

        for(i <- 1 to t) {
            val n = readInt()
            var arr = readLine.split(" ").map(_.toInt)
            println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.indexOf(arr.min) + 1
                    else arr.indexOf(arr.max) - 1)
        }
    }
}

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

object A1512 {
    def main(args: Array[String]){
        val t = readInt()

        for(i <- 1 to t) {
            val n = readInt()
            var arr = readLine.split(" ").map(_.toInt)
            println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.min
                    else arr.max)
        }
    }
}

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

object CodeForces extends App {
  val t = readLine.toInt
  for( _ <- (1 to t)){
    val n = readLine.toInt
    val list = readLine.split(' ').map(x => x.toInt).toList.zipWithIndex
    println(list)
    val a = list(0)._1
    val b = list(1)._1
    val c = list(2)._1
    val mode = if (a == b) a else (if (a == c) a else b)
    val spy = list.find(x => x._1 != mode)
    println(spy.get._2 + 1)
  }

}

import scala.io.StdIn.readLine

object CodeForces extends App {
  val t = readLine.toInt
  for( _ <- (1 to t)){
    val n = readLine.toInt
    val list = readLine.split(' ').map(x => x.toInt).toList
    val a = list(0)
    val b = list(1)
    val c = list(2)
    val mode = if (a == b) a else (if (a == c) a else b)
    val spy = list.find(x => x != mode)
    println(spy.get)
  }

}

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

object CodeForces extends App {
  val t = readLine.toInt
  for( _ <- (1 to t)){
    val n = readLine.toInt
    val list = readLine.split(' ').map(x => x.toInt).toList
    val a = list(0)
    val b = list(1)
    val c = list(2)
    val mode = if (a == b) a else c
    val spy = list.find(x => x != mode)
    println(spy.get)
  }

}


We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo 1000000007 (109 + 7).

Input contains several test cases. The first line contains two integers t and k (1 ≤ t, k ≤ 105), where t represents the number of test cases. The next t lines contain two integers ai and bi (1 ≤ ai ≤ bi ≤ 105), describing the i-th test.

Print t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between ai and bi flowers at dinner modulo 1000000007 (109 + 7).

Note  For K = 2 and length 1 Marmot can eat (R).  For K = 2 and length 2 Marmot can eat (RR) and (WW).  For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR).  For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR).

import java.io._
import java.util.Scanner
import scala.language.implicitConversions

object Main{

  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }

  import Lazy._

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val T = sc.nextInt
    val K = sc.nextInt
    val MAXN = 100005
    val MOD: Int = 1000000007

    lazy val DP: Array[Lazy[Int]] = Array.tabulate(MAXN)(x => if (x < K) 1 else (DP(x - K) + DP(x - 1)) % MOD)
    lazy val P: Array[Lazy[Int]] = Array.tabulate(MAXN)(x => if (x == 0) DP(0) else (DP(x) + P(x - 1)) % MOD)

    val ranges = for (i <- 0.until(T)) yield (sc.nextInt, sc.nextInt)
    ranges.map{case (s, e) =>
      {
        val startValue: Int = if (s == 0) 0 else P(s - 1);
        (P(e) - startValue + MOD) % MOD
      }
    }.foreach(println)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Long](maxB + 1)
  val sumCache = Array.ofDim[Long](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = (cache(i - 1) + cache(i - k)) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

object D474 {

  import IO._
  import collection.{mutable => cu}
  val MOD = 1000000007L
  def main(args: Array[String]): Unit = {
    val Array(t, k) = readInts(2)
    val dp = Array(0L) ++ Array.fill(k-1)(1L) ++ Array(2L) ++ Array.fill(100010-k)(0L)
    for(i <- k+1 until 100010) {
      dp(i) = (dp(i-1) + dp(i-k))%MOD
    }
    for(i <- 1 until 100010) {
      dp(i) = (dp(i) + dp(i-1))%MOD
    }
    for(_ <- 1 to t) {
      val Array(a, b) = readInts(2)
      println((dp(b) - dp(a-1) + 2*MOD)%MOD)
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object D {

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

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

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

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

  def solve: Int = {
    val mod = (1e9 + 7).toInt
    val t = nextInt
    val k = nextInt
    val dp = new Array[Int](1e5.toInt + 1)
    dp(0) = 1
    for (i <- 1 until dp.length) {
      if (i == k) {
        dp(i) = 2
      }
      else if (i > k) {
        dp(i) = (dp(i - 1) % mod + dp(i - k) % mod) % mod
      } else {
        dp(i) = 1
      }
    }
    val prefixSum = new Array[Int](1e5.toInt + 1)
    prefixSum(0) = dp(0)
    for (i <- 1 until prefixSum.length) {
      prefixSum(i) = (dp(i) % mod + prefixSum(i - 1) % mod) % mod
    }
    for (i <- 0 until t) {
      val a = nextInt
      val b = nextInt
      out.println((prefixSum(b) - prefixSum(a - 1) + mod) % mod)
    }
    return 1
  }

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

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Long](maxB + 1)
  val sumCache = Array.ofDim[Long](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = (cache(i - 1) + (if (i % k == 0) 2 else 1)) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Long](maxB + 1)
  val sumCache = Array.ofDim[Long](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007 + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Long](maxB + 1)
  val sumCache = Array.ofDim[Long](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Int](maxB + 1)
  val sumCache = Array.ofDim[Int](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007 + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

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

object D {

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

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

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

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

  def solve: Int = {
    val mod = (1e9 + 7).toInt
    val t = nextInt
    val k = nextInt
    val dp = new Array[Int](1e5.toInt + 1)
    dp(0) = 1
    for (i <- 1 until dp.length) {
      if (i == k) {
        dp(i) = 2
      }
      else if (i > k) {
        dp(i) = (dp(i - 1) % mod + dp(i - k) % mod) % mod
      } else {
        dp(i) = 1
      }
    }
    val prefixSum = new Array[Int](1e5.toInt + 1)
    prefixSum(0) = dp(0)
    for (i <- 1 until prefixSum.length) {
      prefixSum(i) = (dp(i) % mod + prefixSum(i - 1) % mod) % mod
    }
    for (i <- 0 until t) {
      val a = nextInt
      val b = nextInt
      out.println((Math.abs(prefixSum(b)) - Math.abs(prefixSum(a - 1))) % mod)
    }
    return 1
  }

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


Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $$$n$$$ flowers and so it looks like a pipe with $$$n$$$ holes. Arkady can only use the water that flows from the first hole.Arkady can block some of the holes, and then pour $$$A$$$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $$$s_1, s_2, \ldots, s_n$$$. In other words, if the sum of sizes of non-blocked holes is $$$S$$$, and the $$$i$$$-th hole is not blocked, $$$\frac{s_i \cdot A}{S}$$$ liters of water will flow out of it.What is the minimum number of holes Arkady should block to make at least $$$B$$$ liters of water flow out of the first hole?

The first line contains three integers $$$n$$$, $$$A$$$, $$$B$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le B \le A \le 10^4$$$) — the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 10^4$$$) — the sizes of the holes.

Print a single integer — the number of holes Arkady should block.

NoteIn the first example Arkady should block at least one hole. After that, $$$\frac{10 \cdot 2}{6} \approx 3.333$$$ liters of water will flow out of the first hole, and that suits Arkady.In the second example even without blocking any hole, $$$\frac{80 \cdot 3}{10} = 24$$$ liters will flow out of the first hole, that is not less than $$$20$$$.In the third example Arkady has to block all holes except the first to make all water flow out of the first hole.

object WateringSystem extends App {
  import scala.collection.mutable.PriorityQueue
  import scala.io.Source

  //val src = Source.fromFile("data.txt")
  val src = Source.stdin
  val lines = src.getLines

  def readLongs(): Array[Long] =  {
    val line = if (lines.hasNext) lines.next else null
    if (line == null) throw new RuntimeException("Premature end of source encountered")
    line.split(" ").map(x => x.toLong)
  }
  def calculate(nHoles: Long, volIn: Long, volOut: Long, holeSizes: Array[Long]): Int = {
    var totalSizes = holeSizes.sum
    val firstHoleSize = holeSizes(0)
    var holeSizeQueue = new PriorityQueue[Long]() ++= holeSizes.tail
    var nplugged = 0
    while (volIn * firstHoleSize < volOut * totalSizes) {
      nplugged = nplugged + 1
      totalSizes = totalSizes - holeSizeQueue.dequeue()
    }
    nplugged
  }
  val Array(nHoles, volIn, volOut) = readLongs()
  val holeSizes = readLongs()
  val nplugged = calculate(nHoles, volIn, volOut, holeSizes)
  println(nplugged)

}