We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types:  Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≤ q < k). The given operation is correct — both subsegments do not touch unexistent elements.  Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result — the value of the corresponding element of array b.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≤ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≤ 109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti — the type of the i-th query (1 ≤ ti ≤ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≤ xi ≤ n) — the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b.

For each second type query print the result on a single line.

/*
E. Копирование данных
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Очень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.

Более формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:

    Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.
    Определить значение в позиции x массива b, то есть найти значение bx.

Для каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.
Входные данные

В первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).

В следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.

Все числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.
Выходные данные

Для каждого запроса второго типа в отдельную строку выведите результат.
Примеры тестов
Входные данные

5 10
1 2 0 -1 3
3 1 5 -2 0
2 5
1 3 3 3
2 5
2 4
2 1
1 2 1 4
2 1
2 4
1 4 2 1
2 2

Выходные данные

0
3
-1
3
2
3
-1
*/
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Stack

object CrocRound1Task5 extends App {

  def solve(a: Array[Long], b: IndexedSeq[Long], actions: Seq[Action]): Seq[Long] = {
    //    val now = System.currentTimeMillis
    val tree = MutableSegmentTree.fromSeq(b)
    //    println("tree built in " + (System.currentTimeMillis - now))
    solve(a, tree, actions)
  }

  def solve(a: Array[Long], tree: MutableSegmentTree[Long], actions: Seq[Action]): Seq[Long] = {
    val toPrint = ArrayBuffer.empty[Long]
    actions foreach (action => action match {
      case c: Copy => tree.updateRange(c.posB - 1, c.posB + c.length - 2)(i => a(i - c.posB + c.posA))
      case Find(p) => toPrint += tree(p - 1)
    })
    toPrint
  }

  val (n, m) = {
    val l = readLine split ' ' map (_.toInt)
    (l(0), l(1))
  }
  val a = readLine split ' ' map (_.toLong)
  val b = readLine split ' ' map (_.toLong)
  val actions: IndexedSeq[Action] = (0 until m) map { _ =>
    val s = readLine split ' ' map (_.toInt)
    if (s(0) == 1) Copy(s(1), s(2), s(3))
    else Find(s(1))
  }
  val res = solve(a, b, actions)
  res foreach (x => println(x))
}

abstract class Action {}

case class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}

case class Find(val pos: Int) extends Action {}

// SegmentTree impl copy-paste
abstract class MutableSegmentTree[T] {
  def range = start to end
  def size = end - start + 1
  def start: Int
  def end: Int

  def apply(i: Int): T
  def left: Option[MutableSegmentTree[T]]
  def right: Option[MutableSegmentTree[T]]
  def updateRange(lb: Int, rb: Int)(f: Int => T): Unit
  def update(f: Int => T): Unit
}

object MutableSegmentTree {

  def fromSeq[T](data: IndexedSeq[T]): MutableSegmentTree[T] = {
    def formTreeRec(nodes: Seq[MutableSegmentTree[T]]): MutableSegmentTree[T] = {
      if (nodes.size == 1) nodes.head
      else {
        // Optimized, doesn't use grouped(2)
        val united = for (i <- 0 until nodes.size by 2) yield {
          if (i == nodes.size - 1) SegNode(nodes(i))
          else SegNode(nodes(i), nodes(i + 1))
        }
        formTreeRec(united)
      }
    }
    val leaves = (0 until data.size) map (i => leaf(i, data(i)))
    formTreeRec(leaves)
  }

  private def leaf[T](i: Int, d: T) = new SegLeaf(i, d)
}

class SegNode[T](val l: MutableSegmentTree[T],
                 val r: Option[MutableSegmentTree[T]],
                 val start: Int,
                 val end: Int,
                 var func: Option[Int => T]) extends MutableSegmentTree[T] {
  def left = Some(l)
  def right = r

  def hasRightBranch = r.isDefined

  def apply(i: Int): T = {
    require(i >= start && i <= end, "index is out of bounds")
    if (func.isDefined) {
      (func.get)(i)
    } else if (i >= l.start && i <= l.end) {
      l(i)
    } else {
      (r.get)(i)
    }
  }

  def updateRange(lb: Int, rb: Int)(f: Int => T): Unit = {
    if (within(start, end, lb, rb)) {
      update(f)
    } else if (intersects(start, end, lb, rb)) {
      // Optimized routine
      if (func.isDefined) {
        val f2 = func.get
        if (!within(l.start, l.end, lb, rb)) l update f2
        r foreach (r =>
          if (!within(r.start, r.end, lb, rb)) r update f2)
      }
      if (intersects(l.start, l.end, lb, rb)) l.updateRange(lb, rb)(f)
      r foreach (r =>
        if (intersects(r.start, r.end, lb, rb)) r.updateRange(lb, rb)(f))
      this.func = None
    }
  }

  def update(f: Int => T): Unit = {
    this.func = Some(f)
  }

  /** Checks whether (start to end) is within (lb to rb) */
  private def within(start: Int, end: Int, lb: Int, rb: Int) = {
    start >= lb && start <= rb && end >= lb && end <= rb
  }

  /** Checks whether (start to end) and (lb to rb) has points in common */
  private def intersects(start: Int, end: Int, lb: Int, rb: Int) = {
    (start >= lb && start <= rb) || (end >= lb && end <= rb) || (lb >= start && lb <= end) || (rb >= start && rb <= end)
  }

  override def equals(that: Any) = that match {
    case that: SegNode[T] => this.start == that.start && this.end == that.end && this.l == that.l && this.r == that.r && this.func == that.func
    case _                => false
  }
  override def hashCode = (start * 7) ^ (end * 13) ^ (l.hashCode * 17) ^ (r.map(_.hashCode).getOrElse(0) * 31)
  override def toString = {
    if (func.isDefined) ((start to end) map func.get) mkString " "
    else if (!r.isDefined) l.toString
    else l.toString + " " + r.get.toString
  }
}

object SegNode {
  def apply[T](l: MutableSegmentTree[T]) = {
    new SegNode(l, None, l.start, l.end, None)
  }

  def apply[T](l: MutableSegmentTree[T],
               r: MutableSegmentTree[T]) = {
    require(r.start == l.end + 1, "Right node range should start immediately after left")
    new SegNode(l, Some(r), l.start, r.end, None)
  }
}

class SegLeaf[T](val index: Int, var data: T) extends MutableSegmentTree[T] {
  override val size = 1

  def start = index
  def end = index
  def left = None
  def right = None

  def apply(i: Int): T = {
    require(i == index, "index is out of bounds")
    data
  }

  def updateRange(from: Int, to: Int)(f: Int => T): Unit = {
    if (index >= from && index <= to) update(f)
  }

  def update(f: Int => T): Unit = {
    data = f(index)
  }

  override def equals(that: Any) = that match {
    case that: SegLeaf[T] => this.index == that.index && this.data == that.data
    case _                => false
  }
  override def hashCode = (index * 17) ^ (data.hashCode * 31)
  override def toString = data.toString
}

import io.Source
import java.io.PrintWriter

object CF292E {

  def solve(in: In, out: PrintWriter) {
    val n, m = in().toInt
    val a = Array.fill(n)(in().toInt)
    val b = Array.fill(n)(in().toInt)
    val size = {
      var k = 1
      while (k < n) {
        k *= 2
      }
      k
    }
    val offset = Array.fill(size + n - 1)(-1)
    def update(n: Int, nl: Int, nr: Int, l: Int, r: Int, v: Int) {
      if (l <= nl && nr <= r) {
        offset(n) = v + nl - l
      } else if (r > nl && nr > l) {
        if (offset(n) != -1) {
          offset(2 * n + 1) = offset(n)
          offset(2 * n + 2) = offset(n) + (nr - nl) / 2
          offset(n) = -1
        }
        val mid = (nl + nr) / 2
        update(2 * n + 1, nl, mid, l, r, v)
        update(2 * n + 2, mid, nr, l, r, v)
      }
    }
    def get(n: Int, nl: Int, nr: Int, i: Int): Int = {
      if (offset(n) != -1) {
        a(offset(n) + (i - nl))
      } else if (nl + 1 == nr) {
        b(i)
      } else {
        val mid = (nl + nr) / 2
        if (i < mid) {
          get(2 * n + 1, nl, mid, i)
        } else {
          get(2 * n + 2, mid, nr, i)
        }
      }
    }
    for (it <- 0 until m) {
      if (in().toInt == 1) {
        val x, y = in().toInt - 1
        val k = in().toInt
        update(0, 0, size, y, y + k, x)
        //out.println(offset.deep)
      } else {
        out.println(get(0, 0, size, in().toInt - 1))
      }
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

/*
E. Копирование данных
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Очень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.

Более формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:

    Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.
    Определить значение в позиции x массива b, то есть найти значение bx.

Для каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.
Входные данные

В первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).

В следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.

Все числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.
Выходные данные

Для каждого запроса второго типа в отдельную строку выведите результат.
Примеры тестов
Входные данные

5 10
1 2 0 -1 3
3 1 5 -2 0
2 5
1 3 3 3
2 5
2 4
2 1
1 2 1 4
2 1
2 4
1 4 2 1
2 2

Выходные данные

0
3
-1
3
2
3
-1
*/
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Stack

object CrocRound1Task5 extends App {

  type Range = ((Int, Int))
  def solve(a: Array[Long], b: Array[Long], actions: Seq[Action]): Seq[Long] = {
    val ranges = Stack.empty[Copy]
    val toPrint = ArrayBuffer.empty[Long]
    actions foreach {
      case c: Copy => ranges push c
      case Find(p) => toPrint += find(a, b, ranges, p)
    }
    toPrint
  }

  def find(a: Array[Long], b: Array[Long], ranges: Seq[Copy], pos: Int): Long = {
    val lastCopy = ranges find (c => pos >= c.posB && pos <= c.posB + c.length)
    if (lastCopy.isDefined) {
      val copy = lastCopy.get
      val shift = pos - copy.posB
      a(copy.posA + shift - 1)
    } else {
      b(pos - 1)
    }
  }

  val (n, m) = {
    val l = readLine split ' ' map (_.toInt)
    (l(0), l(1))
  }
  val a = readLine split ' ' map (_.toLong)
  val b = readLine split ' ' map (_.toLong)
  val actions: Seq[Action] = (0 until m) map { _ =>
    val s = readLine split ' ' map (_.toInt)
    if (s(0) == 1) Copy(s(1), s(2), s(3))
    else Find(s(1))
  }
  val res = solve(a, b, actions)
  res map (x => println(x))
}

abstract class Action {}

case class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}

case class Find(val pos: Int) extends Action {}

/*
E. Копирование данных
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Очень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.

Более формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:

    Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.
    Определить значение в позиции x массива b, то есть найти значение bx.

Для каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.
Входные данные

В первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).

В следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.

Все числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.
Выходные данные

Для каждого запроса второго типа в отдельную строку выведите результат.
Примеры тестов
Входные данные

5 10
1 2 0 -1 3
3 1 5 -2 0
2 5
1 3 3 3
2 5
2 4
2 1
1 2 1 4
2 1
2 4
1 4 2 1
2 2

Выходные данные

0
3
-1
3
2
3
-1
*/
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Stack

object CrocRound1Task5 extends App {

  def solve(a: Array[Long], b: Array[Long], actions: Seq[Action]): Seq[Long] = {
    val tree = SegmentTree.fromSeq(b)
    val ranges = Stack.empty[Copy]
    val toPrint = ArrayBuffer.empty[Long]
    actions.foldLeft(tree)((tree, action) => action match {
      case Copy(pa, pb, len) => tree.updatedRange((pb - 1) until (pb + len - 1), i => a(i - pb + pa))
      case Find(p)           => { toPrint += tree(p - 1); tree }
    })
    toPrint
  }

  val (n, m) = {
    val l = readLine split ' ' map (_.toInt)
    (l(0), l(1))
  }
  val a = readLine split ' ' map (_.toLong)
  val b = readLine split ' ' map (_.toLong)
  val actions: Seq[Action] = (0 until m) map { _ =>
    val s = readLine split ' ' map (_.toInt)
    if (s(0) == 1) Copy(s(1), s(2), s(3))
    else Find(s(1))
  }
  val res = solve(a, b, actions)
  res foreach (x => println(x))
}

abstract class Action {}

case class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}

case class Find(val pos: Int) extends Action {}

// SegmentTree impl copy-paste
abstract class SegmentTree[T] {
  def size: Int
  def range: Range
  def apply(i: Int): T
  def updatedRange(r: Range, f: Int => T): SegmentTree[T]
  def updated(f: Int => T): SegmentTree[T]
}

object SegmentTree {

  def fromSeq[T](data: Seq[T]): SegmentTree[T] = {
    def unite(nodes: Seq[SegmentTree[T]]) = {
      if (nodes.length == 2) SegNode(nodes(0), nodes(1))
      else if (nodes.length == 1) SegNode(nodes(0))
      else throw new RuntimeException("Wrong collections to unite")
    }
    def formTreeRec(nodes: Seq[SegmentTree[T]]): SegmentTree[T] = {
      if (nodes.size == 1) nodes.head
      else {
        val united = (nodes grouped 2) map unite
        formTreeRec(united.toSeq)
      }
    }
    val iData = data.toIndexedSeq
    val leaves = (0 until iData.size) map (i => leaf(i, iData(i)))
    formTreeRec(leaves)
  }

  private def leaf[T](i: Int, d: T) = new SegLeaf(i, d)
}

case class SegNode[T](val left: SegmentTree[T],
                      val right: Option[SegmentTree[T]],
                      val range: Range,
                      val func: Option[Int => T]) extends SegmentTree[T] {
  require(range.step == 1, "non-standard ranges aren't supported")

  def size = range.size

  def hasRightBranch = right.isDefined

  def apply(i: Int): T = {
    require(range contains i, "index is out of bounds")
    if (func.isDefined) {
      (func.get)(i)
    } else if (left.range contains i) {
      left(i)
    } else {
      (right.get)(i)
    }
  }

  def updatedRange(r: Range, f: Int => T): SegmentTree[T] = {
    if (within(range, r)) {
      updated(f)
    } else if (intersects(range, r)) {
      new SegNode(left.updatedRange(r, f), right map (_.updatedRange(r, f)), range, None)
    } else {
      this
    }
  }

  def updated(f: Int => T): SegmentTree[T] = {
    new SegNode(left, right, range, Some(f))
  }

  override def toString = {
    if (!right.isDefined) left.toString
    else left.toString + " " + right.get.toString
  }

  /** Checks whether r1 is within r2 */
  private def within(r1: Range, r2: Range) = {
    r2.contains(r1.start) && r2.contains(r1.end)
  }

  /** Checks whether r1 and r2 has points in common */
  private def intersects(r1: Range, r2: Range) = {
    r2.contains(r1.start) || r2.contains(r1.end) || r1.contains(r2.start) || r1.contains(r2.end)
  }
}

object SegNode {
  def apply[T](l: SegmentTree[T]) = {
    new SegNode(l, None, l.range, None)
  }

  def apply[T](l: SegmentTree[T],
               r: SegmentTree[T]) = {
    val lr = l.range
    val rr = r.range
    require(rr.start == lr.end + 1, "Right node range should start immediately after left")
    new SegNode(l, Some(r), l.range.start to r.range.end, None)
  }
}

case class SegLeaf[T](val index: Int, val data: T) extends SegmentTree[T] {
  val size = 1
  lazy val range = index to index
  override def toString = data.toString

  def apply(i: Int): T = {
    require(i == index, "index is out of bounds")
    data
  }

  def updatedRange(r: Range, f: Int => T): SegmentTree[T] = {
    if (r contains index) updated(f)
    else this
  }

  def updated(f: Int => T): SegmentTree[T] =
    new SegLeaf[T](index, f(index))
}


It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.

The first line contains an integer n (2 ≤ n ≤ 100) — the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the set.

Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).

NoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.

object C {
  def gcd(a: Int, b: Int): Int = {
    if (b == 0)
      a
    else
      gcd(b, a % b)
  }
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val t = (Nil : Seq[Int]).toBuffer
    for (i <- 1 to n)
      t += sc.nextInt
    val g = t.fold(t.head)(gcd(_, _))
    val cnt = t.sorted.last / g - t.size
    if (cnt % 2 == 1)
      println("Alice")
    else
      println("Bob")
  }
}

object C347 {
  @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 gcd(x: Int, y: Int): Int = {
    if(x == 0) y else gcd(y % x, x)
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val finalgcd = input.foldLeft(input(0)){case (g, n) => gcd(g, n)}
    if((input.max/finalgcd - n) % 2 == 0) {
      println("Bob")
    } else {
      println("Alice")
    }
  }
}

import scala.collection._

object A extends App {

  def gcd(x: Int, y: Int): Int =
    if (y == 0) x
    else gcd(y, x % y)

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

  val n = readString.toInt
  val as = readInts(n)

  val g = as.reduce(gcd)
  val max = as.max
  val moves = max / g - n

  println(if (moves % 2 == 1) "Alice" else "Bob")
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import scala.math._

object Main {

	def gcd(a : Int, b : Int) : Int = if (b==0) a else gcd(b,a%b)

	def main(args: Array[String]) {
		val n = in.rdInt
		var a = (for (i <- 1 to n) yield in.rdInt).sorted
		var z = a(0)
		for (i <- 1 until n) z = gcd(z,a(i))
		println( if ((a(n-1)/z-n)%2 == 1) "Alice" else "Bob" )
	}

	object in {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def FastReader = eat("")
		def eat(s : String) = st = new StringTokenizer(s)
		def rdInt = next.toInt
		def rdLong = next.toLong
		def rdDouble = next.toDouble
	}

}

object Solution extends App {

  def gcd(a: Int, b: Int): Int = {
    if (b == 0)
      a
    else
      gcd(b, a % b)
  }

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).toList
  val d = data.tail.foldLeft(data.head) {
    case (prev, el) => gcd(prev, el)
  }
//  println(d)
  if ((data.max / d - data.length) % 2== 1)
    println("Alice")
  else
    println("Bob")
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    if((input.max - n) % 2 == 0) {
      println("Bob")
    } else {
      println("Alice")
    }
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import scala.math._

object Main {

	def main(args: Array[String]) {
		val n = in.rdInt
		var a = (for (i <- 1 to n) yield in.rdInt).sorted
		var m = true
		for (i <- 1 until n)
			if (a(i)%a(0)!=0) m=false
		if (m) println( if (a(n-1)/a(0)%2 == 1) "Alice" else "Bob" )
		else println( if ( (a(n-1)-n)%2 == 1) "Alice" else "Bob" )
	}

	object in {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def FastReader = eat("")
		def eat(s : String) = st = new StringTokenizer(s)
		def rdInt = next.toInt
		def rdLong = next.toLong
		def rdDouble = next.toDouble
	}

}


One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold:  x occurs in sequence a.  Consider all positions of numbers x in the sequence a (such i, that ai = x). These numbers, sorted in the increasing order, must form an arithmetic progression. Help Jeff, find all x that meet the problem conditions.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 105). The numbers are separated by spaces.

In the first line print integer t — the number of valid x. On each of the next t lines print two integers x and px, where x is current suitable value, px is the common difference between numbers in the progression (if x occurs exactly once in the sequence, px must equal 0). Print the pairs in the order of increasing x.

NoteIn the first test 2 occurs exactly once in the sequence, ergo p2 = 0.

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)
  val previousIndex = Array.ofDim[Int](100001)
  val distance = Array.ofDim[Int](100001)
  data.indices.foreach { i =>
    val value = data(i)
    val d = distance(value)
    if (d == 0) {
      if (previousIndex(value) != 0) {
        distance(value) = i + 1 - previousIndex(value)
      }
      previousIndex(value) = i + 1
    } else if (d > 0) {
      if (d == i + 1 - previousIndex(value))
        previousIndex(value) = i + 1
      else
        distance(value) = -1
    }
  }
  val res = (1 to 100000).collect{
    case (i) if previousIndex(i) != 0 && distance(i) != -1 => s"$i ${distance(i)}"
  }
  println(res.length)
  println(res.mkString("\n"))
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

object P352B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // N integers
  // a_1, ..., a_n
  // needs to find all values of x
  // x occurs in a_i
  // positions must form an arithmetic progression

  def solve(): Unit = {
    val N = sc.nextInt
    val idx = Array.fill(100001)(-1)
    val p, freq = Array.fill(100001)(0)

    @tailrec
    def loop(i: Int): Unit = {
      if (i == N) ()
      else {
        val x = sc.nextInt
        if (freq(x) < 0) ()
        else if (idx(x) < 0) {
          idx(x) = i
          freq(x) = 1
        }
        else if (p(x) == 0) {
          p(x) = i - idx(x)
          idx(x) = i
          freq(x) = 2
        }
        else if (idx(x) + p(x) == i) {
          idx(x) = i
          freq(x) += 1
        }
        else {
          freq(x) = -1
        }
        loop(i + 1)
      }
    }

    loop(0)
    out.println(freq.count(_ > 0))
    (1 to 100000).filter(freq(_) > 0).foreach { x =>
      out.println(x + " " + p(x))
    }
  }

  solve
  out.close
}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var count,differ: Int = 0
    var input: String = readLine
    var test = new Array[String](1000000)
    var rar = new Array[Int](1000000)
    var indexes  = new Array[Int](10000000)
    var fault = new Array[Int](1000000)
    var answers = new Array[String](10000000)
    var differs = new Array[Int](10000000)
    test = input.split(' ')
    for ( i <- 0 to n-1 ) {
      if ( rar(test(i).toInt) == 0 ) {
        rar(test(i).toInt) = 1
        indexes(test(i).toInt) = i;
      }
      else {
        rar(test(i).toInt) = rar(test(i).toInt) + 1
        if ( rar(test(i).toInt) == 2 ) {
          differ = i - indexes(test(i).toInt)
          differs(test(i).toInt) = differ
        }
        else
          differ = i - indexes(test(i).toInt)
          if ( differ != differs(test(i).toInt) )
            fault(test(i).toInt) = 1
          else
            indexes(test(i).toInt) = i
      }
    }
   for ( i <- 0 to 100000 )
     if (( rar(i) != 0 ) && ( fault(i) != 1 )) {
       answers(count) = i.toString +" "+ differs(i)
       count = count + 1
     }
   println(count);
   for ( i <- 0 to count-1 )
     println(answers(i))
  }

}

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)
  val indexValue = data.indices.foldLeft(Map.empty[Int, List[Int]]) {
    case (acc, i) => acc + (data(i) -> (i :: acc.getOrElse(data(i), Nil)))
  }

  val res = indexValue.flatMap{
    case (value, list) if list.length == 1 => Some((value, 0))
    case (value, list) =>
      val distance = list.head - list(1)
      if (list.sliding(2).forall(i => i.head - i(1) == distance))
        Some(value, distance)
      else
        None
  }

  println(res.size)
  println(res.map{case (v, d) => s"$v $d"}.mkString("\n"))

}

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)
  val indexValue = data.indices.foldLeft(Map.empty[Int, (Int, Int)]) {
    case (acc, i) if !acc.contains(data(i)) =>
      acc + (data(i) -> (i, 0))
    case (acc, i) if acc(data(i))._2 == -1 => acc
    case (acc, i) if acc(data(i))._2 == 0 =>
      acc + (data(i) -> (i, i - acc(data(i))._1))
    case (acc, i) =>
      val distance = i - acc(data(i))._1
      acc + (data(i) -> (i, if (acc(data(i))._2 == distance) distance else - 1))
  }
  println(indexValue.filter(_._2._2 >= 0).keys.toList.sorted.map{case v => s"$v ${indexValue(v)._2}"}.mkString("\n"))

}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var z,min,minpos,d: Int = 1000000
    var test = new Array[String](100000)
    var indexes = new Array[Int](100000)
    var input: String = readLine
    var answer: Boolean = false
    test = input.split(' ')
    for ( i <- 0 to n-1)
      indexes(i) = i
    for ( i <- 0 to n-1) {
      min = 100000
      minpos =indexes(i)
      for ( j <- i to n-1)
        if (test(indexes(j)).toInt < min) {
          min = test(indexes(j)).toInt
          minpos = j
        }
      z = indexes(minpos)
      indexes(minpos) = indexes(i)
      indexes(i) = z
    }
    z = 0
    while ( z != n) {
      min = z
      while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )
          z = z + 1
      minpos = z
      if ( (minpos - min) == 0)
        println(test(indexes(z))+" "+0.toString)
      else {
        answer = true
        d = indexes(min+1) - indexes(min)
        for ( j <- min to minpos-1)
          if ((indexes(j+1)-indexes(j)) != d)
            answer = false
        if (answer == true)
          println(test(indexes(z))+" "+d.toString)
      }
      z = z + 1
    }
  }

}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var count,z,min,minpos,d: Int = 1000000
    var test = new Array[String](100000)
    var indexes = new Array[Int](100000)
    var input: String = readLine
    var answer: Boolean = false
    var answers = new Array[String](10000000)
    count = 0
    test = input.split(' ')
    for ( i <- 0 to n-1)
      indexes(i) = i
    for ( i <- 0 to n-1) {
      min = 100000
      minpos =indexes(i)
      for ( j <- i to n-1)
        if (test(indexes(j)).toInt < min) {
          min = test(indexes(j)).toInt
          minpos = j
        }
      z = indexes(minpos)
      indexes(minpos) = indexes(i)
      indexes(i) = z
    }
    z = 0
    while ( z != n) {
      min = z
      while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )
          z = z + 1
      minpos = z
      if ( (minpos - min) == 0) {
        answers(count) = test(indexes(z))+" "+0.toString
        count = count + 1
      }
      else {
        answer = true
        d = indexes(min+1) - indexes(min)
        for ( j <- min to minpos-1)
          if ((indexes(j+1)-indexes(j)) != d)
            answer = false
        if (answer == true) {
          answers(count) = test(indexes(z))+" "+d.toString
          count = count + 1
        }
      }
      z = z + 1
    }
    println(count)
    for ( i<-0 to count-1)
      println(answers(i))
  }

}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var count,differ: Int = 0
    var input: String = readLine
    var test = new Array[String](1000000)
    var rar = new Array[Int](1000000)
    var indexes  = new Array[Int](10000000)
    var fault = new Array[Int](1000000)
    var answers = new Array[String](10000000)
    var differs = new Array[Int](10000000)
    test = input.split(' ')
    for ( i <- 0 to n-1 ) {
      if ( rar(test(i).toInt) == 0 ) {
        rar(test(i).toInt) = 1
        indexes(test(i).toInt) = i;
      }
      else {
        rar(test(i).toInt) = rar(test(i).toInt) + 1
        if ( rar(test(i).toInt) == 2 ) {
          differ = i - indexes(test(i).toInt)
          differs(test(i).toInt) = differ
        }
        else
          differ = i - indexes(test(i).toInt)
          if ( differ != differs(test(i).toInt) )
            fault(test(i).toInt) = 1
          else
            indexes(test(i).toInt) = i
      }
    }
   for ( i <- 0 to 99999 )
     if (( rar(i) != 0 ) && ( fault(i) != 1 )) {
       answers(count) = i.toString +" "+ differs(i)
       count = count + 1
     }
   println(count);
   for ( i <- 0 to count-1 )
     println(answers(i))
  }

}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var z,min,minpos,d: Int = 1000000
    var test = new Array[String](100000)
    var indexes = new Array[Int](100000)
    var input: String = readLine
    var answer: Boolean = false
    test = input.split(' ')
    for ( i <- 0 to n-1)
      indexes(i) = i
    for ( i <- 0 to n-1) {
      min = 100000
      minpos =indexes(i)
      for ( j <- i to n-1)
        if (test(indexes(j)).toInt < min) {
          min = test(indexes(j)).toInt
          minpos = j
        }
      z = indexes(minpos)
      indexes(minpos) = indexes(i)
      indexes(i) = z
    }
    z = 0
    while ( z != n) {
      min = z
      while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )
          z = z + 1
      minpos = z
      if ( (minpos - min) == 0)
        println(test(indexes(z)),0)
      else {
        answer = true
        d = indexes(min+1) - indexes(min)
        for ( j <- min to minpos-1)
          if ((indexes(j+1)-indexes(j)) != d)
            answer = false
        if (answer == true)
          println(test(indexes(z)),d)
      }
      z = z + 1
    }
  }

}


Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that  and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

The first line of the input contains two integer numbers n and k (1 ≤ k ≤ n ≤ 105) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≤ ai ≤ 104) — the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≤ ti ≤ 1) — type of Mishka's behavior at the i-th minute of the lecture.

Print only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, k = r.read[Int]
    val ls, as = r.read[Array[Long]](n)
    val zs = ls.zip(as)
    val ps = zs.map{ case (l, a) => l * a }.sum
    val pfs = pf(zs.map{ case (l, a) => l * (1 - a) })

    println(ps + (1 to n - k + 1).foldLeft(0.toLong) {
      case (acc, i) => math.max(acc, pfs(i + k - 1) - pfs(i - 1))
    })
  }

  def pf(as: Array[Long]) = as.scanLeft(0.toLong){ case (acc, a) => a + acc }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
}

object A {
  def main(args: Array[String]) {
    val t = scala.io.StdIn.readLine().split(" ").map( _.toInt );
    val n = t(0);
    val k = t(1);
    var as = scala.io.StdIn.readLine().split(" ").map( _.toInt );
    var ts = scala.io.StdIn.readLine().split(" ").map( _.toInt );
    var s = 0;
    var dif = Array.ofDim[Int](n);
    var max_dif = 0;
    for(i <- 0 until n){
        if(ts(i) == 0) s += as(i);
        if(i - k >= 0 && ts(i - k) == 0)
            s -= as(i - k);
        if(i - k + 1 >= 0)
            dif(i - k + 1) = s;
            max_dif = math.max(max_dif, s);
    }
    var ans = 0;
    for(i <- 0 until n){
        if(ts(i) == 1)
            ans += as(i);
    }
    println(ans + max_dif);
  }
}


Recently, Olya received a magical square with the size of $$$2^n\times 2^n$$$.It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly $$$k$$$ splitting operations.A Splitting operation is an operation during which Olya takes a square with side $$$a$$$ and cuts it into 4 equal squares with side $$$\dfrac{a}{2}$$$. If the side of the square is equal to $$$1$$$, then it is impossible to apply a splitting operation to it (see examples for better understanding).Olya is happy to fulfill her sister's request, but she also wants the condition of Olya's happiness to be satisfied after all operations.The condition of Olya's happiness will be satisfied if the following statement is fulfilled:Let the length of the side of the lower left square be equal to $$$a$$$, then the length of the side of the right upper square should also be equal to $$$a$$$. There should also be a path between them that consists only of squares with the side of length $$$a$$$. All consecutive squares on a path should have a common side.Obviously, as long as we have one square, these conditions are met. So Olya is ready to fulfill her sister's request only under the condition that she is satisfied too. Tell her: is it possible to perform exactly $$$k$$$ splitting operations in a certain order so that the condition of Olya's happiness is satisfied? If it is possible, tell also the size of the side of squares of which the path from the lower left square to the upper right one will consist.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of tests. Each of the following $$$t$$$ lines contains two integers $$$n_i$$$ and $$$k_i$$$ ($$$1 \le n_i \le 10^9, 1 \le k_i \le 10^{18}$$$) — the description of the $$$i$$$-th test, which means that initially Olya's square has size of $$$2^{n_i}\times 2^{n_i}$$$ and Olya's sister asks her to do exactly $$$k_i$$$ splitting operations.

Print $$$t$$$ lines, where in the $$$i$$$-th line you should output "YES" if it is possible to perform $$$k_i$$$ splitting operations in the $$$i$$$-th test in such a way that the condition of Olya's happiness is satisfied or print "NO" otherwise. If you printed "YES", then also print the $$$log_2$$$ of the length of the side of the squares through space, along which you can build a path from the lower left square to the upper right one. You can output each letter in any case (lower or upper). If there are multiple answers, print any.

NoteIn each of the illustrations, the pictures are shown in order in which Olya applied the operations. The recently-created squares are highlighted with red.In the first test, Olya can apply splitting operations in the following order:   Olya applies one operation on the only existing square. The condition of Olya's happiness will be met, since there is a path of squares of the same size from the lower left square to the upper right one:  The length of the sides of the squares on the path is $$$1$$$. $$$log_2(1) = 0$$$.In the second test, Olya can apply splitting operations in the following order:   Olya applies the first operation on the only existing square. She applies the second one on the right bottom square. The condition of Olya's happiness will be met, since there is a path of squares of the same size from the lower left square to the upper right one:  The length of the sides of the squares on the path is $$$2$$$. $$$log_2(2) = 1$$$.In the third test, it takes $$$5$$$ operations for Olya to make the square look like this:  Since it requires her to perform $$$7$$$ splitting operations, and it is impossible to perform them on squares with side equal to $$$1$$$, then Olya cannot do anything more and the answer is "NO".

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 MAX = 31
    def divNum(x: Int) = {
      if (x == 0) 0L
      else ((1L << x * 2) - 1) / 3
    }

    def calc(n: Int, k: Long): Option[Int] = {
      if (n > 31) Some(n - 1) // 一回全体を４分割した後、右下だけで全部消化できる
      else {

        val S = divNum(n)
        var cur = 1
        var cnt = 0
        var i = 1
        while (i <= MAX && i <= n) {
          cnt += cur
          cur = cur * 2 + 1
          if (cnt <= k && k <= S - cur * divNum(n - i)) {
            return Some(n - i)
          }
          i += 1
        }
        None
      }
    }

    rep(ni()) { _ =>
      val n = ni()
      val k = nl()
      calc(n, k) match {
        case Some(lg) => out.println(s"YES $lg")
        case None => out.println("NO")
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    // todo k == 0に注意
    val MAX = 31
    def divNum(x: Int) = {
      if (x == 0) 0L
      else ((1L << x * 2) - 1) / 3
    }

    def calc(n: Int, k: Long): Option[Int] = {
      if (k == 0) Some(n)
      else {
        val S = divNum(n)
        var cur = 1
        var cnt = 0
        var i = 1
        while (i <= MAX && i <= n) {
          cnt += cur
          cur = cur * 2 + 1
          if (cnt <= k && k <= S - cur * divNum(n - i)) {
            return Some(n - i)
          }
          i += 1
        }
        None
      }
    }

    rep(ni()) { _ =>
      val n = ni()
      val k = nl()
      calc(n, k) match {
        case Some(lg) => out.println(s"YES $lg")
        case None => out.println("NO")
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val MAX = 32
    def divNum(x: Int) = {
      if (x == 0) 0L
      else ((1L << x * 2) - 1) / 3
    }

    def calc(n: Int, k: Long): Option[Int] = {
      val S = divNum(n)
      var cur = 1
      var cnt = 0
      var i = 1
      while (i <= MAX && i <= n) {
        cnt += cur
        cur = cur * 2 + 1
        if (cnt <= k && k <= S - cur * divNum(n - i)) {
          return Some(n - i)
        }
        i += 1
      }
      None
    }

    rep(ni()) { _ =>
      val n = ni()
      val k = nl()
      calc(n, k) match {
        case Some(lg) => out.println(s"YES $lg")
        case None => out.println("NO")
      }
    }
  }

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

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

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

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

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

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


Sasha has an array of integers a1, a2, ..., an. You have to perform m queries. There might be queries of two types:  1 l r x — increase all integers on the segment from l to r by values x;  2 l r — find , where f(x) is the x-th Fibonacci number. As this number may be large, you only have to find it modulo 109 + 7. In this problem we define Fibonacci numbers as follows: f(1) = 1, f(2) = 1, f(x) = f(x - 1) + f(x - 2) for all x > 2.Sasha is a very talented boy and he managed to perform all queries in five seconds. Will you be able to write the program that performs as well as Sasha?

The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of elements in the array and the number of queries respectively. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). Then follow m lines with queries descriptions. Each of them contains integers tpi, li, ri and may be xi (1 ≤ tpi ≤ 2, 1 ≤ li ≤ ri ≤ n, 1 ≤ xi ≤ 109). Here tpi = 1 corresponds to the queries of the first type and tpi corresponds to the queries of the second type. It's guaranteed that the input will contains at least one query of the second type.

For each query of the second type print the answer modulo 109 + 7.

NoteInitially, array a is equal to 1, 1, 2, 1, 1.The answer for the first query of the second type is f(1) + f(1) + f(2) + f(1) + f(1) = 1 + 1 + 1 + 1 + 1 = 5. After the query 1 2 4 2 array a is equal to 1, 3, 4, 3, 1.The answer for the second query of the second type is f(3) + f(4) + f(3) = 2 + 3 + 2 = 7.The answer for the third query of the second type is f(1) + f(3) + f(4) + f(3) + f(1) = 1 + 2 + 3 + 2 + 1 = 9.

import scala.collection.mutable.ArrayBuffer

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 MOD = 1000000007L

  final case class M1x2(a11: Long, a12: Long) {

    def +(b: M1x2) = M1x2(
      (a11 + b.a11) % MOD,
      (a12 + b.a12) % MOD)

    def *(b: M2x2) = M1x2(
      (a11 * b.a11 + a12 * b.a21) % MOD,
      (a11 * b.a12 + a12 * b.a22) % MOD)

  }

  val FibStart = M1x2(0, 1)

  final case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {

    def *(b: M2x2) = M2x2(
      (a11 * b.a11 + a12 * b.a21) % MOD,
      (a11 * b.a12 + a12 * b.a22) % MOD,
      (a21 * b.a11 + a22 * b.a21) % MOD,
      (a21 * b.a12 + a22 * b.a22) % MOD)

    def pow(n: Long) = {
      var pow2 = this
      var res = M2x2.Unit
      var deg = n

      while (deg > 0) {
        if ((deg & 1) != 0) res *= pow2
        pow2 *= pow2
        deg >>= 1
      }

      res
    }

  }

  object M2x2 {

    val Unit = M2x2(
      1, 0,
      0, 1)

    val FibMul = M2x2(
      0, 1,
      1, 1)
  }

  def fib(n: Long) = FibStart * M2x2.FibMul.pow(n)

  case class SegTree(as: Array[M1x2]) {

    val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)

    val n = as.length
    val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)
    val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      if (l > r) 0
      else if (l == tl && r == tr) t(v).a11
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1

        lazyMul(v2) *= lazyMul(v)
        lazyMul(v2 + 1) *= lazyMul(v)
        t(v2) *= lazyMul(v)
        t(v2 + 1) *= lazyMul(v)
        lazyMul(v) = M2x2.Unit

        (query(l, Math.min(r, tm), v2, tl, tm) +
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD
      }
    }

    def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (l == tl && r == tr) {
        lazyMul(v) *= mul
        t(v) *= mul
      } else if (l <= r) {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        update(l, Math.min(r, tm), mul, v2, tl, tm)
        update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)
        t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)
      }
    }

  }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  val st = SegTree(as.map(x => fib(x)))

  val res = ArrayBuffer.empty[Long]

  for (_ <- 0 until m) {

    val s = readLine
    val tl = new java.util.StringTokenizer(s)

    if (s.startsWith("1")) {
      val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)
      st.update(l - 1, r - 1, M2x2.FibMul.pow(x))
    } else {
      val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)
      res += st.query(l - 1, r - 1)
    }
  }

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

  println(res.mkString("\n"))

  Console.flush
}

import scala.collection.mutable.ArrayBuffer

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 MOD = 1000000007

  case class M1x2(a11: Long, a12: Long) {

    def +(other: M1x2) = M1x2(
      (this.a11 + other.a11) % MOD,
      (this.a12 + other.a12) % MOD)

    def *(other: M2x2) = M1x2(
      (this.a11 * other.a11 + this.a12 * other.a21) % MOD,
      (this.a11 * other.a12 + this.a12 * other.a22) % MOD)

  }

  val FibStart = M1x2(1, 1)

  case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {

    def *(other: M2x2) = M2x2(
      (this.a11 * other.a11 + this.a12 * other.a21) % MOD,
      (this.a11 * other.a12 + this.a12 * other.a22) % MOD,
      (this.a21 * other.a11 + this.a22 * other.a21) % MOD,
      (this.a21 * other.a12 + this.a22 * other.a22) % MOD)

    def pow(n: Long) = {
      var pow2 = this
      var res = M2x2.Unit
      var deg = n

      while (deg > 0) {
        if ((deg & 1) != 0) res *= pow2
        pow2 *= pow2
        deg >>= 1
      }

      res
    }

  }

  object M2x2 {
    val Unit = M2x2(1, 0, 0, 1)
    val Fib = M2x2(0, 1, 1, 1)
  }

  case class SegTree(as: Array[M1x2]) {

    val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)

    val n = as.length
    val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)
    val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      if (l > r) 0
      else if (l == tl && r == tr) t(v).a11
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1

        lazyMul(v2) *= lazyMul(v)
        lazyMul(v2 + 1) *= lazyMul(v)
        t(v2) *= lazyMul(v)
        t(v2 + 1) *= lazyMul(v)
        lazyMul(v) = M2x2.Unit

        (query(l, Math.min(r, tm), v2, tl, tm) +
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD
      }
    }

    def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (l == tl && r == tr) {
        lazyMul(v) *= mul
        t(v) *= mul
      } else if (l <= r) {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        update(l, Math.min(r, tm), mul, v2, tl, tm)
        update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)
        t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)
      }
    }

  }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  val st = SegTree(as.map(x => FibStart * M2x2.Fib.pow(x - 1)))

  val res = ArrayBuffer.empty[Long]

  for (_ <- 0 until m) {

    val s = readLine
    val tl = new java.util.StringTokenizer(s)

    if (s.startsWith("1")) {
      val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)
      st.update(l - 1, r - 1, M2x2.Fib.pow(x))
    } else {
      val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)
      res += st.query(l - 1, r - 1)
    }
  }

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

  println(res.mkString("\n"))

  Console.flush
}

import scala.collection.mutable.ArrayBuffer

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 MOD = 1000000007L

  case class M1x2(a11: Long, a12: Long) {

    def +(b: M1x2) = M1x2(
      (a11 + b.a11) % MOD,
      (a12 + b.a12) % MOD)

    def *(b: M2x2) = M1x2(
      (a11 * b.a11 + a12 * b.a21) % MOD,
      (a11 * b.a12 + a12 * b.a22) % MOD)

  }

  val FibStart = M1x2(0, 1)

  case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {

    def *(b: M2x2) = M2x2(
      (a11 * b.a11 + a12 * b.a21) % MOD,
      (a11 * b.a12 + a12 * b.a22) % MOD,
      (a21 * b.a11 + a22 * b.a21) % MOD,
      (a21 * b.a12 + a22 * b.a22) % MOD)

    def pow(n: Long) = {
      var pow2 = this
      var res = M2x2.Unit
      var deg = n

      while (deg > 0) {
        if ((deg & 1) != 0) res *= pow2
        pow2 *= pow2
        deg >>= 1
      }

      res
    }

  }

  object M2x2 {

    val Unit = M2x2(
      1, 0,
      0, 1)

    val FibMul = M2x2(
      0, 1,
      1, 1)
  }

  def fib(n: Long) = FibStart * M2x2.FibMul.pow(n)

  case class SegTree(as: Array[M1x2]) {

    val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)

    val n = as.length
    val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)
    val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      if (l > r) 0
      else if (l == tl && r == tr) t(v).a11
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1

        lazyMul(v2) *= lazyMul(v)
        lazyMul(v2 + 1) *= lazyMul(v)
        t(v2) *= lazyMul(v)
        t(v2 + 1) *= lazyMul(v)
        lazyMul(v) = M2x2.Unit

        (query(l, Math.min(r, tm), v2, tl, tm) +
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD
      }
    }

    def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (l == tl && r == tr) {
        lazyMul(v) *= mul
        t(v) *= mul
      } else if (l <= r) {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        update(l, Math.min(r, tm), mul, v2, tl, tm)
        update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)
        t(v) = (t(v2) + t(v2 + 1)) * lazyMul(v)
      }
    }

  }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  val st = SegTree(as.map(x => fib(x)))

  val res = ArrayBuffer.empty[Long]

  for (_ <- 0 until m) {

    val s = readLine
    val tl = new java.util.StringTokenizer(s)

    if (s.startsWith("1")) {
      val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)
      st.update(l - 1, r - 1, M2x2.FibMul.pow(x))
    } else {
      val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)
      res += st.query(l - 1, r - 1)
    }
  }

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

  println(res.mkString("\n"))

  Console.flush
}

import scala.collection.mutable.ArrayBuffer

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 MOD = 1000000007

  case class M1x2(a11: Long, a12: Long) {

    def +(other: M1x2) = M1x2(
      (this.a11 + other.a11) % MOD,
      (this.a12 + other.a12) % MOD)

    def *(other: M2x2) = M1x2(
      (this.a11 * other.a11 + this.a12 * other.a21) % MOD,
      (this.a11 * other.a12 + this.a12 * other.a22) % MOD)

  }

  val FibStart = M1x2(1, 1)

  case class M2x2(a11: Long, a12: Long, a21: Long, a22: Long) {

    def *(other: M2x2) = M2x2(
      (this.a11 * other.a11 + this.a12 * other.a21) % MOD,
      (this.a11 * other.a12 + this.a12 * other.a22) % MOD,
      (this.a21 * other.a11 + this.a22 * other.a21) % MOD,
      (this.a21 * other.a12 + this.a22 * other.a22) % MOD)

    def pow(n: Long) = {
      var pow2 = this
      var res = M2x2.Unit
      var deg = n

      while (deg > 0) {
        if ((deg & 1) != 0) res *= pow2
        pow2 *= pow2
        deg >>= 1
      }

      res
    }

  }

  object M2x2 {
    val Unit = M2x2(1, 0, 0, 1)
    val Fib = M2x2(0, 1, 1, 1)
  }

  case class SegTree(as: Array[M1x2]) {

    val NEUTRAL = M1x2(0, 0) // neutral element in respect of operation used (+)

    val n = as.length
    val t = Array.fill(4 * Integer.highestOneBit(n))(NEUTRAL)
    val lazyMul = Array.fill(4 * Integer.highestOneBit(n))(M2x2.Unit)
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      if (l > r) 0
      else if (l == tl && r == tr) t(v).a11
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1

        lazyMul(v2) *= lazyMul(v)
        lazyMul(v2 + 1) *= lazyMul(v)
        t(v2) *= lazyMul(v)
        t(v2 + 1) *= lazyMul(v)
        lazyMul(v) = M2x2.Unit

        (query(l, Math.min(r, tm), v2, tl, tm) +
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)) % MOD
      }
    }

    def update(l: Int, r: Int, mul: M2x2, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (l == tl && r == tr) {
        lazyMul(v) *= mul
        t(v) *= mul
      } else if (l <= r) {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        update(l, Math.min(r, tm), mul, v2, tl, tm)
        update(Math.max(l, tm + 1), r, mul, v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

  }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  val st = SegTree(as.map(x => FibStart * M2x2.Fib.pow(x - 1)))

  val res = ArrayBuffer.empty[Long]

  for (_ <- 0 until m) {

    val s = readLine
    val tl = new java.util.StringTokenizer(s)

    if (s.startsWith("1")) {
      val Array(_, l, r, x) = Array.fill(4)(tl.nextToken.toInt)
      st.update(l - 1, r - 1, M2x2.Fib.pow(x))
    } else {
      val Array(_, l, r) = Array.fill(3)(tl.nextToken.toInt)
      res += st.query(l - 1, r - 1)
    }
  }

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

  println(res.mkString("\n"))

  Console.flush
}


Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.

The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.

Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)

  def count(first: Int, last: Int): Long = {
    if (last - first < 2)
      0
    else {
      val diff: Long = last - first
      diff * (diff - 1) / 2
    }
  }

  val res = (1 until n).foldLeft(0, 0l) {
    case ((first, sum), i) if data(i) - data(first) > d =>
      val newFirst = (first to i).find(j => data(i) - data(j) <= d).get
      val newSum = sum + (first until newFirst).map(count(_, i - 1)).sum
      (newFirst, newSum)
    case ((first, sum), i) => (first, sum)
  }
  println(res._2 + (res._1 until n).map(count(_, n - 1)).sum)
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C153A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 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
  }
}

class C153A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  var a: Array[Int] = _

  def solve(): Unit = {
    val n = ni()
    val d = ni()

    a = na(n)

    val ans = a.zipWithIndex.map { f =>
      val x = (bs(f._2, n-1, f._1 + d + 1) - f._2 - 1).toLong
//      println(bs(f._2, n-1, f._1 + d + 1) + " " +x)
      if(x >= 2) {
        (x*(x-1))/2
      }
      else 0L
    }.sum
    out.println(ans)
  }

  def bs(st: Int, en: Int, tar: Long): Int = {
    var l = st
    var r = en
    while (r > l) {
      val m = l + (r - l) / 2
      if(a(m) >= tar) r = m
      else l = m+1
    }
    if(a(l) < tar) l+1
    else l
  }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val Array(n,d)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val dp=new Array[Long](n)
    val sum=new Array[Long](n)
    sum(0)=0
    for(i<-1 until n) sum(i)=sum(i-1)+i-1

    var i=0
    var j=0
    while(j<n){
        if(arr(j)-arr(i)<=d){
            j+=1
        }
        else{
            dp(i)=sum(j-1-i)
            i+=1
        }
    }
    for(k<-i until n){
        dp(k)=sum(n-1-k)
    }
    //println(dp.mkString(","))
    println(dp.sum)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)

  def count(first: Int, last: Int) = {
    if (last - first < 2)
      0
    else {
      val diff = last - first
      diff * (diff - 1) / 2
    }
  }

  val res = (1 until n).foldLeft(0, 0) {
    case ((first, sum), i) if data(i) - data(first) > d =>
      val newFirst = (first to i).find(j => data(i) - data(j) <= d).get
      val newSum = sum + (first until newFirst).map(count(_, i - 1)).sum
      (newFirst, newSum)
    case ((first, sum), i) => (first, sum)
  }
  println(res._2 + (res._1 until n).map(count(_, n - 1)).sum)
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val Array(n,d)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val dp=new Array[Long](n)
    val sum=new Array[Int](n)
    sum(0)=0
    for(i<-1 until n) sum(i)=sum(i-1)+i-1

    var i=0
    var j=0
    while(j<n){
        if(arr(j)-arr(i)<=d){
            j+=1
        }
        else{
            dp(i)=sum(j-1-i)
            i+=1
        }
    }
    for(k<-i until n){
        dp(k)=sum(n-1-k)
    }
    //println(dp.mkString(","))
    println(dp.sum)
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val Array(n,d)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val dp=new Array[Int](n)

    var i=0
    var j=0
    while(j<n){
        if(arr(j)-arr(i)<=d){
            if(j-i>1) dp(i)+=math.max(0,j-i-1)
            j+=1
        }
        else{
            i+=1
            if(j-i>1) dp(i)=math.max(0,dp(i-1)-(j-i-1))
        }
    }
    for(k<-i+1 to n-3){
        dp(k)=math.max(0, dp(k-1)-(n-1-i-1))
    }
    //println(dp.mkString(","))
    println(dp.sum)
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    val Array(n,d)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val dp=new Array[Int](n)
    val sum=new Array[Int](n)
    sum(0)=0
    for(i<-1 until n) sum(i)=sum(i-1)+i-1

    var i=0
    var j=0
    while(j<n){
        if(arr(j)-arr(i)<=d){
            j+=1
        }
        else{
            dp(i)=sum(j-1-i)
            i+=1
        }
    }
    for(k<-i until n){
        dp(k)=sum(n-1-k)
    }
    //println(dp.mkString(","))
    println(dp.sum)
}


This is an interactive problem.Vasya and Petya are going to play the following game: Petya has some positive integer number $$$a$$$. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers $$$(x, y)$$$. Petya will answer him:   "x", if $$$(x \bmod a) \geq (y \bmod a)$$$.  "y", if $$$(x \bmod a) < (y \bmod a)$$$. We define $$$(x \bmod a)$$$ as a remainder of division $$$x$$$ by $$$a$$$.Vasya should guess the number $$$a$$$ using no more, than 60 questions.It's guaranteed that Petya has a number, that satisfies the inequality $$$1 \leq a \leq 10^9$$$.Help Vasya playing this game and write a program, that will guess the number $$$a$$$.

NoteIn the first test, you should play $$$3$$$ games with Petya's numbers $$$1$$$, $$$2$$$ and $$$3$$$.In the first game, Petya will answer "x" (without quotes) to any question, because $$$(x \bmod 1) = 0$$$ for any integer $$$x$$$. In the second game, if you will ask pair $$$(0, 0)$$$, the answer will be "x" (without quotes), because $$$(0 \bmod 2) \geq (0 \bmod 2)$$$. But if you will ask pair $$$(2, 5)$$$, the answer will be "y" (without quotes), because $$$(2 \bmod 2) < (5 \bmod 2)$$$, because $$$(2 \bmod 2) = 0$$$ and $$$(5 \bmod 2) = 1$$$.

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 = {
    def play(): Boolean = {
      def queryRange(): (Int, Int) = {
        REP(30) { i =>
          val y = 1 << i
          val x = y / 2
          out.println(s"? $x $y")
          out.flush()
          ns() match {
            case "x" =>
              return (x, y)

            case "y" =>
          }
        }
        val y = 1 << 30
        val x = y / 2
        (x, y)
      }

      var (l, r) = queryRange()
      while(r - l > 1) {
        val mid = (r + l) / 2
        val x = mid
        val y = r
        out.println(s"? $x $y")
        out.flush()

        ns() match {
          case "x" =>
            // a > mid
            l = mid
          case "y" =>
            // a <= mid
            r = mid
        }
      }

      out.println(s"! $r")
      out.flush()
      true
    }

    var end = false
    while(!end) {
      ns() match {
        case "start" =>
          end = !play()

        case "end" =>
          end = true
      }
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    def play(): Boolean = {
      def queryRange(): (Int, Int) = {
        REP(30) { i =>
          val y = 1 << i
          val x = y / 2
          out.println(s"? $x $y")
          out.flush()
          ns() match {
            case "x" =>
              return (x, y)

            case "y" =>
          }
        }
        ???
      }

      var (l, r) = queryRange()
      while(r - l > 1) {
        val mid = (r + l) / 2
        val x = mid
        val y = r
        out.println(s"? $x $y")
        out.flush()

        ns() match {
          case "x" =>
            // a > mid
            l = mid
          case "y" =>
            // a <= mid
            r = mid
        }
      }

      out.println(s"! $r")
      out.flush()
      true
    }

    var end = false
    while(!end) {
      ns() match {
        case "start" =>
          end = !play()

        case "end" =>
          end = true
      }
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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


The only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of $$$m$$$ pages.Polycarp also has $$$n$$$ cups of coffee. The coffee in the $$$i$$$-th cup Polycarp has $$$a_i$$$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).Let's consider some day of Polycarp's work. Consider Polycarp drinks $$$k$$$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $$$a_{i_1}, a_{i_2}, \dots, a_{i_k}$$$. Then the first cup he drinks gives him energy to write $$$a_{i_1}$$$ pages of coursework, the second cup gives him energy to write $$$max(0, a_{i_2} - 1)$$$ pages, the third cup gives him energy to write $$$max(0, a_{i_3} - 2)$$$ pages, ..., the $$$k$$$-th cup gives him energy to write $$$max(0, a_{i_k} - k + 1)$$$ pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of cups of coffee and the number of pages in the coursework. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the caffeine dosage of coffee in the $$$i$$$-th cup.

If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.

NoteIn the first example Polycarp can drink fourth cup during first day (and write $$$1$$$ page), first and second cups during second day (and write $$$2 + (3 - 1) = 4$$$ pages), fifth cup during the third day (and write $$$2$$$ pages) and third cup during the fourth day (and write $$$1$$$ page) so the answer is $$$4$$$. It is obvious that there is no way to write the coursework in three or less days.In the second example Polycarp can drink third, fourth and second cups during first day (and write $$$4 + (2 - 1) + (3 - 2) = 6$$$ pages) and sixth cup during second day (and write $$$4$$$ pages) so the answer is $$$2$$$. It is obvious that Polycarp cannot write the whole coursework in one day in this test.In the third example Polycarp can drink all cups of coffee during first day and write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15$$$ pages of coursework.In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) = 14$$$ pages of coursework and during second day he will write $$$5$$$ pages of coursework. This is enough to complete it.In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1.

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 A = na(N)
    sort(A)
    reverse(A)

//    debug(A)

    def check(x: Int): Boolean = {
//      debug(s"check($x)")
      var i = 0
      var m = M
      while (m > 0 && i < N) {
        val k = i / x
        val v = max(0, A(i) - k)
        m -= v
//        debug(s"$i $k $v")
        i += 1
      }
      m <= 0
    }

    val INF = N + 1
    var l = 0
    var r = INF
    while(r - l > 1) {
      val mid = (r + l) / 2
      if (check(mid)) r = mid
      else l = mid
    }

    if (r == INF) out.println(-1)
    else out.println(r)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

  def reverse(as: Array[Int]): Unit = {
    REP(as.length / 2) { i =>
      val t = as(i)
      as(i) = as(as.length - 1 - i)
      as(as.length - 1 - i) = t
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    sort(A)
    reverse(A)

//    debug(A)

    def check(x: Int): Boolean = {
//      debug(s"check($x)")
      var i = 0
      var m = M
      while (m > 0 && i < N) {
        val k = i / x
        val v = max(0, A(i) - k)
        m -= v
//        debug(s"$i $k $v")
        i += 1
      }
      m <= 0
    }

    var l = 0
    var r = N
    while(r - l > 1) {
      val mid = (r + l) / 2
      if (check(mid)) r = mid
      else l = mid
    }

    if (r == N) out.println(-1)
    else out.println(r)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

  def reverse(as: Array[Int]): Unit = {
    REP(as.length / 2) { i =>
      val t = as(i)
      as(i) = as(as.length - 1 - i)
      as(as.length - 1 - i) = t
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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
  }
}