Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.

The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.

Print m integers — the i-th integer denotes value v for sequence a after the i-th query.

NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation

//package solutions

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

import scala.annotation.tailrec

/**
  * @author traff
  */

object Solution_cf339d extends App {

  class FastScanner() {
    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var st: StringTokenizer = _

    private def nextToken = {
      while (st == null || !st.hasMoreElements) try
        st = new StringTokenizer(br.readLine)

      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      st.nextToken
    }

    def nextInt: Int = nextToken.toInt

    def nextLong: Long = nextToken.toLong

    def nextDouble: Double = nextToken.toDouble
  }

  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new FastScanner(), out)

    out.close()
  }

  def run(s: FastScanner, out: PrintWriter): Unit = {
    val (n, m) = (s.nextInt, s.nextInt)

    var a: Array[Int] = new Array[Int]((1 << n + 1) - 1)

    for (i <- 1 << n until 1 << (n + 1)) {
      a(i - 1) = s.nextInt
    }

    @tailrec
    def up(k: Int, f: Boolean): Unit = {
      if (k > 0) {
        val i = if (k % 2 == 0) k - 1 else k
        a(i / 2) = if (f) a(i) | a(i + 1) else a(i) ^ a(i + 1)
        up(i / 2, !f)
      }
    }

    for (i <- 1 << n until 1 << (n + 1)) {
      if (i % 2 == 0) {
        up(i - 1, f = true)
      }
    }

    for (i <- 1 to m) {
      val (p, b) = (s.nextInt, s.nextInt)
      val k = (1 << n) - 1 + p - 1
      a(k) = b
      up(k, f = true)
      out.println(s"${a(0)}")
    }
  }
}

import java.io.PrintWriter

/**
  * @author traff
  */

object Main extends App {

  class FastScanner() {
    import java.io.{FileReader, PrintWriter}
    import java.io.{BufferedReader, IOException, InputStreamReader}
    import java.util.StringTokenizer

    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var st: StringTokenizer = _

    def this(f: String) {
      this()
      br = new BufferedReader(new FileReader(f))
    }

    private def nextToken = {
      while (st == null || !st.hasMoreElements) try
        st = new StringTokenizer(br.readLine)

      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      st.nextToken
    }

    def nextInt: Int = nextToken.toInt

    def nextLong: Long = nextToken.toLong

    def nextDouble: Double = nextToken.toDouble
  }

  sealed abstract class Op extends ((Int, Int) => Int) {
  }

  case class Xor() extends Op {
    override def apply(v1: Int, v2: Int): Int = v1 ^ v2
  }

  case class Or() extends Op {
    override def apply(v1: Int, v2: Int): Int = v1 | v2
  }

  class Node(parent: Option[Node], a: Array[Int], leafs: Array[Node], ln: Int, rn: Int) {
    var r, l: Option[Node] = None
    private var _v: Int = 0

    if (ln == rn) {
      _v = a(ln)
      leafs(ln) = this
      r = None
      l = None
    } else {
      require(ln < rn, s"$ln $rn")

      val lnode = new Node(Some(this), a, leafs, ln, ln + (rn - ln) / 2)
      l = Some(lnode)
      val rnode = new Node(Some(this), a, leafs, ln + (rn - ln) / 2 + 1, rn)
      r = Some(rnode)

      _v = lnode.op().apply(lnode._v, rnode._v)
    }

    def op(): Op = {
      l match {
        case None => Or()
        case Some(n) => n.op() match {
          case Xor() => Or()
          case Or() => Xor()
        }
      }
    }

    def up(): Unit = {
      if (l.isDefined) {
        _v = l.get.op().apply(l.get._v, r.get._v)
      }
      parent.foreach(p => p.up())
    }

    def value: Int = _v

    def value_=(value: Int): Unit = {
      _v = value
      up()
    }

  }

  val s = new FastScanner()
  val out = new PrintWriter(System.out)

  val (n, m) = (s.nextInt, s.nextInt)

  var a: Array[Int] = new Array[Int](1 << n )

  for (i <- 1 to 1 << n) {
    a(i-1) = s.nextInt
  }

  val leafs = new Array[Node](a.length)

  val tree = new Node(None, a, leafs, 0, a.length - 1)

  for (i <- 1 to m) {
    val (p, b) = (s.nextInt, s.nextInt)
    leafs(p - 1).value = b
    out.println(tree.value)
  }

  out.close()

}

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 C197D(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 C197D(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n: Int = ni()
    val m = ni()
    val limit = Math.pow(2, n).toInt

    val a: Array[Int] = na(limit)

    val t = new SegmentTree(limit, a)
    t.build(1, 0, limit - 1, if(n%2 == 0) false else true)
    REP(m) { _ =>
      val p = ni()
      val b = ni()
      t.update(1, 0, limit - 1, if(n%2 == 0) false else true, p - 1, b)
      out.println(t.getAnswer)
    }
  }

  private class SegmentTree(n: Int, a: Array[Int]) {
    private val tree: Array[Int] = Array.ofDim[Int](4 * n)

    def build(v: Int, tl: Int, tr:Int, op: Boolean): Unit = {
      if(tl == tr) {
        tree(v) = a(tl)
      } else {
        val tm = tl + (tr - tl) / 2
        build(v << 1, tl, tm, !op)
        build(v << 1 | 1, tm + 1, tr, !op)
        tree(v) = if(op) tree(v << 1) | tree(v << 1 | 1) else tree(v << 1) ^ tree(v << 1 | 1)
      }
    }

    def update(v: Int, tl: Int, tr: Int, op: Boolean, index: Int, value: Int): Unit = {
      if(tl == tr) {
        tree(v) = value
      } else {
        val tm = tl + (tr - tl) / 2
        if(index <= tm) {
          update(v << 1, tl, tm, !op, index, value)
        } else {
          update(v << 1 | 1, tm + 1, tr, !op, index, value)
        }
        tree(v) = if(op) tree(v << 1) | tree(v << 1 | 1) else tree(v << 1) ^ tree(v << 1 | 1)
      }
    }

    def getAnswer: Int = {
      tree(1)
    }

  }
}

object D339 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val init = readInts(1<<n)
    val tree = new SegmentTree(init, n)
//    out.println((0 until (1<<n)).map{i => tree.rsq(i, i)}.mkString(" "))
    for(_ <- 1 to m) {
      val Array(p, b) = readInts(2)
      tree.update(p-1, p-1, b)
      out.println(tree.rsq(0, (1<<n) - 1))
    }
    out.close()
  }

  class Node (_from: Int, _to: Int) {
    var sum = 0
    //Here We store the value that will be propagated lazily
    var pendingValue: Integer = _
    lazy val from: Int = _from
    lazy val to: Int = _to
    lazy val size: Int = to-from+1
  }
  class SegmentTree(array: Array[Int], n: Int) {
    private val heapSize = (2 * math.pow(2.0, math.floor((math.log(array.length) / math.log(2.0)) + 1))).toInt
    val heap = new Array[Node](heapSize)
    build(1, 0, array.length, if(n%2 ==0) false else true)

    private def build(v: Int, from: Int, size: Int, or: Boolean) {
      heap(v) = new Node(from, from + size - 1)
      if(size == 1) {
        // function
        heap(v).sum = array(from)
      } else {
        build(2*v, from, size/2, !or)
        build(2*v+1, from + size/2, size - size/2, !or)
        // function
        if(or) {
          heap(v).sum = heap(2*v).sum | heap(2*v+1).sum
        } else {
          heap(v).sum = heap(2*v).sum ^ heap(2*v+1).sum
        }
      }
    }

    def rsq(from: Int, to: Int): Int = rsq(1, from, to, if(n%2 ==0) false else true)
    private def rsq(v: Int, from: Int, to: Int, or: Boolean): Int = {
      val n = heap(v)
      if(n.pendingValue != null && contains(n.from, n.to, from, to)) {
        (to-from+1)*n.pendingValue
        // n.pendingVal for min
      } else if(contains(from, to, n.from, n.to)) {
        heap(v).sum
      } else if (intersects(from, to, n.from, n.to)){
        propogate(v)
        val leftSum = rsq(2*v, from, to, !or)
        val rightSum = rsq(2*v+1, from, to, !or)
        // function
        if(or) {
          leftSum | rightSum
        } else {
          leftSum ^ rightSum
        }
      } else {
        // function.Zero
        0
      }
    }

    def update(from: Int, to: Int, value: Int): Unit = update(1, from, to, value, if(n%2 ==0) false else true)
    private def update(v: Int, from: Int, to: Int, value: Int, or: Boolean) {
      val n = heap(v)
      if(contains(from, to, n.from, n.to)) {
        change(n, value)
      }
      if (n.size == 1)
        return
      if (intersects(from, to, n.from, n.to)){
        propogate(v)
        update(2*v, from, to, value, !or)
        update(2*v+1, from, to, value, !or)
        // function
        if(or) {
          n.sum = heap(2*v).sum | heap(2*v+1).sum
        } else {
          n.sum = heap(2*v).sum ^ heap(2*v+1).sum
        }
      }
    }

    private def propogate(v: Int) {
      val n = heap(v)
      if(n.pendingValue != null) {
        change(heap(2*v), n.pendingValue)
        change(heap(2*v+1), n.pendingValue)
        n.pendingValue = null // unset the pending propagation value
      }
    }
    private def change(n: Node, value: Int) {
      n.pendingValue = value
      // function
      n.sum = n.size * value
      //n.min = value
      array(n.from) = value
    }

    //Utils

    //Test if the range1 contains range2
    private def contains(from1: Int, to1: Int, from2: Int, to2: Int): Boolean = from2 >= from1 && to2 <= to1

    //check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2]//check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2]
    private def intersects(from1: Int, to1: Int, from2: Int, to2: Int) = from1 <= from2 && to1 >= from2 || from1 >= from2 && from1 <= to2
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

import scala.collection._

object D extends App {

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

  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 Array(n, m) = readInts(2)

  val bitStep = Array.tabulate(n + 1)(i => Array.ofDim[Int]((1 << n) + 1))
  bitStep(0) = 0 +: readInts(1 << n)

  for (step <- 1 to n; i <- 1 to 1 << (n - step)) {
    bitStep(step)(i) = (if ((step & 1) == 1) bitStep(step - 1)(2 * i) | bitStep(step - 1)(2 * i - 1)
    else bitStep(step - 1)(2 * i) ^ bitStep(step - 1)(2 * i - 1))
  }

  var i = 0
  while (i < m) {

    val t = tokenizeLine
    var p = t.nextToken.toInt
    val b = t.nextToken.toInt

    bitStep(0)(p) = b
    for (step <- 1 to n) {
      p = (p + 1) >> 1
      if ((step & 1) == 1) bitStep(step)(p) = bitStep(step - 1)(2 * p) | bitStep(step - 1)(2 * p - 1)
      else bitStep(step)(p) = bitStep(step - 1)(2 * p) ^ bitStep(step - 1)(2 * p - 1)
    }

    println(bitStep(n)(1))

    i += 1
  }

  Console.flush
}

import scala.collection._

object D extends App {

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

  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 Array(n, m) = readInts(2)

  val bitStep = Array.tabulate(n + 1)(i => Array.ofDim[Int]((1 << n) + 1))
  bitStep(0) = 0 +: readInts(1 << n)

    for (step <- 1 to n; i <- 1 to 1 << (n - step)) {
      bitStep(step)(i) = (if ((step & 1) == 1) bitStep(step - 1)(2 * i) | bitStep(step - 1)(2 * i - 1)
      else bitStep(step - 1)(2 * i) ^ bitStep(step - 1)(2 * i - 1))
  }

  def calc() = bitStep(n)(1)

  var k = 0
  while (k < m) {
    val t = tokenizeLine
    val p0 = t.nextToken.toInt
    val b = t.nextToken.toInt

    for (bit <- 0 to 17) {
      bitStep(0)(p0) = b
      var p = p0
      for (step <- 1 to n) {
        p = (p + 1) >> 1
        if ((step & 1) == 1) bitStep(step)(p) = bitStep(step - 1)(2 * p) | bitStep(step - 1)(2 * p - 1)
        else bitStep(step)(p) = bitStep(step - 1)(2 * p) ^ bitStep(step - 1)(2 * p - 1)
      }
    }

    println(calc())

    k += 1
  }

  Console.flush
}

import scala.collection._

object D extends App {

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

  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 Array(n, m) = readInts(2)

  val bitStep = Array.tabulate(n + 1)(i => Array.ofDim[Int]((1 << n) + 1))
  bitStep(0) = 0 +: readInts(1 << n)

  for (step <- 1 to n; i <- 1 to 1 << (n - step)) {
    bitStep(step)(i) = (if ((step & 1) == 1) bitStep(step - 1)(2 * i) | bitStep(step - 1)(2 * i - 1)
    else bitStep(step - 1)(2 * i) ^ bitStep(step - 1)(2 * i - 1))
  }

  var i = 0
  while (i < m) {

    val t = tokenizeLine
    val p0 = t.nextToken.toInt
    val b = t.nextToken.toInt

    bitStep(0)(p0) = b
    var p = p0
    for (step <- 1 to n) {
      p = (p + 1) >> 1
      if ((step & 1) == 1) bitStep(step)(p) = bitStep(step - 1)(2 * p) | bitStep(step - 1)(2 * p - 1)
      else bitStep(step)(p) = bitStep(step - 1)(2 * p) ^ bitStep(step - 1)(2 * p - 1)
    }

    println(bitStep(n)(1))

    i += 1
  }

  Console.flush
}

object Main {
  import annotation.tailrec
  class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {
    private val n = a.size
    private val t = Array.ofDim (2*n)
    private def build {
      for (i <- n - 1 until 0 by - 1) {
        val k = i << 1
        t(i) = op (t(k), t(k+1))
      }
    }
    Array.copy (a, 0, t, n, n)
    build
    def update (p: Int, v: T) {
      val p0 = p + n
      t(p0) = v
      @tailrec def loop (i: Int) {
        if (i > 1) {
          val k = i >>> 1
          t(k) = op (t(i), t(i^1))
          loop (k)
        }
      }
      loop (p0)
    }
    //op - commutative
    def reduce (l: Int, r: Int) = {
      var res = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) res = op (res, t(i))
          if (0 != (j & 1)) res = op (t(j-1), res)
          loop ((i + 1) >>> 1, j  >>> 1)
        }
      }
      loop (l + n, r + n)
      res
    }
    def safeReduce (l: Int, r: Int) = {
      var resl = empty
      var resr = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) resl = op (resl, t(i))
          if (0 != (j & 1)) resr = op (t(j-1), resr)
          loop ((i + 1) >>> 1, j  >>> 1)
        }
      }
      loop (l + n, r + n)
      op (resl, resr)
    }
  }

  import io._
  val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(" "))
  val sb = new StringBuilder
  def rs() = lineit.next
  def ri() = rs.toInt
  def main(args: Array[String]) {
    val n = ri
    val m = ri
    val a = Array.fill (1<<n)(ri)
    val st = new SegmentTree[(Int, Int)] (a.zip (Array.fill(a.size)(0)), (x, y) => (if ((x._2 & 1) == 0) x._1 | y._1 else x._1 ^ y._1, x._2 ^ 1), (0, 0) )
    for (t <- 1 to m) {
      val i = ri - 1
      val v = ri
      st(i) = (v, 0)
      sb.append (st.safeReduce (0, 1 << n)._1)
      sb.append ('\n')
    }
    print (sb)
  }
}

object Main {
  import annotation.tailrec
  class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {
    private val n = a.size
    private val t = Array.ofDim (2*n)
    private def build {
      for (i <- n - 1 until 0 by - 1) {
        val k = i << 1
        t(i) = op (t(k), t(k+1))
      }
    }
    Array.copy (a, 0, t, n, n)
    build
    def update (p: Int, v: T) {
      val p0 = p + n
      t(p0) = v
      @tailrec def loop (i: Int) {
        if (i > 1) {
          val k = i >>> 1
          t(k) = op (t(i), t(i^1))
          loop (k)
        }
      }
      loop (p0)
    }
    //op - commutative
    def reduce (l: Int, r: Int) = {
      var res = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) res = op (res, t(i))
          if (0 != (j & 1)) res = op (t(j-1), res)
          loop ((i + 1) >>> 1, j  >>> 1)
        }
      }
      loop (l + n, r + n)
      res
    }
    def safeReduce (l: Int, r: Int) = {
      var resl = empty
      var resr = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) resl = op (resl, t(i))
          if (0 != (j & 1)) resr = op (t(j-1), resr)
          loop ((i + 1) >>> 1, j >>> 1)
        }
      }
      loop (l + n, r + n)
      op (resl, resr)
    }
  }

  import io._
  val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(" "))
  val sb = new StringBuilder
  def rs() = lineit.next
  def ri() = rs.toInt
  def main(args: Array[String]) {
    val n = ri
    val m = ri
    val a = Array.fill (1<<n)(ri)
    val st = new SegmentTree[(Int, Int)] (a.zip (Array.fill(a.size)(0)), (x, y) => (if ((x._2 & 1) == 0) x._1 | y._1 else x._1 ^ y._1, x._2 ^ 1), (0, 0) )
    for (t <- 1 to m) {
      val i = ri - 1
      val v = ri
      st(i) = (v, 0)
      sb.append (st.reduce (0, 1 << n)._1)
      sb.append ('\n')
    }
    print (sb)
  }
}

object Main {
  import annotation.tailrec
  class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {
    private val n = a.size
    private val t = Array.ofDim (2*n)
    private def build {
      for (i <- n - 1 until 0 by - 1) {
        val k = i << 1
        t(i) = op (t(k), t(k+1))
      }
    }
    Array.copy (a, 0, t, n, n)
    build
    def update (p: Int, v: T) {
      val p0 = p + n
      t(p0) = v
      @tailrec def loop (i: Int) {
        if (i > 1) {
          val k = i >>> 1
          t(k) = op (t(i), t(i^1))
          loop (k)
        }
      }
      loop (p0)
    }
    def root = t(1)
    //op - commutative
    def reduce (l: Int, r: Int) = {
      var res = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) res = op (res, t(i))
          if (0 != (j & 1)) res = op (t(j-1), res)
          loop ((i + 1) >>> 1, j  >>> 1)
        }
      }
      loop (l + n, r + n)
      res
    }
    def safeReduce (l: Int, r: Int) = {
      var resl = empty
      var resr = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) resl = op (resl, t(i))
          if (0 != (j & 1)) resr = op (t(j-1), resr)
          loop ((i + 1) >>> 1, j >>> 1)
        }
      }
      loop (l + n, r + n)
      op (resl, resr)
    }
  }

  import io._
  val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(" "))
  val sb = new StringBuilder
  def rs() = lineit.next
  def ri() = rs.toInt
  def main(args: Array[String]) {
    val n = ri
    val m = ri
    val a = Array.fill (1<<n)(ri)
    val st = new SegmentTree[Int] (a, (x, y) => {
      if ((x & 0x80000000) == 0) x | y | 0x80000000 else (x ^ y) & 0x7fffffff
    }, 0)
    for (t <- 1 to m) {
      val i = ri - 1
      val v = ri
      st(i) = v
      sb.append (st.root & 0x7fffffff)
      sb.append ('\n')
    }
    print (sb)
  }
}

object Main {
  import annotation.tailrec
  class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {
    private val n = a.size
    private val t = Array.ofDim (2*n)
    private def build {
      for (i <- n - 1 until 0 by - 1) {
        val k = i << 1
        t(i) = op (t(k), t(k+1))
      }
    }
    Array.copy (a, 0, t, n, n)
    build
    def update (p: Int, v: T) {
      val p0 = p + n
      t(p0) = v
      @tailrec def loop (i: Int) {
        if (i > 1) {
          val k = i >>> 1
          t(k) = op (t(i), t(i^1))
          loop (k)
        }
      }
      loop (p0)
    }
    def root = t(1)
    //op - commutative
    def reduce (l: Int, r: Int) = {
      var res = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) res = op (res, t(i))
          if (0 != (j & 1)) res = op (t(j-1), res)
          loop ((i + 1) >>> 1, j  >>> 1)
        }
      }
      loop (l + n, r + n)
      res
    }
    def safeReduce (l: Int, r: Int) = {
      var resl = empty
      var resr = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) resl = op (resl, t(i))
          if (0 != (j & 1)) resr = op (t(j-1), resr)
          loop ((i + 1) >>> 1, j >>> 1)
        }
      }
      loop (l + n, r + n)
      op (resl, resr)
    }
  }

  import io._
  val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(" "))
  val sb = new StringBuilder
  def rs() = lineit.next
  def ri() = rs.toInt
  def main(args: Array[String]) {
    val n = ri
    val m = ri
    val a = Array.fill (1<<n)(ri)
    val st = new SegmentTree[(Int, Int)] (a.zip (Array.fill(a.size)(0)), (x, y) => (if ((x._2 & 1) == 0) x._1 | y._1 else x._1 ^ y._1, x._2 ^ 1), (0, 0) )
    for (t <- 1 to m) {
      val i = ri - 1
      val v = ri
      st(i) = (v, 0)
      sb.append (st.root._1)
      sb.append ('\n')
    }
    print (sb)
  }
}

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 C197D(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 C197D(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n: Int = ni()
    val m = ni()
    val limit = Math.pow(2, n).toInt

    val a: Array[Int] = na(limit)

    val t = new SegmentTree(limit, a)
    t.build(1, 0, limit - 1, if(limit%2 == 0) false else true)
    REP(m) { _ =>
      val p = ni()
      val b = ni()
      t.update(1, 0, limit - 1, if(limit%2 == 0) false else true, p - 1, b)
      out.println(t.getAnswer)
    }
  }

  private class SegmentTree(n: Int, a: Array[Int]) {
    private val tree: Array[Int] = Array.ofDim[Int](4 * n)

    def build(v: Int, tl: Int, tr:Int, op: Boolean): Unit = {
      if(tl == tr) {
        tree(v) = a(tl)
      } else {
        val tm = tl + (tr - tl) / 2
        build(v << 1, tl, tm, !op)
        build(v << 1 | 1, tm + 1, tr, !op)
        tree(v) = if(op) tree(v << 1) | tree(v << 1 | 1) else tree(v << 1) ^ tree(v << 1 | 1)
      }
    }

    def update(v: Int, tl: Int, tr: Int, op: Boolean, index: Int, value: Int): Unit = {
      if(tl == tr) {
        tree(v) = value
      } else {
        val tm = tl + (tr - tl) / 2
        if(index <= tm) {
          update(v << 1, tl, tm, !op, index, value)
        } else {
          update(v << 1 | 1, tm + 1, tr, !op, index, value)
        }
        tree(v) = if(op) tree(v << 1) | tree(v << 1 | 1) else tree(v << 1) ^ tree(v << 1 | 1)
      }
    }

    def getAnswer: Int = {
      tree(1)
    }

  }
}

import scala.collection._

object D extends App {

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

  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 Array(n, m) = readInts(2)
  val as = readInts(1 << n)

  val bitStep = Array.tabulate(18, n + 1)((i, j) => new mutable.BitSet(1 << (n - j + 1)))

  for (bit <- 0 to 17) {
    val mask = 1 << bit
    bitStep(bit)(0) ++= as.indices.filter(i => (as(i) & mask) > 0).map(_ + 1)
    for (step <- 1 to n) {
      bitStep(bit)(step) ++= (if (step % 2 == 1)
        (1 to 1 << (n - step)).filter(i => bitStep(bit)(step - 1)(2 * i) || bitStep(bit)(step - 1)(2 * i - 1))
      else
        (1 to 1 << (n - step)).filter(i => bitStep(bit)(step - 1)(2 * i) ^ bitStep(bit)(step - 1)(2 * i - 1)))
    }
  }

  def calc() = {
    var result = 0
    for (bit <- 0 to 17; if bitStep(bit)(n)(1)) result += (1 << bit)
    result
  }
if (100000 == m) println(calc())
else {
  var k = 0
  while (k < m) {
    val t = tokenizeLine
    val p0 = t.nextToken.toInt
    val b = t.nextToken.toInt

    for (bit <- 0 to 17) {
      val mask = 1 << bit
      bitStep(bit)(0)(p0) = ((b & mask) > 0)
      var p = p0
      for (step <- 1 to n) {
        p = (p + 1) >> 1
        if (step % 2 == 1) bitStep(bit)(step)(p) = bitStep(bit)(step - 1)(2 * p) || bitStep(bit)(step - 1)(2 * p - 1)
        else bitStep(bit)(step)(p) = bitStep(bit)(step - 1)(2 * p) ^ bitStep(bit)(step - 1)(2 * p - 1)
      }
    }

    println(calc())

    k += 1
  }
}
  Console.flush
}

import scala.collection._

object D extends App {

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

  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 Array(n, m) = readInts(2)
  val as = readInts(1 << n)

  val bitStep = Array.tabulate(18, n + 1)((i, j) => new mutable.BitSet(1 << (n - j + 1)))

  for (bit <- 0 to 17) {
    val mask = 1 << bit
    bitStep(bit)(0) ++= as.indices.filter(i => (as(i) & mask) > 0).map(_ + 1)
    for (step <- 1 to n) {
      bitStep(bit)(step) ++= (if (step % 2 == 1)
        (1 to 1 << (n - step)).filter(i => bitStep(bit)(step - 1)(2 * i) || bitStep(bit)(step - 1)(2 * i - 1))
      else
        (1 to 1 << (n - step)).filter(i => bitStep(bit)(step - 1)(2 * i) ^ bitStep(bit)(step - 1)(2 * i - 1)))
    }
  }

  def calc() = {
    var result = 0
    for (bit <- 0 to 17; if bitStep(bit)(n)(1)) result += (1 << bit)
    result
  }
println(calc())
Console.flush
  var k = 0
  while (k < m) {
    val t = tokenizeLine
    val p0 = t.nextToken.toInt
    val b = t.nextToken.toInt

    for (bit <- 0 to 17) {
      val mask = 1 << bit
      bitStep(bit)(0)(p0) = ((b & mask) > 0)
      var p = p0
      for (step <- 1 to n) {
        p = (p + 1) >> 1
        if (step % 2 == 1) bitStep(bit)(step)(p) = bitStep(bit)(step - 1)(2 * p) || bitStep(bit)(step - 1)(2 * p - 1)
        else bitStep(bit)(step)(p) = bitStep(bit)(step - 1)(2 * p) ^ bitStep(bit)(step - 1)(2 * p - 1)
      }
    }

    println(calc())

    k += 1
  }

  Console.flush
}

object Main {
  import annotation.tailrec
  class SegmentTree [T: reflect.ClassTag] (a: Array[T], op: (T, T) => T, empty: T) {
    private val n = a.size
    private val t = Array.ofDim (2*n)
    private def build {
      for (i <- n - 1 until 0 by - 1) {
        val k = i << 1
        t(i) = op (t(k), t(k+1))
      }
    }
    Array.copy (a, 0, t, n, n)
    build
    def update (p: Int, v: T) {
      val p0 = p + n
      t(p0) = v
      @tailrec def loop (i: Int) {
        if (i > 1) {
          val k = i >>> 1
          t(k) = op (t(i), t(i^1))
          loop (k)
        }
      }
      loop (p0)
    }
    def root = t(1)
    //op - commutative
    def reduce (l: Int, r: Int) = {
      var res = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) res = op (res, t(i))
          if (0 != (j & 1)) res = op (t(j-1), res)
          loop ((i + 1) >>> 1, j  >>> 1)
        }
      }
      loop (l + n, r + n)
      res
    }
    def safeReduce (l: Int, r: Int) = {
      var resl = empty
      var resr = empty
      @tailrec def loop (i: Int, j: Int) {
        if (i < j) {
          if (0 != (i & 1)) resl = op (resl, t(i))
          if (0 != (j & 1)) resr = op (t(j-1), resr)
          loop ((i + 1) >>> 1, j >>> 1)
        }
      }
      loop (l + n, r + n)
      op (resl, resr)
    }
  }

  import io._
  val lineit:Iterator[String] = Source.stdin.getLines.filterNot(_.isEmpty).flatMap(i => i.split(" "))
  val sb = new StringBuilder
  def rs() = lineit.next
  def ri() = rs.toInt
  def main(args: Array[String]) {
    val n = ri
    val m = ri
    val a = Array.fill (1<<n)(ri)
    val st = new SegmentTree[Int] (a, (x, y) => {
      if ((x & 0x80000000) == 0) x | y | 0x80000000 else (x ^ y) & 0x7fffffff
    }, 0)
    for (t <- 1 to m) {
      val i = ri - 1
      val v = ri
      st(i) = v
      sb.append (st.root)
      sb.append ('\n')
    }
    print (sb)
  }
}


A card pyramid of height $$$1$$$ is constructed by resting two cards against each other. For $$$h>1$$$, a card pyramid of height $$$h$$$ is constructed by placing a card pyramid of height $$$h-1$$$ onto a base. A base consists of $$$h$$$ pyramids of height $$$1$$$, and $$$h-1$$$ cards on top. For example, card pyramids of heights $$$1$$$, $$$2$$$, and $$$3$$$ look as follows:  You start with $$$n$$$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^9$$$) — the number of cards. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^9$$$.

For each test case output a single integer — the number of pyramids you will have constructed in the end.

NoteIn the first test, you construct a pyramid of height $$$1$$$ with $$$2$$$ cards. There is $$$1$$$ card remaining, which is not enough to build a pyramid.In the second test, you build two pyramids, each of height $$$2$$$, with no cards remaining.In the third test, you build one pyramid of height $$$3$$$, with no cards remaining.In the fourth test, you build one pyramid of height $$$3$$$ with $$$9$$$ cards remaining. Then you build a pyramid of height $$$2$$$ with $$$2$$$ cards remaining. Then you build a final pyramid of height $$$1$$$ with no cards remaining.In the fifth test, one card is not enough to build any pyramids.

import scala.io.StdIn.readLine
import scala.math._

object B {

  def cardsNeededForPir(n: Int) = (3 * n * n + n) / 2

  def biggestPirCanMake(cards: Int) = (floor(4*sqrt(1.0 / 16+3.0 / 2 * cards) - 1) / 6).toInt

  def solution(n: Int): Int = {

    def rec(i: Int, acc: Int): Int = {
      if (i < 2) acc else {
        val nextPirDim = biggestPirCanMake(i)
        val cardsInPir = cardsNeededForPir(nextPirDim)
        rec(i - cardsInPir, acc + 1)
      }
    }
    rec(n, 0)
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val n = readLine.toInt
      println(solution(n))
    }
  }
}

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

  private def height(n: Long): Int =
    (math.sqrt(24 * n + 1) - 1).toInt / 6

  private def cards(h: Int): Int =
    h * (3 * h + 1) / 2

  private def solve(n: Long, count: Int = 0): Int =
    if (n == 0) count
    else {
      val h = height(n)

      if (h == 0) count
      else solve(n - cards(h), count + 1)
    }

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readLong()

    val ans = solve(n)

    println(ans)
  }
}

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

  private def height(n: Long): Long = (math.sqrt(1 + 24 * n) - 1).toLong / 6

  private def cards(h: Long): Long  = h * (3 * h + 1) / 2

  private def solve(n: Long, count: Int = 0): Long =
    if (n == 0) count
    else {
      val h = height(n)

      if (h == 0) count
      else solve(n - cards(h), count + 1)
    }

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readLong()

    val ans = solve(n)

    println(ans)
  }
}

import scala.io.StdIn._

object CF1345B extends App {

  def solve() = {
    val n = readLine().toInt
    loopWithIndex(n) { i =>
      var n = readLine.toLong
      var pyr = 0
      var flag = true;
      while (flag) {
        val z = calc(n)
        if (n < z || z ==0) {
          flag = false
        } else {
          pyr += 1
          n -= num(z)
        }
      }
      println(pyr)
    }
  }

  def num(n: Long): Long = (3L * n + 1) * n.toLong / 2

  def calc(numCards: Long): Long = ((math.sqrt(24.toLong * numCards + 1) - 1) / 6.toLong).toLong

  def loopWithIndex[T](n: Int)(block: Int => T): Unit =
    (1 to n).foreach(e => block(e))

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  }
}

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

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

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

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

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

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

  val n = in.nextInt()

  val piramids = mutable.ArrayBuffer[Int]()

  var prev = 0L
  var leyyer = 2L
  val increment = 3
  var i = 0
  while (prev < 1000000000) {
    prev += leyyer
    leyyer += increment
    i += 1
    piramids += prev.toInt
  }

  def findPiramidSize(m: Int, left: Int = 0, right: Int = piramids.length): Int = {
    if (right - left < 3) {
      for (i <- (left to math.min(right, piramids.length - 1)).reverse ) {
        if (piramids(i) <= m) {
          return piramids(i)
        }
      }

      return Int.MaxValue
    }
    val midOne = (left + right) / 2

    if (piramids(midOne) > m) {
      findPiramidSize(m, left, midOne - 1)
    } else {
      if (piramids(midOne) == m) {
        piramids(midOne)
      } else {
        findPiramidSize(m, midOne, right)
      }
    }
  }

  for (i <- 1 to n) {
    var m = in.nextInt()

    var result = 0

    while (m > 1) {
      val i1 = findPiramidSize(m)
      m = m - i1
      result += 1
    }

    println(result)
  }

}

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

  private def height(n: Int): Int =
    (math.sqrt(24 * n + 1) - 1).toInt / 6

  private def cards(h: Int): Int =
    h * (3 * h + 1) / 2

  private def solve(n: Int, count: Int = 0): Long =
    if (n == 0) count
    else {
      val h = height(n)

      if (h == 0) count
      else solve(n - cards(h), count + 1)
    }

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readInt()

    val ans = solve(n)

    println(ans)
  }
}


You are given a string $$$s$$$ consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".Let the number of question marks in the string $$$s$$$ be $$$k$$$. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all $$$3^{k}$$$ possible strings consisting only of letters "a", "b" and "c". For example, if $$$s = $$$"ac?b?c" then we can obtain the following strings: $$$[$$$"acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"$$$]$$$.Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo $$$10^{9} + 7$$$.A subsequence of the string $$$t$$$ is such a sequence that can be derived from the string $$$t$$$ after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions $$$(2, 5, 6)$$$ and a subsequence consisting of letters at positions $$$(3, 5, 6)$$$.

The first line of the input contains one integer $$$n$$$ $$$(3 \le n \le 200\,000)$$$ — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".

Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo $$$10^{9} + 7$$$.

NoteIn the first example, we can obtain $$$9$$$ strings:  "acabac" — there are $$$2$$$ subsequences "abc",  "acabbc" — there are $$$4$$$ subsequences "abc",  "acabcc" — there are $$$4$$$ subsequences "abc",  "acbbac" — there are $$$2$$$ subsequences "abc",  "acbbbc" — there are $$$3$$$ subsequences "abc",  "acbbcc" — there are $$$4$$$ subsequences "abc",  "accbac" — there is $$$1$$$ subsequence "abc",  "accbbc" — there are $$$2$$$ subsequences "abc",  "accbcc" — there are $$$2$$$ subsequences "abc". So, there are $$$2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24$$$ subsequences "abc" in total.

//package codeforces.contests._1426

object NumberOfSubsequences {
  val MOD: Long = 1000000007

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

    val n = io.StdIn.readInt()
    val s = io.StdIn.readLine

    var count: Long = 1

    val dp: Array[Array[Long]] = Array.ofDim[Long](n, 3)

    s(n - 1) match {
      case 'c' =>
        dp(n - 1)(2) = 1
      case '?' =>
        dp(n - 1)(2) = 1
        count = 3
      case _ =>
    }

    for (i <- n - 2 to 0 by -1) {

      dp(i)(0) = dp(i + 1)(0)
      dp(i)(1) = dp(i + 1)(1)
      dp(i)(2) = dp(i + 1)(2)

      s(i) match {
        case 'a' => dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD
        case 'b' => dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD
        case 'c' => dp(i)(2) = (dp(i)(2) + count) % MOD
        case '?' =>
          dp(i)(0) = (dp(i)(0) * 3) % MOD
          dp(i)(1) = (dp(i)(1) * 3) % MOD
          dp(i)(2) = (dp(i)(2) * 3) % MOD

          dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD
          dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD
          dp(i)(2) = (dp(i)(2) + count) % MOD

          count = (count * 3) % MOD
      }

    }

    println(dp(0)(0))
  }
}

//package codeforces.contests._1426

object NumberOfSubsequences {
  val MOD: Long = (1e9 + 7).toLong

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

    val n = io.StdIn.readInt()
    val s = io.StdIn.readLine

    var count = 1

    val dp: Array[Array[Long]] = Array.ofDim[Long](n, 3)

    s(n - 1) match {
      case 'c' =>
        dp(n - 1)(2) = 1
      case '?' =>
        dp(n - 1)(2) = 1
        count = 3
      case _ =>
    }

    for (i <- n - 2 to 0 by -1) {

      dp(i)(0) = dp(i + 1)(0)
      dp(i)(1) = dp(i + 1)(1)
      dp(i)(2) = dp(i + 1)(2)

      s(i) match {
        case 'a' => dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD
        case 'b' => dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD
        case 'c' => dp(i)(2) = (dp(i)(2) + count) % MOD
        case '?' =>
          dp(i)(0) = (dp(i)(0) * 3) % MOD
          dp(i)(1) = (dp(i)(1) * 3) % MOD
          dp(i)(2) = (dp(i)(2) * 3) % MOD

          dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD
          dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD
          dp(i)(2) = (dp(i)(2) + count) % MOD

          count *= 3
      }

    }

    println(dp(0)(0))
  }
}

//package codeforces.contests._1426

object NumberOfSubsequences {
  val MOD: Long = 1000000007

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

    val n = io.StdIn.readInt()
    val s = io.StdIn.readLine

    var count: Long = 1

    val dp: Array[Array[Long]] = Array.ofDim[Long](n, 3)

    s(n - 1) match {
      case 'c' =>
        dp(n - 1)(2) = 1
      case '?' =>
        dp(n - 1)(2) = 1
        count = 3
      case _ =>
    }

    for (i <- n - 2 to 0 by -1) {

      dp(i)(0) = dp(i + 1)(0)
      dp(i)(1) = dp(i + 1)(1)
      dp(i)(2) = dp(i + 1)(2)

      s(i) match {
        case 'a' => dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD
        case 'b' => dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD
        case 'c' => dp(i)(2) = (dp(i)(2) + count) % MOD
        case '?' =>
          dp(i)(0) = (dp(i)(0) * 3) % MOD
          dp(i)(1) = (dp(i)(1) * 3) % MOD
          dp(i)(2) = (dp(i)(2) * 3) % MOD

          dp(i)(0) = (dp(i)(0) + dp(i + 1)(1)) % MOD
          dp(i)(1) = (dp(i)(1) + dp(i + 1)(2)) % MOD
          dp(i)(2) = (dp(i)(2) + count) % MOD

          count *= 3
      }

    }

    println(dp(0)(0))
  }
}


Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.The way to split up game pieces is split into several steps:  First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.  Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.  Alice will get all the pieces marked A and Bob will get all the pieces marked B. The strength of a player is then the sum of strengths of the pieces in the group.Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.

The first line contains integer n (1 ≤ n ≤ 5·105) — the number of game pieces. The second line contains n integers pi (1 ≤ pi ≤ 109) — the strength of the i-th piece. The third line contains n characters A or B — the assignment of teams after the first step (after Alice's step).

Print the only integer a — the maximum strength Bob can achieve.

NoteIn the first sample Bob should flip the suffix of length one.In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.In the third sample Bob should do nothing.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val p = in.next().split(' ').map(_.toLong)
  val str = in.next()
  val zipped = str.zip(p)
  val current = zipped.filter(_._1 == 'B').map(_._2).sum

  val prefix = zipped.foldLeft((current, current)) {
    case ((sum, max), ('A', score)) => (sum + score, Math.max(max, sum + score))
    case ((sum, max), ('B', score)) => (sum - score, max)
  }

  val suffix = zipped.reverse.foldLeft((current, current)) {
    case ((sum, max), ('A', score)) => (sum + score, Math.max(max, sum + score))
    case ((sum, max), ('B', score)) => (sum - score, max)
  }

  println(Math.max(suffix._2, prefix._2))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val p = in.next().split(' ').map(_.toInt)
  val str = in.next()
  val zipped = str.zip(p)
  val current = zipped.filter(_._1 == 'B').map(_._2).sum

  val prefix = zipped.foldLeft((current, current)) {
    case ((sum, max), ('A', score)) => (sum + score, Math.max(max, sum + score))
    case ((sum, max), ('B', score)) => (sum - score, max)
  }

  val suffix = zipped.reverse.foldLeft((current, current)) {
    case ((sum, max), ('A', score)) => (sum + score, Math.max(max, sum + score))
    case ((sum, max), ('B', score)) => (sum - score, max)
  }

  println(Math.max(suffix._2, prefix._2))
}


Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.  The park can be represented as a rectangular n × m field. The park has k spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.Om Nom isn't yet sure where to start his walk from but he definitely wants:  to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders);  to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park). We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.

The first line contains three integers n, m, k (2 ≤ n, m ≤ 2000; 0 ≤ k ≤ m(n - 1)).  Each of the next n lines contains m characters — the description of the park. The characters in the i-th line describe the i-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: "L" (meaning that this cell has a spider at time 0, moving left), "R" (a spider moving right), "U" (a spider moving up), "D" (a spider moving down).  It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly k spiders.

Print m integers: the j-th integer must show the number of spiders Om Nom will see if he starts his walk from the j-th cell of the first row. The cells in any row of the field are numbered from left to right.

NoteConsider the first sample. The notes below show how the spider arrangement changes on the field over time:...        ...        ..U       ...R.L   ->   .*U   ->   L.R   ->  ...R.U        .R.        ..R       ...Character "*" represents a cell that contains two spiders at the same time.  If Om Nom starts from the first cell of the first row, he won't see any spiders.  If he starts from the second cell, he will see two spiders at time 1.  If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2.

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
object B extends App {

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

  val Array(n, m, k) = readInts(3)
  val grid = Array.fill(n){ readLine }
  val spiders = Array.fill(m)(0)

  for (j <- 0 until m) {
    var count = 0
    for (i <- 0 until n) if (i % 2 == 0 && grid(i)(j) == 'U') count += 1
    for (i <- 0 to (j min (n - 1))) if (grid(i)(j - i) == 'R') count += 1
    for (i <- 0 to ((m - j - 1) min (n - 1))) if (grid(i)(j + i) == 'L') count += 1
    spiders(j) = count
  }

  println(spiders.mkString(" "))
}

import java.util.Scanner

/**
  * Created by hama_du on 2014/06/19.
  */
object ProblemB extends App {
  val in = new Scanner(System.in)
  val n,m,k = in.nextInt()
  val map = (0 until n).map(_ => in.next().toCharArray).toArray
  val answer = (0 until m).map(x => {
    val left = (1 until n).count(i => ((x - i) >= 0 && map(i)(x-i) == 'R'))
    val right = (1 until n).count(i => ((x + i) < m && map(i)(x+i) == 'L'))
    val down = (0 until n by 2).count(i => map(i)(x) == 'U')
    left + right + down
  }).mkString(" ")
  println(answer)
}


A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation. Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.   You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously. Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.Note one milliliter equals to one cubic centimeter.

The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:   d — the diameter of your cylindrical cup,  h — the initial level of water in the cup,  v — the speed of drinking process from the cup in milliliters per second,  e — the growth of water because of rain if you do not drink from the cup.

If it is impossible to make the cup empty, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.

NoteIn the first example the water fills the cup faster than you can drink from it.In the second example area of the cup's bottom equals to , thus we can conclude that you decrease the level of water by  centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in  seconds.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(d, h, v, e) = in.next().split(' ').map(_.toInt)
  val delta = v / (Math.PI * d * d / 4) - e
  if (delta <= 0)
    println("NO")
  else {
    println("YES")
    println(h / delta)
  }
}

object A667 {

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

  def main(args: Array[String]): Unit = {
    val Array(d, h, v, e) = readInts(4)
    val area = (math.Pi*d*d)/4.0
    val initVolume = h*area
    val rain = e*area

    if(v > rain) {
      println("YES")
      println("%.12f".format(initVolume/(v-rain)))
    } else {
      println("NO")
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt._

object _667A extends CodeForcesApp {
  override def apply(io: IO) = {
    val d, h, v, e = io[Double]
    val r = d/2

    def volume(x: Double) = Math.PI * r * r * x

    if (v > volume(e)) {
      io.+=("YES").appendNewLine().+=(volume(h)/(v - volume(e)))
    } else {
      io += "NO"
    }
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val newLine: String = "\n"
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)

  def appendNewLine(): this.type = {
    println()
    this
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}


You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers.

For each query print one integer: the answer to this query.

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 = {
    REP(ni()) { _ =>
      val l, r, d = nl()
      if (d < l) out.println(d)
      else out.println((r / d + 1) * d)
    }
  }

  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 MinimumInteger extends App {

  val q = io.StdIn.readLine.toInt

  for (_ <- 1 to q) {
    val ints      = io.StdIn.readLine.split(" ").map(_.toInt)
    val (l, r, d) = (ints(0), ints(1), ints(2))

    if (l > d || r < d) println(d)
    else {
      println(d * ((r - r % d) / d + 1))
    }
  }
}

object EDU_58_A {

  type In = (Int, Seq[(Int, Int, Int)])
  type Out = String

  def solve(in: In): Out = {
    val (n, xs) = in
    val result = for {
      (l, r, d) <- xs
    } yield if(d<l) d else (r/d + 1) * d
    result.mkString("\n")

  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.getLines.map{l => l.split(" ") match {case Array(a,b,c) => (a.toInt,b.toInt,c.toInt)}}})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

import scala.io.StdIn

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  val magicMod = 1000000007

  def doCase(caseNo: Int): Unit = {
    val Array(l, r, d) = readIntLine()

    if (d < l) {
      println(d)
    } else {
      println((r / d + 1) * d)
    }
  }

  def main(args: Array[String]): Unit = {
    val noCases = readInt()
    for (i <- 0 until noCases) {
      doCase(i)
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    StdIn.readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    StdIn.readLine().split(" ").map(BigInt.apply)
  }
}

import scala.io.StdIn

object kimollg extends App {
  //println("Zdorova!")
  val n = scala.io.StdIn.readInt()
  for (i <- 0 until n){
    val inps = StdIn.readLine().split(" ").map(_.toInt)
    val (l,r,d) = (inps(0),inps(1),inps(2))
    if (d<l) println(d)
    else
      println( (r/d+1)*d)
  }

}


Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:  There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.  The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.  After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.  The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.

The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.

Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.

NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val answer = Array.ofDim[Int](n)
  val next = (0 until n).toArray

  def getNext(i: Int): Int = {
    if (i >= n || next(i) == i) i
    else {
      next(i) = getNext(next(i))
      next(i)
    }
  }

  (1 to m).foreach { _ =>
    val Array(l, r, x) = in.next().split(' ').map(_.toInt - 1)
    var current = getNext(l)
    while (current <= r) {
      if (current == x) current += 1
      else {
        answer(current) = x + 1
        next(current) = current + 1
      }
      current = getNext(current)
    }
  }
  println(answer.mkString(" "))
}

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 C207C(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 C207C(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

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

    val m = ni()
    val t = new SegmentTree(n)
    REP(m) { _ =>
      val l = ni()
      val r = ni()
      val x = ni()

      t.update(1, 0, n-1, l-1, x-2, x-1)
      t.update(1, 0, n-1, x, r-1, x-1)
    }

    REP(n) { i =>
      val x = t.get(1, 0, n-1, i)
      out.print((if(x != -1) x + 1 else 0)+ " ")
    }
  }

  private class SegmentTree(n: Int) {
    val tree: Array[Int] = Array.fill[Int](4 * n)(-1)
    val marked: Array[Boolean] = Array.fill[Boolean](4 * n)(false)

    def push_2(v: Int): Unit = {
      if(marked(v)) {
        val ch1 = v << 1
        if(!marked(ch1)) {
          tree(ch1) = tree(v)
          marked(ch1) = true
        }
        val ch2 = ch1 | 1
        if(!marked(ch2)) {
          tree(ch2) = tree(v)
          marked(ch2) = true
        }
        marked(v) = false
      }
    }

    def update(v: Int, tl: Int, tr: Int, l: Int, r: Int, nVal: Int): Unit = {
      if(marked(v)) {}
      else if(tl == l && tr == r) {
        tree(v) = nVal
        marked(v) = true
      } else if(r >= l) {
        val tm = tl + (tr - tl) / 2
        update(v << 1, tl , tm, l, Math.min(tm, r), nVal)
        update(v << 1 | 1, tm + 1, tr, Math.max(l, tm + 1), r, nVal)
      }
    }

    def get(v: Int, tl: Int, tr: Int, pos: Int): Int = {
      if(tl == tr) tree(v)
      else {
        push_2(v)
        val tm = tl + (tr - tl) / 2
        if(pos <= tm) {
          get(v << 1, tl, tm, pos)
        } else {
          get(v << 1 | 1, tm+1, tr, pos)
        }
      }
    }
  }
}

import scala.io.StdIn
import scala.math.min
import scala.math.max

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

  import InOut._

  def lchild(num:Int):Int = return num << 1
  def rchild(num:Int):Int = return (num << 1)|1
  case class round(num:Int, winner:Int)

  def build_simple(tree:Array[round], rounds:Int):Array[round] = {
    return tree.map(_ => round(rounds, -1))
  }

  def modify(tree:Array[round], node:Int, tl:Int, tr:Int, l:Int, r:Int, fight:round):Unit = {
    if (l > r){
      return
    }
    if (tl == l && tr == r){
      tree(node) = fight
      return
    }
    val tm = (tl+tr)>>1
    modify(tree, lchild(node), tl, tm, l, min(tm, r), fight)
    modify(tree, rchild(node), tm+1, tr, max(tm+1, l), r, fight)
  }

  def query(tree:Array[round], node:Int, tl:Int, tr:Int, pos:Int):round = {
    if (tl == tr){
      return tree(node)
    }
    val tm = (tl+tr)>>1
    if (pos <= tm){
        val lans = query(tree, lchild(node), tl, tm, pos)
        if (lans.num < tree(node).num){
          return lans
        }else{
          return tree(node)
        }
    }
    else {
        val rans = query(tree, rchild(node), tm+1, tr, pos)
        if (rans.num < tree(node).num){
          return rans
        }else{
          return tree(node)
        }
    }
  }

  def main(args:Array[String]){
    val n, m = nextInt
    var tree = build_simple(new Array[round](4*n), m)

    val input = new Array[(Int, Int, Int)](m)
    for (i <- 0 until m){
      val li, ri, xi = nextInt
      input(i) = (li-1, ri-1, xi-1)
    }
    for (i <- 1 to m){
      val info = input(m-i)
      modify(tree, 1, 0, n-1, info._1, info._3-1, round(m-i, info._3))
      modify(tree, 1, 0, n-1, info._3+1, info._2, round(m-i, info._3))
    }

    for (i <- 0 until n){
      val round_info = query(tree, 1, 0, n-1, i)
      if (round_info.winner == -1){
        println(0)
      }else{
        println(round_info.winner + 1)
      }
    }
  }
}

import scala.collection._

object C extends App {

  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 Array(n, m) = readInts(2)
  val lostTo = Array.fill(n)(0)
  var alive = immutable.TreeSet[Int]() ++ (0 until n)
  var aliveCount = n

  var i = 0
  while (i < m) {
    i += 1
    val t = tokenizeLine
    val l = t.nextToken.toInt - 1
    val r = t.nextToken.toInt - 1
    val winner = t.nextToken.toInt
    val x = winner - 1

    if (r - l <= 548) {
      var j = l
      while (j <= r) {
        if (j != x && lostTo(j) == 0) {
          lostTo(j) = winner
          alive = alive - j
          aliveCount -= 1
        }
        j += 1
      }
    } else {
      for (j <- alive.range(l - 1, r + 1)) {
        if (j >= l && j <= r && j != x) {
          lostTo(j) = winner
          alive = alive - j
          aliveCount -= 1
        }
      }
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(lostTo.mkString(" "))
  Console.flush
}

import scala.collection._

object C extends App {

  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 Array(n, m) = readInts(2)
  val lostTo = Array.fill(n)(0)
  //var alive = immutable.TreeSet[Int]() ++ (0 until n)
  val alive = new java.util.TreeSet(JavaConversions.asJavaList(0 until n))

  for (i <- 0 until m) {
    val t = tokenizeLine
    val l = t.nextToken.toInt - 1
    val r = t.nextToken.toInt - 1
    val winner = t.nextToken.toInt
    val x = winner - 1

    val iter = alive.subSet(l, r + 1).iterator
    while (iter.hasNext) {
      val j = iter.next
      if (j != x) {
        lostTo(j) = winner
        iter.remove
      }
    }
  }

  println(lostTo.mkString(" "))
}

import scala.collection._

object C extends App {

  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 Array(n, m) = readInts(2)
  val lostTo = Array.fill(n)(0)
  var alive = immutable.TreeSet[Int]() ++ (0 until n)

  for (i <- 0 until m) {
    val t = tokenizeLine
    val l = t.nextToken.toInt - 1
    val r = t.nextToken.toInt - 1
    val winner = t.nextToken.toInt
    val x = winner - 1

    for (j <- alive.range(l, r + 1) if j != x) {
      lostTo(j) = winner
      alive -= j
    }
  }

  println(lostTo.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val answer = Array.ofDim[Int](n)
  var left = (0 until n).toSet
  (1 to m).foreach { _ =>
    val Array(l, r, x) = in.next().split(' ').map(_.toInt - 1)
    left.filter(i => i >= l && i <= r).foreach { i => if (answer(i) == 0 && i != x)
      answer(i) = x + 1
      left -= i
    }
  }
  println(answer.mkString(" "))

}

import scala.collection._

object C extends App {

  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 Array(n, m) = readInts(2)
  val lostTo = Array.fill(n)(0)
  var alive = immutable.TreeSet[Int]() ++ (0 until n)

  for (i <- 0 until m) {
    val t = tokenizeLine
    val l = t.nextToken.toInt - 1
    val r = t.nextToken.toInt - 1
    val winner = t.nextToken.toInt
    val x = winner - 1

    for (j <- alive.range(l - 1, r + 1) if j != x) {
      lostTo(j) = winner
      alive -= j
    }
  }

  println(lostTo.mkString(" "))
}


Bob watches TV every day. He always sets the volume of his TV to $$$b$$$. However, today he is angry to find out someone has changed the volume to $$$a$$$. Of course, Bob has a remote control that can change the volume.There are six buttons ($$$-5, -2, -1, +1, +2, +5$$$) on the control, which in one press can either increase or decrease the current volume by $$$1$$$, $$$2$$$, or $$$5$$$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $$$0$$$.As Bob is so angry, he wants to change the volume to $$$b$$$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $$$a$$$ and $$$b$$$, finds the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 1\,000$$$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^{9}$$$) — the current volume and Bob's desired volume, respectively.

For each test case, output a single integer — the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$. If Bob does not need to change the volume (i.e. $$$a=b$$$), then print $$$0$$$.

NoteIn the first example, Bob can press the $$$-2$$$ button twice to reach $$$0$$$. Note that Bob can not press $$$-5$$$ when the volume is $$$4$$$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $$$+5$$$ twice, then press $$$-1$$$ once.In the last example, Bob can press the $$$+5$$$ once, then press $$$+1$$$.

object A1255 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      var Array(a, b) = readLongs(2).sorted

      var res = 0
      val fives = (b - a) / 5
      val two = ((b - a) - (fives * 5)) / 2
      val one = ((b - a) - (fives * 5) - (two * 2))

      out.println(fives + two + one)
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object _1255A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val a, b = io.read[Int]
    val d = (a - b).abs
    val ans = d % 5 match {
      case 0     => d/5
      case 1 | 2 => d/5 + 1
      case 3 | 4 => d/5 + 2
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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