//package codeblocks

import java.util.Scanner
import scala.math._
object cf441B {

	val sc = new Scanner(System.in)
	def main(args : Array[String]) : Unit = {
		val n,v = sc.nextInt
		var a = new Array[Long](3002)
		for(i <- 1 to n) a(sc.nextInt)+=sc.nextInt
		var counts:Long = 0
		for(i <-1 to 3001){
			val today =min(v, a(i)+a(i-1))
			counts+=today
			a(i) = if(today!=v) 0 else min(a(i),a(i)+a(i-1)-v)
		}
		println(counts)
	}

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, v) = in.next().split(' ').map(_.toInt)
  val data = Array.ofDim[Int](3001)
  (0 until n).foreach { _ =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
    data(a - 1) += b
  }
  val res = data.foldLeft((0, 0)) {
    case((soFar, fromPrev), el) if (fromPrev + el) <= v => (soFar + fromPrev + el, 0)
    case((soFar, fromPrev), el) if fromPrev >= v => (soFar + v, el)
    case((soFar, fromPrev), el) => (soFar + v, el + fromPrev - v)
  }._1
  println(res)
}

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

object B extends App {

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

  val Array(n, v) = readInts(2)
  val day1 = Array.fill(3002)(0)
  val day2 = Array.fill(3002)(0)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    day1(a - 1) += b
    day2(a) += b
  }

  var sum = 0
  var prevDay1take = 0
  for (i <- 0 to 3001) {
	val day2take = (day2(i) - prevDay1take) min v max 0
	val day1take = day1(i) min (v - day2take)
	prevDay1take = day1take
	//println(day1take, day2take)
	sum += day1take + day2take
  }

  println(sum)
}

object Bnew {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var ans = new Array[Long](3002)

    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      ans(x) += y
      }
    var cnt = ans(0)
    for (i <- 1 to 3001){
        var minn = min(v, (ans(i)+ans(i-1)))
    	cnt += minn
    	ans(i) = max(0, ans(i) - max(0,
    	    minn -ans(i-1)))
    }

    println(cnt)
  }

}

/**
 * Created by slie742 on 9/09/2015.
 */

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

import Math.abs
import Math.max
import Math.min

object ValeraFruits {

  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def count(garden: Map[Int,Int], v: Int) : Int = {
    val maxDay = garden.keys.max + 1
    def go(day: Int, leftFromPrev: Int, total: Int) : Int = {
      if (day > maxDay) total
      else {
        val harvested = leftFromPrev + min(v-leftFromPrev, garden.getOrElse(day,0))
        go(day + 1,min(v,garden.getOrElse(day,0) - (harvested-leftFromPrev))
          , total + harvested)
      }
    }
    go(1, 0, 0)
  }

  def main(args: Array[String]) {
    val (n,v) = readTuple()
    val garden = for {
      i <- 1 to n
      (a,b) = readTuple()
    } yield (a,b)
    val gardenGrouped = garden.groupBy{ case (a,b) => a}.mapValues( l => l.map(_._2).sum)
    println(count(gardenGrouped,v))
  }

}

import java.util.Scanner

object cf441B {

	val sc = new Scanner(System.in)
	def main(args : Array[String]) : Unit = {
		val n,v = sc.nextInt
		var arr = ( for(i <- 1 to n) yield (sc.nextInt,sc.nextInt)).toArray
	//	arr sortBy (_._1) foreach(println )
		var yetCollect = 0
		var sumCollect = 0
		for(i <- 1 to n+1){
			i match {
				case 1 => {
					//第一天只能采第一天的水果,yetCollect保存的为前一天所摘的数量
					if(v>=arr(i-1)._2){sumCollect+=arr(i-1)._2;yetCollect=arr(i-1)._2}
					else {sumCollect+=v;yetCollect=v}
				}
				case x => {
					if(x<=n){
						if(yetCollect == arr(i-2)._2){
							if(v>=arr(i-1)._2){sumCollect+=arr(i-1)._2;yetCollect=arr(i-1)._2}
							else {sumCollect+=v;yetCollect=v}
						}
						else{
							if(v>=arr(i-2)._2-yetCollect){
								yetCollect=arr(i-2)._2-yetCollect
								sumCollect+=yetCollect
							}
							else{
								yetCollect=v
								sumCollect+=yetCollect
							}

							if(v-yetCollect >0){
								if(v-yetCollect >= arr(i-1)._2){
									yetCollect=arr(i-1)._2
									sumCollect+=yetCollect}
								else {sumCollect+=v-yetCollect;yetCollect=v-yetCollect}
							}
							else
								yetCollect = 0

						}

					}
					else{
						if(yetCollect != arr(i-2)._2){
								if(v>=arr(i-2)._2-yetCollect){
									yetCollect=arr(i-2)._2-yetCollect
									sumCollect+=yetCollect
								}
								else{
									yetCollect=v
									sumCollect+=yetCollect
								}

						}
					}
				}
			}
		}
		println(sumCollect)
	}

}

object Bnew {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](3002)
    var minn = 30000
    var maxx = 0
    var cnt = 0
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      ans(x) += y
      minn = min(minn,x)
      maxx = max(maxx,x)
    }
    var bl = false;
    for (i <- minn to maxx){
      if (ans(i)>0){
        if (ans(i+1)==0){
            if (!bl)
        	cnt += min(2*v,ans(i))
        	else cnt += min(v,ans(i))
        	bl = false
        }
        else {
          if (!bl){
        	cnt += min(2*v,ans(i))
        	if (ans(i)<2*v){
        	  var coef= min(2*v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
        	}
          }
          else {cnt += min(v,ans(i))
            if (ans(i)<v){
              var coef= min(v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
            }
          }
          bl = true
        }
      }
//      println(cnt)
    }
    println(cnt)
  }

}

object b {
  import scala.math._

  def sort(xs: Array[Int],ys: Array[Int]) {
		def swap(i: Int, j: Int) {
		val t = xs(i); xs(i) = xs(j); xs(j) = t
		}
		def swap2(i: Int, j: Int) {
		val t = ys(i); ys(i) = ys(j); ys(j) = t
		}
		def sort1(l: Int, r: Int) {
		val pivot = xs((l + r) / 2)
		var i = l; var j = r
		while (i <= j) {
		while (xs(i) < pivot) i += 1
		while (xs(j) > pivot) j -= 1
		if (i <= j) {
		swap(i, j)
		swap2(i, j)
		i += 1
		j -= 1
		}
		}
		if (l < j) sort1(l, j)
		if (j < r) sort1(i, r)
		}
		sort1(0, xs.length - 2)
		}

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](n+1)
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      a(i) = x
      b(i) = y
    }
//    for (i <- 0 until n-1)
//      for (j <- i+1 until n)
//        if (a(i)>a(j)){
//          var t = a(i)
//          a(i) = a(j)
//          a(j) = t
//          t = b(i)
//          b(i) = b(j)
//          b(j) = t
//        }
    sort(a,b)
   ans(0) = min(b(0),v)
   b(0) -= ans(0)
   for (i <- 1 to n){
     if (a(i)-a(i-1)>1){
       ans(i-1) += min(v,b(i-1))
       b(i-1) -= ans(i-1)
       ans(i) += min(v,b(i))
       b(i) -= ans(i)
     }
     else{
     ans(i) = min(v,b(i)+b(i-1))
     if (ans(i) > b(i-1)){
       b(i) -= ans(i) - b(i-1)
       b(i-1) = 0
     }else {b(i-1) -= ans(i)}
     }
     ans(i) += ans(i-1)
//     println(ans(i))
   }

   println(ans(n))
  }

}

object b {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](n+1)
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      a(i) = x
      b(i) = y
    }
    for (i <- 0 until n-1)
      for (j <- i+1 until n)
        if (a(i)>a(j)){
          var t = a(i)
          a(i) = a(j)
          a(j) = t
          t = b(i)
          b(i) = b(j)
          b(j) = t
        }
   ans(0) = min(b(0),v)
   b(0) -= ans(0)
   for (i <- 1 to n){
     ans(i) = min(v,b(i)+b(i-1))
     if (ans(i) > b(i-1)){
       b(i) -= ans(i) - b(i-1)
       b(i-1) = 0
     }else {b(i-1) -= ans(i)}
     ans(i) += ans(i-1)
//     println(ans(i))
   }

   println(ans(n))
  }

}

object b {
  import scala.math._

  def sort(xs: Array[Int],ys: Array[Int]) {
		def swap(i: Int, j: Int) {
		val t = xs(i); xs(i) = xs(j); xs(j) = t
		}
		def swap2(i: Int, j: Int) {
		val t = ys(i); ys(i) = ys(j); ys(j) = t
		}
		def sort1(l: Int, r: Int) {
		val pivot = xs((l + r) / 2)
		var i = l; var j = r
		while (i <= j) {
		while (xs(i) < pivot) i += 1
		while (xs(j) > pivot) j -= 1
		if (i <= j) {
		swap(i, j)
		swap2(i, j)
		i += 1
		j -= 1
		}
		}
		if (l < j) sort1(l, j)
		if (j < r) sort1(i, r)
		}
		sort1(0, xs.length - 2)
		}

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](n+1)
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      a(i) = x
      b(i) = y
    }
//    for (i <- 0 until n-1)
//      for (j <- i+1 until n)
//        if (a(i)>a(j)){
//          var t = a(i)
//          a(i) = a(j)
//          a(j) = t
//          t = b(i)
//          b(i) = b(j)
//          b(j) = t
//        }
    sort(a,b)
   ans(0) = min(b(0),v)
   b(0) -= ans(0)
   for (i <- 1 to n){
     if (a(i)-a(i-1)>1){
       ans(i-1) += v
       b(i-1) -= v
       ans(i) += v
       b(i) -= v
     }
     else{
     ans(i) = min(v,b(i)+b(i-1))
     if (ans(i) > b(i-1)){
       b(i) -= ans(i) - b(i-1)
       b(i-1) = 0
     }else {b(i-1) -= ans(i)}
     }
     ans(i) += ans(i-1)
//     println(ans(i))
   }

   println(ans(n))
  }

}

object Bnew {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](3002)
    var minn = 30000
    var maxx = 0
    var cnt = 0
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      ans(x) = y
      minn = min(minn,x)
      maxx = max(maxx,x)
    }
    var bl = false;
    for (i <- minn to maxx){
      if (ans(i)>0){
        if (ans(i+1)==0){
            if (!bl)
        	cnt += min(2*v,ans(i))
        	else cnt += min(v,ans(i))
        	bl = false
        }
        else {
          if (!bl){
        	cnt += min(2*v,ans(i))
        	if (ans(i)<2*v){
        	  var coef= min(2*v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
        	}
          }
          else {cnt += min(v,ans(i))
            if (ans(i)<v){
              var coef= min(v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
            }
          }
          bl = true
        }
      }
//      println(cnt)
    }
    println(cnt)
  }

}

object b {
  import scala.math._

  def sort(xs: Array[Int],ys: Array[Int]) {
		def swap(i: Int, j: Int) {
		val t = xs(i); xs(i) = xs(j); xs(j) = t
		}
		def swap2(i: Int, j: Int) {
		val t = ys(i); ys(i) = ys(j); ys(j) = t
		}
		def sort1(l: Int, r: Int) {
		val pivot = xs((l + r) / 2)
		var i = l; var j = r
		while (i <= j) {
		while (xs(i) < pivot) i += 1
		while (xs(j) > pivot) j -= 1
		if (i <= j) {
		swap(i, j)
		swap2(i, j)
		i += 1
		j -= 1
		}
		}
		if (l < j) sort1(l, j)
		if (j < r) sort1(i, r)
		}
		sort1(0, xs.length - 2)
		}

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](n+1)
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      a(i) = x
      b(i) = y
    }
//    for (i <- 0 until n-1)
//      for (j <- i+1 until n)
//        if (a(i)>a(j)){
//          var t = a(i)
//          a(i) = a(j)
//          a(j) = t
//          t = b(i)
//          b(i) = b(j)
//          b(j) = t
//        }
    sort(a,b)
   ans(0) = min(b(0),v)
   b(0) -= ans(0)
   for (i <- 1 to n){
     ans(i) = min(v,b(i)+b(i-1))
     if (ans(i) > b(i-1)){
       b(i) -= ans(i) - b(i-1)
       b(i-1) = 0
     }else {b(i-1) -= ans(i)}
     ans(i) += ans(i-1)
//     println(ans(i))
   }

   println(ans(n))
  }

}

object Bnew {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var ans = new Array[Long](3002)
    var minn = 30000
    var maxx = 0
    var cnt = ans(0)

    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      ans(x) += y
      minn = min(minn,x)
      maxx = max(maxx,x)
    }
    var bl = false;
    for (i <- minn to maxx){
      if (ans(i)>0){
        if (ans(i+1)==0){
            if (!bl)
        	cnt += min(2*v,ans(i))
        	else cnt += min(v,ans(i))
        	bl = false
        }
        else {
          if (!bl){
        	cnt += min(2*v,ans(i))
        	if (ans(i)<2*v){
        	  var coef= min(2*v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
        	}
          }
          else {cnt += min(v,ans(i))
            if (ans(i)<v){
              var coef= min(v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
            }
          }
          bl = true
        }
      }
//      println(cnt)
    }
    println(cnt)
  }

}

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

object B extends App {

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

  val Array(n, v) = readInts(2)
  val day1 = Array.fill(3002)(0)
  val day2 = Array.fill(3002)(0)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    day1(a - 1) += b
    day2(a) += b
  }

  var sum = 0
  var prevDay1take = 0
  for (i <- 0 to n) {
	val day2take = (day2(i) - prevDay1take) min v max 0
	val day1take = day1(i) min (v - day2take)
	prevDay1take = day1take
	//println(day1take, day2take)
	sum += day1take + day2take
  }

  println(sum)
}


object Game123t863C extends App {
  import scala.collection.mutable.ListBuffer
  import scala.collection.mutable

  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val k = in.nextLong()
    val a = in.nextInt()
    val b = in.nextInt()

    val g = new Graph()
    val A = Array.ofDim[Int](5,5)
    val B = Array.ofDim[Int](5,5)
    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      A(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      B(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      val from = Node(i,j)
      val to = Node(A(i)(j),B(i)(j))
      g.addEdge(Edge(from,to))
    }

    val sc = g.findFinalScoreBoard(Node(a,b),k)

    out.println(s"${sc.bob} ${sc.alice}")

  }
  case class Node(a: Int, b: Int)
  case class Edge(from: Node, to: Node)
  case class ScoreBoard(bob: Long, alice: Long, tie: Long){
    def addGame(node: Node): ScoreBoard = {
      node match {
        case Node(3,2) => copy(bob = bob+1)
        case Node(2,1) => copy(bob = bob+1)
        case Node(1,3) => copy(bob = bob+1)
        case Node(2,3) => copy(alice = alice+1)
        case Node(1,2) => copy(alice = alice+1)
        case Node(3,1) => copy(alice = alice+1)
        case _ => copy(tie = tie+1)
      }
    }
    val numGames = bob + alice + tie

    def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)
    def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)
    def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)
  }
  class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){
    def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)
    def step(): Game = {
     new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)
    }
  }

  class Graph(){
    val edges = ListBuffer.empty[Edge]
    def addEdge(edge: Edge): Unit = edges.append(edge)

    private def next(node: Node): Node = {
      edges.find(_.from == node).get.to
    }

    val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]

    def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {
      (1 to gamesLeft).foldLeft(new Game(node,next)){
        case (prevGame,_) => {
          prevGame.step()
        }
      }.currentScore
    }
    def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {
      if(gamesLeft > 0){
        if(mapCycle.contains(node)){
          val optScoreBoard = mapCycle(node)
          optScoreBoard.map{ sc =>
            val cyclesRequired = gamesLeft/sc.numGames
            val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % sc.numGames).toInt

            sc*cyclesRequired + simulateSmall(node,extraGames)
          }.getOrElse{
            ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)
          }
        }else{
          (1 to 15).foldLeft(Option(new Game(node,next))){
            case (Some(prevGame), _) =>
              val currentGame = prevGame.step()
              if(currentGame.nodeToEvaluate == node){
                mapCycle += node -> Some(currentGame.currentScore)
                None
              }else{
                Some(currentGame)
              }
            case (None, _ ) => None
          }
          if(!mapCycle.contains(node)){ // no se encontro ciclo
            mapCycle += node -> None

          }
          findFinalScoreBoard(node,gamesLeft)
        }
      }
      else{
        ScoreBoard(0,0,0)
      }
    }

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

//package edu29

import scala.io.StdIn

object C extends App {
  def readArray = StdIn.readLine().split(" ").map(_.toInt)

  val Array(k, a0, b0) = StdIn.readLine().split(" ").map(_.toLong)
  val alice, bob = Array.fill(3)(readArray)
  def result(i: Int, j: Int) =
    if (i == j) (0L, 0L)
    else if (i - 1 == (j % 3)) (1L, 0L)
    else (0L, 1L)

  def go(a: Int = a0.toInt, b: Int = b0.toInt, seen: Map[(Int, Int), Int] = Map.empty, i: Int = 0): (Seq[(Int, Int)], Int) =
    if (seen.contains((a, b))) (seen.toSeq.sortBy(_._2).map(_._1), seen((a, b)))
    else go(alice(a - 1)(b - 1), bob(a - 1)(b - 1), seen + ((a, b) -> i), i + 1)

  val (full, init) = go()
//  println(full, init)
  val (pref, cycle) = full.map((result _).tupled).splitAt(init)
//  println(pref, cycle)

  def sumPoints(seq: Seq[(Long, Long)]) =
    seq.foldLeft((0L, 0L)) { case ((ap, bp), (a, b)) => (ap + a, bp + b) }

  def mulPoints(a: Long, b: Long)(c: Long) = (a * c, b * c)
  val mulp = (mulPoints _).tupled

  val (ap, bp) =
    if (k <= pref.length) sumPoints(pref.take(k.toInt))
    else {
      val n = k - pref.length
      val prefp = sumPoints(pref)
      val cyclic = mulp(sumPoints(cycle))(n / cycle.length)
      val last = sumPoints(cycle.take((n % cycle.length).toInt))
//      println(pref, cyclic, last)
      sumPoints(Seq(prefp, cyclic, last))
    }

  println(s"$ap $bp")

}

object Game123t863C   extends App {
  import scala.collection.mutable.ListBuffer
  import scala.collection.mutable

  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val k = in.nextLong()
    val a = in.nextInt()
    val b = in.nextInt()

    val g = new Graph()
    val A = Array.ofDim[Int](5,5)
    val B = Array.ofDim[Int](5,5)
    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      A(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      B(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      val from = Node(i,j)
      val to = Node(A(i)(j),B(i)(j))
      g.addEdge(Edge(from,to))
    }

    val sc = g.findFinalScoreBoard(Node(a,b),k)

    out.println(s"${sc.bob} ${sc.alice}")

  }
  case class Node(a: Int, b: Int)
  case class Edge(from: Node, to: Node)
  case class ScoreBoard(bob: Long, alice: Long, tie: Long){
    def addGame(node: Node): ScoreBoard = {
      node match {
        case Node(3,2) => copy(bob = bob+1)
        case Node(2,1) => copy(bob = bob+1)
        case Node(1,3) => copy(bob = bob+1)
        case Node(2,3) => copy(alice = alice+1)
        case Node(1,2) => copy(alice = alice+1)
        case Node(3,1) => copy(alice = alice+1)
        case _ => copy(tie = tie+1)
      }
    }
    val numGames = bob + alice + tie

    def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)
    def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)
    def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)
  }
  class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){
    def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)
    def step(): Game = {
     new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)
    }
  }

  class Graph(){
    val edges = ListBuffer.empty[Edge]
    def addEdge(edge: Edge): Unit = edges.append(edge)

    private def next(node: Node): Node = {
      edges.find(_.from == node).get.to
    }

    val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]

    def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {
      (1 to gamesLeft).foldLeft(new Game(node,next)){
        case (prevGame,_) => {
          prevGame.step()
        }
      }.currentScore
    }
    def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {
      if(mapCycle.contains(node)){
        val optScoreBoard = mapCycle(node)
        optScoreBoard.map{ sc =>
          val cyclesRequired = gamesLeft/sc.numGames
          val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % sc.numGames).toInt

          sc*cyclesRequired + simulateSmall(node,extraGames)
        }.getOrElse{
          ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)
        }
      }else{
        (1 to 15).foldLeft(Option(new Game(node,next))){
          case (Some(prevGame), _) =>
            val currentGame = prevGame.step()
            if(currentGame.nodeToEvaluate == node){
              mapCycle += node -> Some(currentGame.currentScore)
              None
            }else{
              Some(currentGame)
            }
          case (None, _ ) => None
        }
        if(!mapCycle.contains(node)){ // no se encontro ciclo
          mapCycle += node -> None

        }
        findFinalScoreBoard(node,gamesLeft)
      }
    }

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Game123t863C extends App {
  import scala.collection.mutable.ListBuffer
  import scala.collection.mutable

  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val k = in.nextLong()
    val a = in.nextInt()
    val b = in.nextInt()

    val g = new Graph()
    val A = Array.ofDim[Int](5,5)
    val B = Array.ofDim[Int](5,5)
    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      A(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      B(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      val from = Node(i,j)
      val to = Node(A(i)(j),B(i)(j))
      g.addEdge(Edge(from,to))
    }

    val sc = g.findFinalScoreBoard(Node(a,b),k)

    out.println(s"${sc.bob} ${sc.alice}")

  }
  case class Node(a: Int, b: Int)
  case class Edge(from: Node, to: Node)
  case class ScoreBoard(bob: Long, alice: Long, tie: Long){
    def addGame(node: Node): ScoreBoard = {
      node match {
        case Node(3,2) => copy(bob = bob+1)
        case Node(2,1) => copy(bob = bob+1)
        case Node(1,3) => copy(bob = bob+1)
        case Node(2,3) => copy(alice = alice+1)
        case Node(1,2) => copy(alice = alice+1)
        case Node(3,1) => copy(alice = alice+1)
        case _ => copy(tie = tie+1)
      }
    }
    val numGames = bob + alice + tie

    def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)
    def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)
    def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)
  }
  class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){
    def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)
    def step(): Game = {
     new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)
    }
  }

  class Graph(){
    val edges = ListBuffer.empty[Edge]
    def addEdge(edge: Edge): Unit = edges.append(edge)

    private def next(node: Node): Node = {
      edges.find(_.from == node).get.to
    }

    val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]

    def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {
      (1 to gamesLeft).foldLeft(new Game(node,next)){
        case (prevGame,_) => {
          prevGame.step()
        }
      }.currentScore
    }
    def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {
      if(mapCycle.contains(node)){
        val optScoreBoard = mapCycle(node)
        optScoreBoard.map{ sc =>
          val cyclesRequired = gamesLeft/sc.numGames
          val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % cyclesRequired).toInt
          sc*cyclesRequired + simulateSmall(node,extraGames)
        }.getOrElse{
          ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)
        }
      }else{
        (1 to 11).foldLeft(Option(new Game(node,next))){
          case (Some(prevGame), _) =>
            val currentGame = prevGame.step()
            if(currentGame.nodeToEvaluate == node){
              mapCycle += node -> Some(currentGame.currentScore)
              None
            }else{
              Some(prevGame.step())
            }
          case (None, _ ) => None
        }
        if(!mapCycle.contains(node)){ // no se encontro ciclo
          mapCycle += node -> None

        }
        findFinalScoreBoard(node,gamesLeft)
      }
    }

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


object B154 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(n + 1)(false)
    var i = 2
    while (i <= n) {
      if (!isComposite(i)) primes.append(i)
      var j = 0
      var break = false
      while (j < primes.size && i * primes(j) <= n && !break) {
        isComposite(i * primes(j)) = true
        if (i % primes(j) == 0)
          break = true
        j += 1
      }
      i += 1
    }
    val factors = Array.fill(n + 1)(Array.empty[Int])
    i = 0
    while (i <= n) {
      var x = i
      val idxs = ArrayBuffer.empty[Int]
      var j = 0
      while (j < primes.length && primes(j) * primes(j) <= x) {
        if (x % primes(j) == 0) {
          idxs.append(primes(j))
          while (x % primes(j) == 0) x /= primes(j)
        }
        j += 1
      }
      if (x > 1)
        idxs.append(x)
      factors(i) = idxs.toArray
      i += 1
    }

    val arr = Array.fill(n + 1)(-1) // stores number with factor i
    val on = Array.fill(n + 1)(false)
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var break = factors(num).find(i => arr(i) != -1)
          if (break.isDefined) {
            out.println(s"Conflict with ${arr(break.get)}")
          } else {
            var i = 0
            factors(num).foreach(arr(_) = num)
            on(num) = true
            out.println("Success")
          }
        }
      } else {
        if (!on(num)) {
          out.println("Already off")
        } else {
          factors(num).foreach(arr(_) = -1)
          on(num) = false
          out.println("Success")
        }
      }
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B154 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(n + 1)(false)
    var i = 2
    while (i <= n) {
      if (!isComposite(i)) primes.append(i)
      var j = 0
      var break = false
      while (j < primes.size && i * primes(j) <= n && !break) {
        isComposite(i * primes(j)) = true
        if (i % primes(j) == 0)
          break = true
        j += 1
      }
      i += 1
    }
    val factorIndices = Array.fill(n + 1)(Array.empty[Int])
    val poss = cu.Map.empty[Int, Int]
    i = 0
    while (i < primes.length) {
      poss.put(primes(i), i)
      i += 1
    }
    i = 0
    while (i <= n) {
      var x = i
      val idxs = ArrayBuffer.empty[Int]
      var j = 0
      while (j < primes.length && primes(j) * primes(j) <= x) {
        if (x % primes(j) == 0) {
          idxs.append(j)
          while (x % primes(j) == 0) x /= primes(j)
        }
        j += 1
      }
      if (x > 1)
        idxs.append(poss(x))
      factorIndices(i) = idxs.toArray.clone()
      i += 1
    }

    val arr = Array.fill(primes.length)(-1) // stores number with factor i
    val on = Array.fill(n + 1)(false)
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var break = factorIndices(num).find(i => arr(i) != -1)
          if (break.isDefined) {
            out.println(s"Conflict with ${arr(break.get)}")
          } else {
            var i = 0
            factorIndices(num).foreach(arr(_) = num)
            on(num) = true
            out.println("Success")
          }
        }
      } else {
        if (!on(num)) {
          out.println("Already off")
        } else {
          factorIndices(num).foreach(arr(_) = -1)
          on(num) = false
          out.println("Success")
        }
      }
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B154 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(n + 1)(false)
    var i = 2
    while (i <= n) {
      if (!isComposite(i)) primes.append(i)
      var j = 0
      var break = false
      while (j < primes.size && i * primes(j) <= n && !break) {
        isComposite(i * primes(j)) = true
        if (i % primes(j) == 0)
          break = true
        j += 1
      }
      i += 1
    }
    val factors = ArrayBuffer.empty[ArrayBuffer[Int]]
    i = 0
    while (i <= n) {
      var x = i
      val idxs = ArrayBuffer.empty[Int]
      var j = 0
      while (j < primes.length && primes(j) * primes(j) <= x) {
        if (x % primes(j) == 0) {
          idxs.append(primes(j))
          while (x % primes(j) == 0) x /= primes(j)
        }
        j += 1
      }
      if (x > 1)
        idxs.append(x)
      factors.append(idxs)
      i += 1
    }

    val arr = Array.fill(n + 1)(-1) // stores number with factor i
    val on = Array.fill(n + 1)(false)
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var break = factors(num).find(i => arr(i) != -1)
          if (break.isDefined) {
            out.println(s"Conflict with ${arr(break.get)}")
          } else {
            var i = 0
            factors(num).foreach(arr(_) = num)
            on(num) = true
            out.println("Success")
          }
        }
      } else {
        if (!on(num)) {
          out.println("Already off")
        } else {
          factors(num).foreach(arr(_) = -1)
          on(num) = false
          out.println("Success")
        }
      }
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import collection.mutable
import java.io._

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 29.02.12
 * Time: 5:17
 * To change this template use File | Settings | File Templates.
 */
object D {
  def main(args: Array[String]) {
    val Array(colliderCount, requestCount) = readLine split ' ' map (str => str.toInt)
    val colliders: Array[Collider] = Array((0 to colliderCount) map (_ => new Collider): _*)
    val conflicts = new Array[Int](1 + colliderCount)
    val output = new BufferedWriter(new OutputStreamWriter(System.out))
    for (prime <- 2 to colliderCount filter (i => colliders(i).primes == Nil)) {
      for (num <- (prime to colliderCount by prime)) {
        colliders(num).primes ::= prime
      }
    }
    for (i <- (1 to requestCount)) {
      val line = readLine
      val sign = line(0)
      val num = line.split(" ")(1).toInt
      val collider = colliders(num)
      (sign, collider.state) match {
        case ('+', true) => output.write("Already on\n")
        case ('-', false) => output.write("Already off\n")
        case ('+', false) => {
          collider.primes.find(prime => conflicts(prime) > 0) match {
            case Some(prime) => output.write("Conflict with %d\n".format(conflicts(prime)))
            case None => {
              collider.primes.foreach(prime => conflicts(prime) = num)
              collider.state = true
              output.write("Success\n")
            }
          }
        }
        case ('-', true) => {
          collider.primes.foreach(prime => conflicts(prime) = 0)
          collider.state = false
          output.write("Success\n")
        }
      }
    }
    output.flush
  }

  class Collider {
    var primes: List[Int] = Nil
    var state = false
  }

}

import collection.mutable
import java.io._

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 29.02.12
 * Time: 5:17
 * To change this template use File | Settings | File Templates.
 */
object D {
  val output = new BufferedWriter(new OutputStreamWriter(System.out))
  val input = new BufferedReader(new InputStreamReader(System.in))

  def main(args: Array[String]) {
    val Array(colliderCount, requestCount) = input.readLine split ' ' map (str => str.toInt)
    val colliders: Array[Collider] = Array((0 to colliderCount) map (_ => new Collider): _*)
    val conflicts = new Array[Int](1 + colliderCount)

    for (prime <- 2 to colliderCount filter (i => colliders(i).primes == Nil)) {
      for (num <- (prime to colliderCount by prime)) {
        colliders(num).primes ::= prime
      }
    }
    for (i <- (1 to requestCount)) {
      val line = input.readLine
      val sign = line(0)
      val num = line.split(" ")(1).toInt
      val collider = colliders(num)
      (sign, collider.state) match {
        case ('+', true) => output.write("Already on\n")
        case ('-', false) => output.write("Already off\n")
        case ('+', false) => {
          collider.primes.find(prime => conflicts(prime) > 0) match {
            case Some(prime) => output.write("Conflict with %d\n".format(conflicts(prime)))
            case None => {
              collider.primes.foreach(prime => conflicts(prime) = num)
              collider.state = true
              output.write("Success\n")
            }
          }
        }
        case ('-', true) => {
          collider.primes.foreach(prime => conflicts(prime) = 0)
          collider.state = false
          output.write("Success\n")
        }
      }
    }
    output.flush
  }

  class Collider {
    var primes: List[Int] = Nil
    var state = false
  }

}

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import java.io.File
import java.io.BufferedOutputStream
import java.io.PrintWriter

object D {
  object Int {
    def unapply(s: String) : Some[Int] = Some(s.toInt)
  }
  val N = 100001

  val factors = new Array[ListBuffer[Int]](N)
  val active = new Array[Boolean](N)

  factors.indices.foreach(factors(_) = ListBuffer[Int]())

  (2 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))

  val usedBy = new Array[Int](N)

  def main(args: Array[String]): Unit = {
    val output = new PrintWriter(new BufferedOutputStream(System.out, 100000))

    val lines = scala.io.Source.stdin.getLines()
    lines.next()
    lines.foreach( cmd => {
      val s = cmd.split(" ")
      val n = s(1).toInt
      output.println( if (s(0).equals("+")) {
          if (active(n)) "Already on"
          else factors(n).find(usedBy(_) > 0) match { case Some(uf) => "Conflict with " + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; "Success" }
      } else {
          if (!active(n)) "Already off"
          else { factors(n).foreach(usedBy(_) = 0); active(n) = false; "Success" }
     })
    })

    output.close()
}
}

object B154 {

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

  case class Sieve(to: Int) {
    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(to + 1)(false)
    def sieve(): Unit = { // Works in linear time
      for (i <- 2 until to) {
        if (!isComposite(i)) primes.append(i)
        var j = 0
        var break = false
        while (j < primes.size && i * primes(j) < to && !break) {
          isComposite(i * primes(j)) = true
          if (i % primes(j) == 0)
            break = true
          j += 1
        }
      }
    }
  }
  val s = Sieve(100000 + 10)
  s.sieve()

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val arr = Array.fill(s.primes.length)(-1)
    val on = cu.Set.empty[Int]
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on.contains(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var bad = -1
          while (bad == -1 && i < arr.length && s.primes(i) <= num) {
            if (num % s.primes(i) == 0) {
              if (arr(i) == -1) {
                arr(i) = num
              } else {
                bad = arr(i)
              }
            }
            i += 1
          }
          if (bad != -1) {
            out.println(s"Conflict with $bad")
          } else {
            on.add(num)
            out.println("Success")
          }
        }
      } else {
        if (!on.contains(num)) {
          out.println("Already off")
        } else {
          var i = 0
          while (i < arr.length && s.primes(i) <= num) {
            if (num % s.primes(i) == 0) {
              arr(i) = -1
            }
            i += 1
          }
          on.remove(num)
          out.println("Success")
        }
      }
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B154 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(n + 1)(false)
    var i = 2
    while (i <= n) {
      if (!isComposite(i)) primes.append(i)
      var j = 0
      var break = false
      while (j < primes.size && i * primes(j) <= n && !break) {
        isComposite(i * primes(j)) = true
        if (i % primes(j) == 0)
          break = true
        j += 1
      }
      i += 1
    }
    val factors = Array.fill(n + 1)(Array.empty[Int])
    i = 0
    while (i <= n) {
      var x = i
      val idxs = ArrayBuffer.empty[Int]
      var j = 0
      while (j < primes.length && primes(j) * primes(j) <= x) {
        if (x % primes(j) == 0) {
          idxs.append(j)
          while (x % primes(j) == 0) x /= primes(j)
        }
        j += 1
      }
      if (x > 1)
        idxs.append(x)
      factors(i) = idxs.toArray.clone()
      i += 1
    }

    val arr = Array.fill(n + 1)(-1) // stores number with factor i
    val on = Array.fill(n + 1)(false)
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var break = factors(num).find(i => arr(i) != -1)
          if (break.isDefined) {
            out.println(s"Conflict with ${arr(break.get)}")
          } else {
            var i = 0
            factors(num).foreach(arr(_) = num)
            on(num) = true
            out.println("Success")
          }
        }
      } else {
        if (!on(num)) {
          out.println("Already off")
        } else {
          factors(num).foreach(arr(_) = -1)
          on(num) = false
          out.println("Success")
        }
      }
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer

object D {
  object Int {
    def unapply(s: String) : Some[Int] = Some(s.toInt)
  }
  val N = 100000

  val factors = new Array[ListBuffer[Int]](N)
  val active = new Array[Boolean](N)

  factors.indices.foreach(factors(_) = ListBuffer[Int]())

  (1 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))

  val usedBy = new Array[Int](10000)

  def main(args: Array[String]): Unit = {
    scala.io.Source.stdin.getLines().toList.tail.foreach( cmd => {
      System.out.println (cmd.split(" ").toList match {
        case "+"::Int(n)::_ =>
          if (active(n)) "Already on"
          else factors(n).find(usedBy(_) > 0) match { case Some(uf) => "Conflict with " + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; "Success" }
        case "-"::Int(n)::_ =>
          if (!active(n)) "Already off"
          else { factors(n).foreach(usedBy(_) = 0); active(n) = false; "Success" }
     })
    })
  }
}

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer

object D {
  object Int {
    def unapply(s: String) : Some[Int] = Some(s.toInt)
  }
  val N = 100000

  val factors = new Array[ListBuffer[Int]](N)
  val active = new Array[Boolean](N)

  factors.indices.foreach(factors(_) = ListBuffer[Int]())

  (2 until N/2).foreach (fc => (fc*2 until N by fc).foreach (factors(_) += fc))

  val usedBy = new Array[Int](10000)

  def main(args: Array[String]): Unit = {
    scala.io.Source.stdin.getLines().toList.tail.foreach( cmd => {
      System.out.println (cmd.split(" ").toList match {
        case "+"::Int(n)::_ =>
          if (active(n)) "Already on"
          else factors(n).find(usedBy(_) > 0) match { case Some(uf) => "Conflict with " + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; "Success" }
        case "-"::Int(n)::_ =>
          if (!active(n)) "Already off"
          else { factors(n).foreach(usedBy(_) = 0); active(n) = false; "Success" }
     })
    })
  }
}

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import java.io.File
import java.io.BufferedOutputStream
import java.io.PrintWriter

object D {
  object Int {
    def unapply(s: String) : Some[Int] = Some(s.toInt)
  }
  val N = 100001

  val factors = new Array[ListBuffer[Int]](N)
  val active = new Array[Boolean](N)

  factors.indices.foreach(factors(_) = ListBuffer[Int]())

  (2 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))

  val usedBy = new Array[Int](N)

  def main(args: Array[String]): Unit = {
    val output = new PrintWriter(new BufferedOutputStream(System.out, 100000))

    val lines = scala.io.Source.stdin.getLines()
    lines.next()
    lines.foreach( cmd => {
      val s = cmd.split(" ")
      val n = s(1).toInt
      output.println( if (s(0).equals("+")) {
          if (active(n)) "Already on"
          else factors(n).find(usedBy(_) > 0) match { case Some(uf) => "Conflict with " + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; "Success" }
      } else {
          if (!active(n)) "Already off"
          else { factors(n).foreach(usedBy(_) = 0); active(n) = false; "Success" }
     })
    })
}
}


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

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val as = nextLongs(n).sorted.reverse
      var res = 0
      var cnt = 0
      for (a <- as) {
        cnt += 1
        if (a * cnt >= x) {
          cnt = 0
          res += 1
        }
      }

      out.println(res)
    }

    out.flush()
  }

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

import scala.io.StdIn._

object C extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val Array(n, x) = readLine().split(" ").map(_.toInt)
    val A           = readLine().split(" ").map(_.toInt).sorted

    var teams   = 0
    var current = 0
    for {
      i <- A.length - 1 to 0 by -1
    } {
      current += 1
      if (A(i) * current >= x) {
        teams += 1
        current = 0
      }
    }
    println(teams)
  }
}

import java.util

object ProblemC extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  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 t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val k = in.nextInt()
    val a = new Array[Int](n)
    for (i <- a.indices) {
      a(i) = in.nextInt()
    }

    util.Arrays.sort(a)

    var result = 0

    var i = a.length
    var count: Long = 0
    while (i > 0) {
      i = i - 1
      count = count + 1
      if (count * a(i) >= k) {
        result = result + 1
        count = 0
      }
    }

    println(result)
  }
}

object C extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, x) = readLine().split(" ").map(_.toInt)
    val an          = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

    val m = an.lastIndexWhere(_ >= x) match {
      case -1 => if (an.head >= x) n else 0
      case i  => i + 1
    }

    val l = an.drop(m).foldLeft((0, 0)) {
      case ((l, r), a) =>
        if ((r + 1) * a >= x) (l + 1, 0)
        else (l, r + 1)
    }._1

    val ans = m + l

    println(ans)
  }
}

object C extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, x) = readLine().split(" ").map(_.toInt)
    val an          = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

    val ans = an
      .foldLeft((0, 0)) {
        case ((count, remains), a) =>
          if (a * (remains + 1) >= x) (count + 1, 0)
          else (count, remains + 1)
      }
      ._1

    println(ans)
  }
}


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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) { i =>
      f(i)
    }
  }
  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 Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

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

    val V = "aiueo"

    REP(math.sqrt(N).toInt, 1) { n =>
      if (N % n == 0) {
        val m = N / n
        if (n >= 5 && m >= 5) {
          REP(n) { i =>
            REP(m) { j =>
              out.print(V((i + j) % 5))
            }
          }
          out.println()

          return
        }
      }
    }

    out.println(-1)
  }
}

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

  override def apply(io: IO): io.type = {
    val k = io.read[Int]
    val vowels = "aeiou"

    val ans = (vowels.length to k).find(i => k%i == 0 && k/i >= vowels.length) match {
      case None => "-1"
      case Some(n) =>
        val m = k/n
        Vector.tabulate(n, m)((i, j) => vowels((i + j)%vowels.length)).map(_.mkString).mkString
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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
      }
    }
  }
}

import scala.math.sqrt
import scala.util.control.Breaks._

object Main extends App {

	def isPrimeNumber (n : Double) : Boolean = {
		var max : Int = sqrt(n).toInt

		for ( i <- 2 to max ) {
			if ( n%i == 0 ) {
				return false
			}
		}

		return true
	}

	var m = Console.readLine
	var n : Int = m.toInt
	var arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')

	if ( isPrimeNumber(n.toDouble) || n < 25 ) {
		println(-1)
		sys.exit(0)
	}

	var row : Int = 5
	var col : Int = 0
	var max : Int = n/5 + 1

	while ( row < max && col == 0) {
		if ( n%row == 0 ) {
			col = n/row - 1
			row -= 1
		} else {
			row += 1
		}
	}

	if ( col < 4 ) {
		println(-1)
		sys.exit(0)
	}

	for ( i <- 0 to row ) {
		for ( j <- 0 to col) {
			print(arrChar((i+j) % 5))
		}
	}

	println()

}

import scala.math.sqrt
import scala.util.control.Breaks._

object Main extends App {

	def isPrimeNumber (n : Double) : Boolean = {
		var max : Int = sqrt(n).toInt

		for ( i <- 2 to max ) {
			if ( n%i == 0 ) {
				return false
			}
		}

		return true
	}

	var m = Console.readLine
	var n : Int = m.toInt
	var arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')

	if ( isPrimeNumber(n.toDouble) || n < 25 ) {
		println(-1)
		sys.exit(0)
	}

	var row : Int = 5
	var col : Int = 0

	while ( col == 0) {
		if ( n%row == 0 ) {
			col = n/row - 1
			row -= 1
		} else {
			row += 1
		}
	}

	for ( i <- 0 to row ) {
		for ( j <- 0 to col) {
			print(arrChar((i+j) % 5))
		}
	}

	println()

}

import scala.math.sqrt
import scala.util.control.Breaks._

object Main extends App {

	def isPrimeNumber (n : Double) : Boolean = {
		var max : Int = sqrt(n).toInt

		for ( i <- 2 to max ) {
			if ( n%i == 0 ) {
				return false
			}
		}

		return true
	}

	var m = Console.readLine
	var n : Int = m.toInt
	var arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')

	if ( isPrimeNumber(n.toDouble) || n < 25 ) {
		println(-1)
		sys.exit(0)
	}

	var row : Int = 5
	var col : Int = 0

	while ( col == 0) {
		if ( n%row == 0 ) {
			col = n/row - 1
			row -= 1
		} else {
			row += 1
		}
	}

	for ( i <- 0 to row ) {
		for ( j <- 0 to col) {
			if ( i < 5 && j < 5) {
				print(arrChar((i+j) % 5))
			} else {
				print('b')
			}
		}
	}

	println()

}

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

  override def apply(io: IO): io.type = {
    val k = io.read[Int]
    val vowels = "aeiou"

    val ans = (vowels.length to k).find(i => k%i == 0 && k/i >= vowels.length) match {
      case None => "-1"
      case _ => Vector.tabulate(k)(i => vowels(i%vowels.length)).mkString
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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 P034A extends App {
  val n = readInt
  val a = readLine.split(' ').map(_.toInt)
  val next = (x: Int) => (x+1) % n
  val b = for (i <- 0 to n-1) yield math.abs(a(i)-a(next(i)))
  val pos = b.indexOf(b min)
  printf("%d %d\n", pos+1, next(pos)+1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val res = data.sliding(2).map(t => Math.abs(t.last - t.head)).zipWithIndex.min
  val firstLast = Math.abs(data.head - data.last)
  if (firstLast > res._1)
    println(s"${res._2 + 1} ${res._2 + 2}")
  else
    println(s"$n 1")
}

object A34 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val heights = readInts(n)
    var x = 0
    var y = heights.length-1
    var max = math.abs(heights(y)-heights(x))
    for(i <- 0 until heights.length-1) {
      if(math.abs(heights(i)-heights(i+1)) < max) {
        x = i
        y = i + 1
        max = math.abs(heights(i)-heights(i+1))
      }
    }
    out.println(s"${x+1} ${y+1}")
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  val d: PartialFunction[List[Int], Int] = { case List(i, j) => (A(i) - A(j)).abs }
  val res = List.tabulate(N + 1)(_ % N).sliding(2).toList.sortBy(d).head.map(_ + 1)

  out.println(res.mkString(" "))
  out.close
}

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

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var arr = readLine.split(" ").zipWithIndex;
    var a = arr.flatMap(x => for (y <- arr if (math.abs(x._2 - y._2) == 1 || math.abs(x._2 - y._2) == n - 1)) yield (x, y));
    var min = a.reduceLeft((a, b) => if (math.abs(a._1._1.toInt - a._2._1.toInt) < math.abs(b._1._1.toInt - b._2._1.toInt)) a else b);
    println((min._1._2 + 1) + " " + (min._2._2 + 1));
  }

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val a1 = a.zipWithIndex
    val a2 = (a1 ++ Seq(a1(0))).sliding(2).map(s => ((s(0)._1 - s(1)._1).abs, (s(0)._2, s(1)._2)))
    val t = a2.toList.sortBy(_._1).apply(0)
    println((t._2._1 + 1) + " " + (t._2._2 + 1))
  }
}


object B extends App {
  import scala.collection.mutable
  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {
      if (arr.length == 1) {
        return true
      }

      var anyExchange = true
      while(anyExchange) {
        anyExchange = false
        for (i <- 0 until arr.length - 1) {
          if (arr(i) > arr(i + 1)) {
            if (ex.contains(i + 1)) {
              val t = arr(i)
              arr(i) = arr(i + 1)
              arr(i + 1) = t
              anyExchange = true
            }
          }
        }
      }

      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          return false
        }
      }
      true
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val (n, m) = (nextInt, nextInt)
      val array = new Array[Int](n)
      val exchangable = new mutable.HashSet[Int]()

      for (i <- 0 until n) {
        array(i) = nextInt
      }
      for (_ <- 0 until m) {
        exchangable.add(nextInt)
      }

      val can = canSort(array, exchangable)
      println(if(can) "YES" else "NO")
    }
  }

}

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val m = ni()

      val a = na(n)
      val p = Array.fill[Int](n+1)(0)
      REP(m) { _ =>
        p(ni()) += 1
      }

      var continue = true

      while (continue) {
        continue = false
        REP(n-1) { i =>
          if(a(i) > a(i+1)) {
            if(p(i+1) > 0) {
              val x = a(i+1)
              a(i+1) = a(i)
              a(i) = x
              continue = true
            }
          }
        }
      }
//      out.println(a.mkString(" "))
      REP(n-1) { i =>
        if(a(i) > a(i+1)) {
          continue = true
        }
      }
      if(continue) out.println("NO")
      else out.println("YES")
    }
  }
}

import scala.collection.mutable

object B extends App {
  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {
      if (arr.length == 1) {
        return true
      }

      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          if (ex.contains(i + 1)) {
            val t = arr(i)
            arr(i) = arr(i + 1)
            arr(i + 1) = t
          } else {
            return false
          }
        }
      }
      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          return false
        }
      }
      true
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val (n, m) = (nextInt, nextInt)
      val array = new Array[Int](n)
      val exchangable = new mutable.HashSet[Int]()

      for (i <- 0 until n) {
        array(i) = nextInt
      }
      for (_ <- 0 until m) {
        exchangable.add(nextInt)
      }

      val can = canSort(array, exchangable)
      println(if(can) "YES" else "NO")
    }
  }

}

import scala.collection.mutable

object B extends App {
  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {
      if (arr.length == 1) {
        return true
      }

      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          if (ex.contains(i + 1)) {
            val t = arr(i)
            arr(i) = arr(i + 1)
            arr(i + 1) = t
          } else {
            return false
          }
        }
      }
      true
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val (n, m) = (nextInt, nextInt)
      val array = new Array[Int](n)
      val exchangable = new mutable.HashSet[Int]()

      for (i <- 0 until n) {
        array(i) = nextInt
      }
      for (_ <- 0 until m) {
        exchangable.add(nextInt)
      }

      val can = canSort(array, exchangable)
      println(if(can) "YES" else "NO")
    }
  }

}

object B extends App {
  import scala.collection.mutable
  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {
      if (arr.length == 1) {
        return true
      }

      var anyExchange = true
      while(anyExchange) {
        for (i <- 0 until arr.length - 1) {
          anyExchange = false
          if (arr(i) > arr(i + 1)) {
            if (ex.contains(i + 1)) {
              val t = arr(i)
              arr(i) = arr(i + 1)
              arr(i + 1) = t
              anyExchange = true
            }
          }
        }
      }

      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          return false
        }
      }
      true
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val (n, m) = (nextInt, nextInt)
      val array = new Array[Int](n)
      val exchangable = new mutable.HashSet[Int]()

      for (i <- 0 until n) {
        array(i) = nextInt
      }
      for (_ <- 0 until m) {
        exchangable.add(nextInt)
      }

      val can = canSort(array, exchangable)
      println(if(can) "YES" else "NO")
    }
  }

}


object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val line = (0 :: lines.next().split(' ').map(_.toInt).reverse.toList).sliding(2).map(_.sum).toList.reverse
  println(line.mkString(" "))
}

object A712 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readLongs(n)
    val res = Array.fill(n)(0L)
    for(i <- in.indices) {
      if(i != n-1) {
        res(i) = in(i) + in(i+1)
      } else {
        res(i) = in(i)
      }
    }
    println(res.mkString(" "))
  }

  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 Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _712A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val bs = read[Vector[Int]] :+ 0
    val as = bs.sliding(2).map(_.sum)

    write(as mkString " ")
  }
}
/****************************[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
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  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)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    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)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  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 toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  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 writeAll(obj: Traversable[Any], separator: String = "\n"): 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
      }
    }
  }
}