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

object _699A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    val dir = read[String]
    val pos = read[Vector, Long](n)

    val collisions = dir.zip(pos).sliding(2) collect {
      case Seq(('R', p1), ('L', p2)) => (p2 - p1)/2
    }

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

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  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 = write(obj mkString separator)

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

object CF699A{
import scala.io.StdIn.{
    readLine,
    readInt}
import scala.math.min

    val INF:Int = 1000000100
    def dist(pos1:(Int, Char), pos2:(Int, Char)): Int = {
        var (d1,r1) = pos1;
        var (d2,r2) = pos2;
        if(r1=='R' && r2=='L') (d2-d1)/2;
        else INF
    }
    def main(args: Array[String]){
        var n:Int = readInt()
        var dir: String = readLine()
        var arr: Array[Int] = readLine().split(' ') map Integer.parseInt
        var pos = (arr zip dir).sorted

        var minTime: Int = INF;
        (0 until n-1).foreach(i => minTime = min(minTime, dist(pos(i), pos(i+1))));
        // println(pos.mkString)
        if (minTime == INF) println(-1)
        else println(minTime)
    }
}

object Main extends App {
  val n = scala.io.StdIn.readInt()
  val directions = scala.io.StdIn.readLine()
  val positions = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val values = for(i <- (0 until n - 1) if (directions(i) =='R' && directions(i + 1) == 'L')) yield (positions(i + 1) - positions(i)) / 2
  val answer = if (values.isEmpty) -1 else values.min
  println(answer)
}

/**
  * Created by allen on 16-7-22.
  */

import scala.io._
object main {
  def calTime(x:(Char, Int), y:(Char, Int)): Int = {
    if(x._1 != 'R' || y._1 != 'L') Int.MaxValue
    else math.abs(y._2 - x._2) / 2
  }

  def lt(x: ((Char, Int), (Char, Int)), y: ((Char, Int), (Char, Int))): Boolean =
    calTime(x._1, x._2) < calTime(y._1, y._2)

  def main(args: Array[String])= {
    val N = StdIn.readInt()
    val InpStr = StdIn.readLine()
    val InpNum = StdIn.readLine().split(' ').map(x => x.toInt).toSeq
    val SN = InpStr zip InpNum
    val pro = SN.zip(SN.drop(1))
    val tm = pro.foldLeft(Int.MaxValue) ((x, y) => math.min(x, calTime(y._1, y._2)))
    if(N == 1 || tm == Int.MaxValue) println(-1)
    else println(tm)
  }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val directions = lines.next()
  val positions = lines.next().split(' ').map(_.toInt)
  val join = positions.zip(directions)
  val res = join.sliding(2).foldLeft(Int.MaxValue) {
    case (min, Array((p1, 'R'), (p2, 'L'))) => Math.min(min, (p2 - p1) / 2)
    case (min, _) => Math.min(min, min)
  }

  println(if (res == Int.MaxValue) -1 else res)
}

object A699 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val dir = read
    val pos = readInts(n)
    if(dir.contains("RL")) {
      var res = Integer.MAX_VALUE
      for(i <- 0 until n-1) {
        if(dir(i) == 'R' && dir(i+1) == 'L') {
          res = math.min(res, (pos(i+1)-pos(i))/2)
        }
      }
      println(res)
    } else {
      println("-1")
    }
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

    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.util.control.Breaks._

object main extends App{
  val n = readInt
  val s = readLine
  var x = readLine.split(" ").map(_.toInt)
  println(List.range(0, x.length - 1).foldLeft(-1)((res: Int, i: Int) => {
  	var newRes = res
  	if (s(i) == 'R' && s(i+1) == 'L') {
  		val nRes = (x(i+1) - x(i)) / 2
  		if (res == -1 || res > nRes) {
  			newRes = nRes
  		}
  	}
  	newRes
  }))
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val directions = lines.next()
  val positions = lines.next().split(' ').map(_.toInt)
  val join = positions.zip(directions)
  val left = join.filter(_._2 == 'L').map(_._1).sorted.toList
  val right = join.filter(_._2 == 'R').map(_._1).sorted.toList

  def solution(left: List[Int], right: List[Int], soFar: Int = Int.MaxValue): Int = {
    if (left.isEmpty || right.isEmpty)
      if (soFar == Int.MaxValue) -1 else soFar
    else if (right.head > left.head)
      solution(left.tail, right, soFar)
    else
      solution(left.tail, right.tail, Math.min(soFar, (left.head - right.head) / 2))
  }
  println(solution(left, right))

}

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

object _699A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    val dir = read[String]
    val pos = read[Vector, Long](n)

    val collisions = dir.zip(pos).grouped(2) collect {
      case Seq(('R', p1), ('L', p2)) => (p2 - p1)/2
    }

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

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  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 = write(obj mkString separator)

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


object A extends App {
  val (n) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ans = a.zipWithIndex.groupBy(_._1).maxBy { case (_, seq) =>
    (seq.size, -seq.map(_._2).max)
  }._1

  println(ans)
}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 29 Jun 2016
 */
object A637 extends App {

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val map: mutable.HashMap[Int, (Int, Int)] = mutable.HashMap.empty[Int, (Int, Int)]
    for (i <- 0 until n) {
      if (!map.contains(a(i))) {
        map += (a(i) -> (0, 0))
      }
      val currentTuple = map(a(i))
      map += (a(i) -> (currentTuple._1 + 1, i + 1))
    }
    var max = 0
    var min = Integer.MAX_VALUE
    var id = 0
    map.foreach((f :(Int, (Int, Int))) => {
      if (f._2._1 > max) {
        max = f._2._1
        min = f._2._2
        id = f._1
      } else if (f._2._1 == max && f._2._2 < min) {
        min = f._2._2
        id = f._1
      }
    })

    println(id)
  }

  solve()

}

import scala.collection.mutable
object A extends App{
  val (like) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val photoNumb = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val indexArray = mutable.HashMap[Int, Int]()
  var maxID: Int = 0
  var otvet:Int =0
  photoNumb.foreach(x => {
    indexArray.put(x, indexArray.getOrElse(x, 0) + 1)
    if (indexArray(x) > maxID) {
      maxID = indexArray(x)
      otvet = x
    }
  })
  println(otvet)
}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.io.Codec

/**
  * @author itegulov
  */
object A extends App {

  import scala.collection.mutable.{Map => MMap}

  val in: Scanner = new Scanner(System.in)
  val out: PrintWriter = new PrintWriter(System.out)

  val map: MMap[Int, (Int, Int)] = MMap()

  val n = in.nextInt()

  for (i <- 1 to n) {
    val liked = in.nextInt()
    map(liked) = (map.getOrElse(liked, (0, 0))._1 + 1, i)
  }

  val answer = map.fold((-1, (0, -1)))((p1, p2) => if (p1._2._1 > p2._2._1 || p1._2._1 == p2._2._1 && p1._2._2 < p2._2._2) p1 else p2)
  out.println(answer._1)

  in.close()
  out.close()

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine())
      .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val sum = data.groupBy(i => i).map(i => i._1 -> i._2.length)
  val max = sum.maxBy(_._2)._2
  val filtered = sum.filter(i => i._2 == max).keySet
  data.filter(filtered.contains).reverse.distinct.reverse.find(filtered.contains).foreach(println)
}


object B1144Policarp extends App{
  import scala.io.StdIn.{readInt, readLine}
  val _ = readInt
  val arr = readLine.split(' ').map(_.toInt).toList.sorted
  val odd = arr filter {_ % 2 == 1}
  val even = arr filter {_ % 2 == 0}
  val forDrop = math.min(odd.length, even.length) + 1
  println(odd.dropRight(forDrop).sum + even.dropRight(forDrop).sum)
}

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

  override def apply(io: IO): io.type = {
    val nums = io.read[Seq[Int]]
    val (odd, even) = nums.sorted(desc[Int]).partition(_ % 2 == 1)
    val len = odd.length min even.length
    val ans = Seq(odd, even).map(_.drop(len + 1).sum).sum
    io.write(ans)
  }

  def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
}
/****************************[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()
}
/***********************************[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")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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
      }
    }
  }
}

object B {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val arr0 = stdin.readLine().trim.split(" ").map(_.toInt).toList
    val arr = arr0.groupBy(_ % 2 == 1)
    if (arr.size > 1){
      val even = arr(false).sorted.reverse
      val odd = arr(true).sorted.reverse
      val ans = if (math.abs(even.length-odd.length)<=1) 0
      else if (even.length > odd.length){
        even.drop(odd.length+1).sum
      } else {
        odd.drop(even.length+1).sum
      }
      println(ans)
    } else {
      println(arr0.sum-arr0.max)
    }

  }
}

object B {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val arr0 = stdin.readLine().trim.split(" ").map(_.toInt).toList
    val arr = arr0.groupBy(_ % 2 == 1)
    if (arr.size > 1){
      val even = arr(false).sorted
      val odd = arr(true).sorted
      val ans = if (math.abs(even.length-odd.length)<=1) 0
      else if (even.length > odd.length){
        even.drop(odd.length+1).sum
      } else {
        odd.drop(even.length+1).sum
      }
      println(ans)
    } else {
      println(arr0.sum-arr0.max)
    }

  }
}

object B {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val arr0 = stdin.readLine().trim.split(" ").map(_.toInt).toList
    val arr = arr0.groupBy(_ % 2 == 1)
    if (arr.size > 1){
      val even = arr(false).sorted
      val odd = arr(true).sorted
      val ans = if (even.length > odd.length){
        even.drop(odd.length+1).sum
      } else if (even.length < odd.length){
        odd.drop(even.length+1).sum
      } else 0
      println(ans)
    } else {
      println(arr0.sum-arr0.max)
    }

  }
}


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

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


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

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

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


/**
 * 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)
}


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

}

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

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


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

}