Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:  He looks through all the coins from left to right;  If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.  Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.

The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.

Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.

NoteLet's denote as O coin out of circulation, and as X — coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO  →  OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO  →  OXOX  →  OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX  →  OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object D_441_2 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.sa2)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    val pLine = readLine

    val coins = (0 until n).map(x=>pLine.int).toArray

    //---------------------------- parameters reading :end

    val state = Array.fill(n)(false)

//    def count3(arr: Array[Boolean], ind: Int) = {
//      var count = 0
//      var afterGap = false
//      for(i <- (arr.length-1 to 0 by -1) ) {
//        if (afterGap && arr(i)) {
//          count += 1
//        }
//        if (!arr(i)) afterGap = true
//      }
//      count + 1
//    }
//
//    val steps = coins.map{co =>
//      val ind = co-1
//      state(ind) = true
//      debug("coin: " + co + " -> " + state.map(x => if(x) "X" else "O").mkString(""))
//      count3(state, ind)
//    }

    var counts = new Array[Int](n)
    var count = 0
    var readyEnd = n
    val state2 = Array.fill(n)(false)
    for(i <- (0 until n)) {
//      if (coins(i) == 11) {
//        println("kmkm")
//      }
      val ind = coins(i) -1
      state2(ind) = true
      debug("coin: " + coins(i) + " -> " + state2.map(x => if(x) "X" else "O").mkString(""))
      if (coins(i) == readyEnd) {
        readyEnd -= 1
        while (readyEnd > 0 && state2(readyEnd-1)) {
          readyEnd -= 1
        }
      }
      count += 1

      val ready = n - readyEnd
      debug(s"count:$count ready:$ready")
      counts(i) = (count - ready)  + 1
    }

    val steps2 = counts

    val res = (1 +: steps2).mkString(" ")

    outLn(res)
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
4
1 3 4 2
"""

val sa2 = """
8
6 8 3 4 7 2 1 5
"""

val sa3 = """
"""

val t4 = """
11
10 8 9 4 6 3 5 1 11 7 2
"""
//  10 8 9 4 6 3 5 1 11 7 2
// 1 2 3 4 5 6 7 8 9 6 2 1
// 1 2 3 4 5 6 7 8 9 6 2 1 my
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object D_441_2 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.sa2)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    val pLine = readLine

    val coins = (0 until n).map(x=>pLine.int).toArray

    //---------------------------- parameters reading :end

    val state = Array.fill(n)(false)

    def count(arr: Array[Boolean], ind: Int) = {
      var rightGaps = 0
      var max = 0
      var i = arr.length-1
      var xGroup = true
      var groupSum = 0
      while (i > -1) {
        val coin = arr(i)
        if (coin) {
          if (xGroup) {
            groupSum += 1
          } else {
            groupSum += rightGaps
          }
        } else {
          if (xGroup) {
            if (groupSum > max && rightGaps > 0) max = groupSum
            rightGaps += 1
          } else {
            //nothing
          }
          groupSum = 0
        }
        xGroup = coin
        i -= 1
      }
      if (xGroup && groupSum > max && rightGaps > 0) max = groupSum
      max + 1
    }

    val steps = coins.map{co =>
      val ind = co-1
      state(ind) = true
      debug("coin: " + co + " -> " + state.map(x => if(x) "X" else "O").mkString(""))
      count(state, ind)
    }

    val res = (1 +: steps).mkString(" ")

    outLn(res)
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
4
1 3 4 2
"""

val sa2 = """
8
6 8 3 4 7 2 1 5
"""

val sa3 = """
"""
}

}


Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.What is the maximum number of apples he can collect?

The first line contains one number n (1 ≤ n ≤ 100), the number of apple trees in Lala Land. The following n lines contains two integers each xi, ai ( - 105 ≤ xi ≤ 105, xi ≠ 0, 1 ≤ ai ≤ 105), representing the position of the i-th tree and number of apples on it. It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.

Output the maximum number of apples Amr can collect.

NoteIn the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.In the second sample test the optimal solution is to go left to x =  - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x =  - 2.In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left.

//package c558.a

object Solution extends App {
  import scala.io.StdIn
  val n = StdIn.readInt()
  val (leftTree, rightTree) = (1 to n).map(_ ⇒ {
    val s = StdIn.readLine().split(" ")
    s(0).toInt → s(1).toLong
  }).partition(_._1 > 0)
  @scala.annotation.tailrec
  def eatApples(left: Seq[(Int, Long)], right: Seq[(Int, Long)], applesAcc: Long, direction: String): Long =
    if (direction == "left") {
      left match {
        case Nil ⇒ applesAcc
        case _ ⇒ eatApples(left.tail, right, applesAcc + left.head._2, "right")
      }
    } else {
      right match {
        case Nil ⇒ applesAcc
        case _ ⇒ eatApples(left, right.tail, applesAcc + right.head._2, "left")
      }
    }
  val sortedLeft = leftTree.sortBy(_._1)
  val sortedRight = rightTree.sortBy(_._1 * -1)
  val twoResults = Seq("left", "right").map(eatApples(sortedLeft, sortedRight, 0, _))
  println(scala.math.max(twoResults.head, twoResults.tail.head))
}

import scala.io._
import Array._
import collection.immutable.SortedMap

object lala {
  def main(args: Array[String]) {

    var numberOfTrees: Int = 0
    var walk = 0
    var totalApples = 0

    val line = readInt()
    numberOfTrees = line.toInt

    implicit val Ord = implicitly[Ordering[Int]]

    var field: Map[Int, Int] = Map()
    var fieldPositive: SortedMap[Int, Int] = SortedMap()
    var fieldPositive1: SortedMap[Int, Int] = SortedMap()
    var fieldPositive2: SortedMap[Int, Int] = SortedMap()
    var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative2: SortedMap[Int, Int] = SortedMap()(Ord.reverse)

    for (a <- 0 until numberOfTrees) {
      var temp = new Array[Int](2)
      var line = readLine()

      temp = line.split(" ") map (_.toInt)

      for (b <- 0 until 2) {
        field += (temp(0) -> temp(1))
      }
    }

    for (a <- field) {
      if (a._1 < 0) {
        fieldNegative += (a._1 -> a._2)
      } else {
        fieldPositive += (a._1 -> a._2)
      }
    }

    if (fieldPositive.size == fieldNegative.size) {
      for (i <- fieldPositive) {
        totalApples += i._2
      }
      for (i <- fieldNegative) {
        totalApples += i._2
      }
    }

    if (fieldPositive.size > fieldNegative.size) {

      for (i <- fieldNegative) {
        totalApples += i._2
      }

      fieldPositive1 = fieldPositive.take(fieldNegative.size)

      for (i <- fieldPositive1) {
        totalApples += i._2
      }

      fieldPositive2 = fieldPositive.take(fieldNegative.size + 1)

      totalApples += fieldPositive2.last._2

    }

    if (fieldPositive.size < fieldNegative.size) {

      for (i <- fieldPositive) {
        totalApples += i._2
      }

      fieldNegative1 = fieldNegative.take(fieldPositive.size)

      for (i <- fieldNegative1) {
        totalApples += i._2
      }

      fieldNegative2 = fieldNegative.take(fieldPositive.size + 1)

      totalApples += fieldNegative2.last._2

    }

    println(totalApples)

  }
}

import scala.io._
import Array._
import collection.immutable.SortedMap

object lala {
  def main(args: Array[String]) {

    var numberOfTrees: Int = 0
    var totalApples = 0
    val line = readInt()
    numberOfTrees = line.toInt

    implicit val Ord = implicitly[Ordering[Int]]

    var field: Map[Int, Int] = Map()
    var fieldPositive: SortedMap[Int, Int] = SortedMap()
    var fieldPositive1: SortedMap[Int, Int] = SortedMap()
    var fieldPositive2: SortedMap[Int, Int] = SortedMap()
    var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative2: SortedMap[Int, Int] = SortedMap()(Ord.reverse)

    for (a <- 0 until numberOfTrees) {
      var temp = new Array[Int](2)
      var line = readLine()
      temp = line.split(" ") map (_.toInt)
      for (b <- 0 until 2) {
        field += (temp(0) -> temp(1))
      }
    }

    for (a <- field) {
      if (a._1 < 0) {
        fieldNegative += (a._1 -> a._2)
      } else {
        fieldPositive += (a._1 -> a._2)
      }
    }

    if (fieldPositive.size == fieldNegative.size) {
      totalApples += fieldPositive.foldLeft(0)(_ + _._2)
      totalApples += fieldNegative.foldLeft(0)(_ + _._2)
    }

    if (fieldPositive.size > fieldNegative.size) {
      totalApples += fieldNegative.foldLeft(0)(_ + _._2)
      fieldPositive1 = fieldPositive.take(fieldNegative.size)
      totalApples += fieldPositive1.foldLeft(0)(_ + _._2)
      fieldPositive2 = fieldPositive.take(fieldNegative.size + 1)
      totalApples += fieldPositive2.last._2
    }

    if (fieldPositive.size < fieldNegative.size) {
      totalApples += fieldPositive.foldLeft(0)(_ + _._2)
      fieldNegative1 = fieldNegative.take(fieldPositive.size)
      totalApples += fieldNegative1.foldLeft(0)(_ + _._2)
      fieldNegative2 = fieldNegative.take(fieldPositive.size + 1)
      totalApples += fieldNegative2.last._2
    }
    println(totalApples)
  }
}

import scala.io._
import Array._
import collection.immutable.SortedMap

object lala {
  def main(args: Array[String]) {

    implicit val Ord = implicitly[Ordering[Int]]

    var totalApples = 0
    val numberOfTrees = readInt()
    var field: Map[Int, Int] = Map()
    var fieldPositive: SortedMap[Int, Int] = SortedMap()
    var fieldPositive1: SortedMap[Int, Int] = SortedMap()
    var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)

    for (a <- 0 until numberOfTrees) {
      var temp = new Array[Int](2)
      var line = readLine()
      temp = line.split(" ") map (_.toInt)
      for (b <- 0 until 2) {
        field += (temp(0) -> temp(1))
      }
    }

    for (a <- field) {
      if (a._1 < 0) {
        fieldNegative += (a._1 -> a._2)
      } else {
        fieldPositive += (a._1 -> a._2)
      }
    }

    if (fieldPositive.size == fieldNegative.size) {
      totalApples += fieldPositive.foldLeft(0)(_ + _._2)
      totalApples += fieldNegative.foldLeft(0)(_ + _._2)
    } else if (fieldPositive.size > fieldNegative.size) {
        totalApples += fieldNegative.foldLeft(0)(_ + _._2)
        fieldPositive1 = fieldPositive.take(fieldNegative.size + 1)
        totalApples += fieldPositive1.foldLeft(0)(_ + _._2)
     } else if (fieldPositive.size < fieldNegative.size) {
          totalApples += fieldPositive.foldLeft(0)(_ + _._2)
          fieldNegative1 = fieldNegative.take(fieldPositive.size + 1)
          totalApples += fieldNegative1.foldLeft(0)(_ + _._2)
    }
    println(totalApples)
  }
}

import scala.io.StdIn.readLine
import scala.collection.mutable.PriorityQueue
import scala.annotation.tailrec

// PriorityQueue[Long]()(scala.math.Ordering.Long.reverse)

case class Tree(x : Int, a : Int)

object Main {
  object EnRich {
    implicit class AString(val self : String) extends AnyVal {
      def splitToIntArray = self.split(" ").map(_.toInt)
    }
  }
  import EnRich._
  def main(args : Array[String]) : Unit = {
    val n = readLine.toInt
    val trees = (1 to n).map(_ => {
                               val (x,a) = {
                                 val xa = readLine.splitToIntArray
                                 (xa(0),xa(1))
                               }
                               Tree(x,a)
                             }).toVector
    val left  = trees.filter({case Tree(x,a) => x < 0}).
                      sortBy({case Tree(x,a) => -x})
    val right = trees.filter({case Tree(x,a) => x > 0}).
                      sortBy({case Tree(x,a) => x})
    val m     = left.length min right.length
    val go_l  = left.take(m+1) ++ right.take(m)
    val go_r  = left.take(m)   ++ right.take(m+1)

    val ans1  = go_l.map({case Tree(x,a) => a}).sum
    val ans2  = go_r.map({case Tree(x,a) => a}).sum

    println(ans1 max ans2)
  }
}

object A558 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1))).sortBy(_._1)
    val neg = in.filter(_._1 < 0).map(_._2)
    val pos = in.filter(_._1 > 0).map(_._2)

    if(neg.length > pos.length) {
      println(pos.sum + neg.takeRight(pos.length+1).sum)
    } else {
      println(neg.sum + pos.take(neg.length+1).sum)
    }
  }

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

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

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

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

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

}

import scala.collection.mutable._

object A extends App {
 val apples = new HashMap[Int, Int]()
 val n = readInt
 for(i <- 1 to n) {
  val str = readLine.split(" ").map(_.toInt)
  apples.put(str(0), str(1))
 }
  val pair = apples.groupBy({case (k, v) => k > 0})
                   .map({case (k, v) => (k, v.size)})
  val left  = pair.get(false).getOrElse(0)
  val right = pair.get(true).getOrElse(0)

  var takeLeft, takeRight = 0
  if(left <= right) {
  takeLeft = left
  takeRight = left + 1
  }
  else {
  takeLeft = right + 1
  takeRight = right
  }

  val leftRes = apples.filter({case (k, v) => k < 0}).toList.sortWith((i, j) => i._1 > j._1).take(takeLeft).foldLeft(0)((acc, elem) => acc + elem._2)
  val rightRes = apples.filter({case (k, v) => k > 0}).toList.sortWith((i, j) => i._1 < j._1).take(takeRight).foldLeft(0)( (acc, elem) => acc + elem._2)

  println(leftRes + rightRes)
}

import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
object _558A extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val data = List.fill(n)((nextInt, nextInt))

  def solve(left: List[(Int, Int)], right: List[(Int, Int)]): Int = (left, right) match {
    case (Nil, Nil) => 0
    case (Nil, (_, b) :: _) => b
    case ((_, a) :: _, Nil) => a
    case ((_, a) :: ls, (_, b) :: rs) => a + b + solve(ls, rs)
  }

  val (l, r) = data.sortBy(_._1.abs).partition(_._1 < 0)
  solve(l, r)
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}

import scala.collection.immutable.SortedMap

object LalaProblem {

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

    implicit val Ord = implicitly[Ordering[Int]]

    var listPos: SortedMap[Int, Int] = SortedMap()
    var listNeg: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    val n: Int = readInt()
    var count: Int = 0

    for (x <- 0 until n) {
      var line = readLine()
      var temp: Array[String] = line.split(" ")
      if (temp(0).toInt < 0) {
        listNeg = listNeg ++ converToMap(temp(0), temp(1))
      } else {
        listPos = listPos ++ converToMap(temp(0), temp(1))
      }
    }

    if (listNeg.size == listPos.size) {
      listNeg.keys.foreach { x => count += listNeg(x) }
      listPos.keys.foreach { x => count += listPos(x) }
    } else {
      if (listNeg.size < listPos.size) {
        listNeg.keys.foreach { x => count += listNeg(x) }
        var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      } else {
        listPos.keys.foreach { x => count += listPos(x) }
        var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      }
    }
    println(count)
  }

  def converToMap(x: String, y: String): Map[Int, Int] = {

    val xc: Int = x.toInt
    val yc: Int = y.toInt
    Map(xc -> yc)
  }
}

import scala.io._
import Array._
import collection.immutable.SortedMap
import util.control.Breaks._

object lala {
  def main(args: Array[String]) {

    var numberOfTrees: Int = 0
    var walk = 0
    var totalApples = 0

    val line = readInt()
    numberOfTrees = line.toInt

    implicit val Ord = implicitly[Ordering[Int]]

    var field: Map[Int, Int] = Map()
    var fieldPositive: SortedMap[Int, Int] = SortedMap()
    var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)

    for (a <- 0 until numberOfTrees) {
      var temp = new Array[Int](2)
      var line = readLine()

      temp = line.split(" ") map (_.toInt)

      for (b <- 0 until 2) {
        field += (temp(0) -> temp(1))
      }
    }

    for (a <- field) {
      if (a._1 < 0) {
        fieldNegative += (a._1 -> a._2)
      } else {
        fieldPositive += (a._1 -> a._2)
      }
    }

    breakable {
      for (i <- fieldPositive) {
        if (i._1 == walk + 1) {
          totalApples += i._2
          walk += 1
        } else {
          break
        }
      }
    }

    walk = 0

    breakable {
      for (i <- fieldNegative) {
        if (i._1 == walk - 1) {
          totalApples += i._2
          walk -= 1
        } else {
          break
        }
      }
    }

    println(totalApples)

  }
}

object LalaProblem {

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

    var listPos = List[Int]()
    var listNeg = List[Int]()
    val n: Int = readInt()
    var count: Int = 0
    var xc = 1

    for(x <- 0 until n){
      var line = readLine()
      var temp : Array[String] = line.split(" ")
      if (temp(0).toInt < 0) {
        listNeg = listNeg ::: converToList(temp(0), temp(1))
      }else{
        listPos = listPos ::: converToList(temp(0), temp(1))
      }
    }

    if (listNeg.size == listPos.size) {
      for(x <- 0 until listNeg.size){
        if(x % 2 == 0){
          xc = x
          count += listNeg(xc + 1)
          count += listPos(xc + 1)
        }
      }
    }else{
      if(listNeg.size < listPos.size){
        for(x <- 0 until listNeg.size) {
          if(x % 2 == 0){
            xc = x
            count += listNeg(xc + 1)
            count += listPos(xc + 1)
          }
        }
        count += listPos(listNeg.size + 1)
      }else{
         for(x <- 0 until listPos.size) {
          if(x % 2 == 0){
            xc = x
            count += listNeg(xc + 1)
            count += listPos(xc + 1)
          }
        }
        count += listNeg(listPos.size + 1)
      }
    }
    println(count)
  }

  def converToList(x: String, y: String): List[Int] = {

    val xc: Int = x.toInt
    val yc: Int = y.toInt
    List(xc, yc)
  }
}

import scala.io.StdIn.readLine
import scala.collection.mutable.PriorityQueue
import scala.annotation.tailrec

// PriorityQueue[Long]()(scala.math.Ordering.Long.reverse)

case class Tree(x : Int, a : Int)

object Main {
  object EnRich {
    implicit class AString(val self : String) extends AnyVal {
      def splitToIntArray = self.split(" ").map(_.toInt)
    }
  }
  import EnRich._
  def main(args : Array[String]) : Unit = {
    val n = readLine.toInt
    val trees = (1 to n).map(_ => {
                               val (x,a) = {
                                 val xa = readLine.splitToIntArray
                                 (xa(0),xa(1))
                               }
                               Tree(x,a)
                             }).toVector
    val left  = trees.filter({case Tree(x,a) => x < 0})
    val right = trees.filter({case Tree(x,a) => x > 0})
    val m     = left.length min right.length
    val go_l  = left.take(m+1) ++ right.take(m)
    val go_r  = left.take(m)   ++ right.take(m+1)

    val ans1  = go_l.map({case Tree(x,a) => a}).sum
    val ans2  = go_r.map({case Tree(x,a) => a}).sum

    println(ans1 max ans2)
  }
}

import scala.collection.immutable.SortedMap

object LalaProblem {

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

    implicit val Ord = implicitly[Ordering[Int]]

    var listPos: SortedMap[Int, Int] = SortedMap()
    var listNeg: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    val n: Int = readInt()
    var count: Int = 0

    for (x <- 0 until n) {
      var line = readLine()
      var temp: Array[String] = line.split(" ")
      if (temp(0).toInt < 0) {
        listNeg = listNeg ++ converToMap(temp(0), temp(1))
      } else {
        listPos = listPos ++ converToMap(temp(0), temp(1))
      }
    }

    println(listNeg)
    println(listPos)

    if (listNeg.size == listPos.size) {
      listNeg.keys.foreach { x => count += listNeg(x) }
      listPos.keys.foreach { x => count += listPos(x) }
    } else {
      if (listNeg.size < listPos.size) {
        listNeg.keys.foreach { x => count += listNeg(x) }
        var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      } else {
        listPos.keys.foreach { x => count += listPos(x) }
        var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      }
    }
    println(count)
  }

  def converToMap(x: String, y: String): Map[Int, Int] = {

    val xc: Int = x.toInt
    val yc: Int = y.toInt
    Map(xc -> yc)
  }
}

object LalaProblem {

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

    var listPos: Map[Int, Int] = Map()
    var listNeg: Map[Int, Int] = Map()
    val n: Int = readInt()
    var count: Int = 0

    for (x <- 0 until n) {
      var line = readLine()
      var temp: Array[String] = line.split(" ")
      if (temp(0).toInt < 0) {
        listNeg = listNeg ++ converToMap(temp(0), temp(1))
      } else {
        listPos = listPos ++ converToMap(temp(0), temp(1))
      }
    }
    listNeg.toSeq.sortWith(_._1 > _._1)
    listPos.toSeq.sortWith(_._1 < _._1)

    if (listNeg.size == listPos.size) {
      listNeg.keys.foreach { x => count += listNeg(x) }
      listPos.keys.foreach { x => count += listPos(x) }
    } else {
      if (listNeg.size < listPos.size) {
        listNeg.keys.foreach { x => count += listNeg(x) }
        var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      } else {
        listPos.keys.foreach { x => count += listPos(x) }
        var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      }
    }
    println(count)
  }

  def converToMap(x: String, y: String): Map[Int, Int] = {

    val xc: Int = x.toInt
    val yc: Int = y.toInt
    Map(xc -> yc)
  }
}


As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).

The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.

Print the number of valid sets modulo 1000000007.

NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.

import scala.collection.mutable.ArrayBuilder

object P277D extends App {

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

  val MOD = 1000000007

  val Array(d, n) = readInts(2)
  val as = readInts(n)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  def dfs(origin: Int, u: Int, prev: Int, min: Int, max: Int): Long = {

    var cnt = 1L

    for (v <- adj(u)) if (v != prev && (as(v) > min || (as(v) == min && v > origin)) && as(v) <= max) {
      val cnt2 = dfs(origin, v, u, min, max)
      cnt = cnt * (cnt2 + 1) % MOD
    }

    cnt
  }

  var total = 0L
  for (u <- 0 until n) total += dfs(u, u, -1, as(u), as(u) + d)

  println(total % MOD)
}

import java.util.Scanner
import java.util.Arrays
import java.util.ArrayList

object Solution {
    var MOD = 1000 * 1000 * 1000 + 7
    var d: Integer = null
    var used: Array[Boolean] = null
    var graph: Array[ArrayList[Integer]] = null
    var a: Array[Integer] = null

    def bad(a1: Integer, i1: Integer, a2: Integer, i2: Integer): Boolean = {
	return (a1 < a2 || a1 == a2 && i1 < i2 || a1 - a2 > d)
    }

    def dfs(v: Integer, root: Integer): Long = {
	if (bad(a(v), v, a(root), root))
	    return 1
	used(v) = true
	var res: Long = 1
	var index = 0
	for (index <- 0 until graph(v).size()) {
	    val to = graph(v).get(index)
	    if (!used(to))
		res = res * dfs(to, root) % MOD
	}
	return res + 1
    }

    def main(args: Array[String]) = {
	val in = new Scanner(System.in)
	d = in.nextInt()
	val n = in.nextInt()
	a = new Array(n)
	graph = new Array(n)
	var i = 0
	for (i <- 0 until n) {
	    graph(i) = new ArrayList()
	    a(i) = in.nextInt()
	}
	for (i <- 0 until n - 1) {
	    val from = in.nextInt()
	    val to = in.nextInt()
	    graph(from - 1).add(to - 1)
	    graph(to - 1).add(from - 1)
	}
	var res: Long = 0
	used = new Array(n)
	for (i <- 0 until n) {
	    Arrays.fill(used, false)
	    res = (res + dfs(i, i) - 1 + MOD) % MOD
	}
	println(res)
    }
}


Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.       These subrectangles are not flags.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.

In the only line print the number of subrectangles which form valid flags.

Note  The selected subrectangles are flags in the first example.

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[Int]]): 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, M = ni()
    val g = nm_c(N, M)

    val cum = Array.ofDim[Int](N, M)
    REP(M) { j =>
      REP_r(N) { i =>
        val v = if (i == N - 1) 1
        else {
          if (g(i)(j) == g(i + 1)(j)) cum(i + 1)(j) + 1 else 1
        }
        cum(i)(j) = v
      }
    }

    debugDim(cum)

    var ans = 0L
    REP(N) { i =>
      var j = 0
      while(j < M) {
        var k = j
        val w = cum(i)(j) // １本のstripeの幅
        if (i + w * 3 <= N) {
          val i2 = i + w
          val i3 = i + w * 2
          while (k < M &&
            g(i)(j) == g(i)(k) && cum(i)(k) == w &&
            g(i2)(j) == g(i2)(k) && cum(i2)(k) == w &&
            g(i3)(j) == g(i3)(k) && cum(i3)(k) >= w
          ) {
            k += 1
          }
          val n = k - j
          debug(s"i:$i j:$j k:$k n:$n")
          ans += n.toLong * (n + 1) / 2
        }
        j = max(j + 1, k)
      }
    }

    out.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[Int]]): 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, M = ni()
    val g = nm_c(N, M)

    val cum = Array.ofDim[Int](N, M)
    REP(M) { j =>
      REP_r(N) { i =>
        val v = if (i == N - 1) 1
        else {
          if (g(i)(j) == g(i + 1)(j)) cum(i + 1)(j) + 1 else 1
        }
        cum(i)(j) = v
      }
    }

    debugDim(cum)

    var ans = 0L
    REP(N) { i =>
      var j = 0
      while(j < M) {
        var k = j
        val w = cum(i)(j) // １本のstripeの幅
        if (i + w * 3 <= N) {
          val i2 = i + w
          val i3 = i + w * 2
          while (k < M && cum(i)(k) == w &&
            cum(i2)(k) == w &&
            cum(i3)(k) >= w
          ) {
            k += 1
          }
          val n = k - j
          debug(s"i:$i j:$j k:$k n:$n")
          ans += n.toLong * (n + 1) / 2
        }
        j = max(j + 1, k)
      }
    }

    out.println(ans)
  }
}


One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $$$n$$$ non-negative integers.If there are exactly $$$K$$$ distinct values in the array, then we need $$$k = \lceil \log_{2} K \rceil$$$ bits to store each value. It then takes $$$nk$$$ bits to store the whole file.To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $$$l \le r$$$, and after that all intensity values are changed in the following way: if the intensity value is within the range $$$[l;r]$$$, we don't change it. If it is less than $$$l$$$, we change it to $$$l$$$; if it is greater than $$$r$$$, we change it to $$$r$$$. You can see that we lose some low and some high intensities.Your task is to apply this compression in such a way that the file fits onto a disk of size $$$I$$$ bytes, and the number of changed elements in the array is minimal possible.We remind you that $$$1$$$ byte contains $$$8$$$ bits.$$$k = \lceil log_{2} K \rceil$$$ is the smallest integer such that $$$K \le 2^{k}$$$. In particular, if $$$K = 1$$$, then $$$k = 0$$$.

The first line contains two integers $$$n$$$ and $$$I$$$ ($$$1 \le n \le 4 \cdot 10^{5}$$$, $$$1 \le I \le 10^{8}$$$) — the length of the array and the size of the disk in bytes, respectively. The next line contains $$$n$$$ integers $$$a_{i}$$$ ($$$0 \le a_{i} \le 10^{9}$$$) — the array denoting the sound file.

Print a single integer — the minimal possible number of changed elements.

NoteIn the first example we can choose $$$l=2, r=3$$$. The array becomes 2 2 2 3 3 3, the number of distinct elements is $$$K=2$$$, and the sound file fits onto the disk. Only two values are changed.In the second example the disk is larger, so the initial file fits it and no changes are required.In the third example we have to change both 1s or both 3s.

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, I = ni()
    val A = na(N)
    radixSort(A)
    val seen = mutable.HashSet[Int]()
    REP(N) { i =>
      if (!seen(A(i))) {
        seen += A(i)
      }
    }

    val S = seen.size
    val K = log2_ceil(S)
    var k = K
    while(k.toLong * N > I * 8) {
      k -= 1
    }

    debug(s"k:$k K:$K")

    if (k == K) {
      out.println(0)
    } else {
      val len = 1 << k
      var ans = N
      var l, r = 0
      var cnt = 0

      def next(i: Int): Int = {
        var j = i
        while(j < N && A(i) == A(j)) j += 1
        j
      }

      while(l < N) {
        while(r < N && cnt < len) {
          r = next(r)
          cnt += 1
        }
        val change = N - (r - l)
        debug(s"l:$l r:$r change:$change")
        ans = min(ans, change)
        l = next(l)
        cnt -= 1
      }
      out.println(ans)
    }
  }

  /**
    * log2して小数点切り捨てたもの
    */
  def log2(x: Int): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }

  /**
    * log2の小数点を切り上げたもの
    */
  def log2_ceil(x: Int): Int = {
    assert(x > 0)
    if (x == 1) {
      0
    } else {
      log2(x - 1) + 1
    }
  }

  /**
    * 正の値のみのときだけ
    */
  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(as: Array[Int], n: Int): Array[Int] = {
    val n = as.length
    val xs = Array(as, new Array[Int](n))
    val b = Array.ofDim[Int](65537)

    def step(k: Int, x: Int): Unit = {
      REP(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }
      REP(65536, 1){ i => b(i) += b(i - 1) }
      REP(n){ i =>
        val j = xs(x)(i) >>> k & 0xffff
        xs(x ^ 1)(b(j)) = xs(x)(i)
        b(j) += 1
      }
    }

    step(0, 0)
    java.util.Arrays.fill(b, 0)
    step(16, 1)

    as
  }
}


Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.

For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.

NoteLet's consider the test cases of the example:  $$$n=8$$$, $$$k=3$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$;  during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$.   $$$n=6$$$, $$$k=6$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$.   $$$n=7$$$, $$$k=1$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$;  during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$;  during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$;  during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.

object B extends App {

  def log2(x: Long): Int = {
    @annotation.tailrec
    def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)
    go(0)
  }

  def updateFiles(n: Long, k: Long): Long = (log2(k), log2(n)) match {
    case (log2k, log2n) if log2n <= log2k => log2n
    case (log2k, _)                       =>
      val num4k = (1L << log2k) - 1L
      val rem   = (n - 1L) - num4k

      log2k + (rem + k - 1L) / k
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextLong()
    val k = nextLong()
    val h = updateFiles(n, k)

    out.println(h)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

object B extends App {

  def log2(x: Long): Int = {
    @annotation.tailrec
    def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)
    go(0)
  }

  def updateFiles(n: Long, k: Long): Long = {
    val log2k = log2(k)
    val log2n = log2(n)

    if (log2n <= log2k) log2n
    else {
      val num4k = (1L << log2k) - 1L
      val rem   = n - 1L - num4k

      log2k + (rem + k - 1L) / k
    }
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextLong()
    val k = nextLong()
    val h = updateFiles(n, k)

    out.println(h)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

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

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

    case class pair(var s: Int, var a:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (a == that.a && s == that.s)
                return 0
            if (a > that.s && that.a <= s)
                return 1
            if (a <= that.s && that.a > s)
                return -1
            if (a == that.a) {
                if (s < that.s)
                    return -1
                else
                    return 1
            }
            if (a < that.a)
                return -1
            else
                return 1
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        var n = readLong() - 1L
        val k = readLong()
        var p = 1L
        var ans = 0L
        while (n > 0 && p < k) {
            ans += 1L
            n -= p
            p *= 2L
        }
        if (n > 0) {
            if (n % k != 0L) {
                ans += 1L
                n -= n % k
            }
            ans += (n / k).toLong
        }
        writer.println(ans)
    }
    writer.flush()
}

object B extends App {

  def log2(x: Long): Int = {
    @annotation.tailrec
    def go(pow: Int): Int = if (x <= (1L << pow)) pow else go(pow + 1)
    go(0)
  }

  def updateFiles(n: Long, k: Long): Long =
    (log2(k), log2(n - 1L)) match {
      case (log2k, log2n) if log2n <= log2k => log2n
      case (log2k, _)                       =>
        val num4k = (1L << log2k) - 1L
        val rem   = (n - 1L) - num4k

        log2k + (rem + k - 1L) / k
    }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextLong()
    val k = nextLong()
    val h = updateFiles(n, k)

    out.println(h)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}


You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct.You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?

The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct.

If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO.

NoteIn the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points.

object Solution {
  type Point = (Long, Long)

  def main(args: Array[String]) {
    val r = new Reader()
    val n = r.read[Int]
    val ps = r.read[List[Point]](n)

    println(if (ps.length < 3 || solve(ps)) "YES" else "NO")
  }

  def solve(ps: List[Point]) = {
    val q1 :: q2 :: q3 :: _ = ps
    lazy val u = ps.partition(collinear(_, q1, q2))._2
    lazy val v = ps.partition(collinear(_, q1, q3))._2
    lazy val w = ps.partition(collinear(_, q2, q3))._2

    u.length < 3 || v.length < 3 || w.length < 3 ||
      collinear(u) || collinear(v) || collinear(w)
  }

  def collinear(ps: List[Point]): Boolean =
    ps match {
      case p1 :: p2 :: qs => qs.dropWhile(collinear(_, p1, p2)).isEmpty
      case _ => true
    }

  def collinear(p: Point, q: Point, r: Point): Boolean =
     p._1*(q._2 - r._2) + q._1*(r._2 - p._2) + r._1*(p._2 - q._2) == 0
}

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

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

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

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

  val tokenizer = new Tokenizer(br)
}

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

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

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

    import scala.collection.generic.CanBuildFrom

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

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

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

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

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

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

object A {
    def main(args: Array[String]) {
        var n = scala.io.StdIn.readInt();
        var ps = Array.ofDim[Int](n, 2);
        for(i <- 0 until n){
            ps(i) = scala.io.StdIn.readLine().split(" ").map( _.toInt );
        }

        if(n <= 4) println("YES");
        else{
            var a1 = check(ps, 0, 1);
            var a2 = check(ps, 0, 2);
            var a3 = check(ps, 1, 2);
            var ans = a1 || a2 || a3;
            if(ans) println("YES");
            else println("NO");
        }
    }

    def check(ps: Array[Array[Int]], id1: Int, id2: Int): Boolean = {
        var n = ps.size;
        var on = Array.ofDim[Int](n);
        for(i <- 0 until n){
            if(cross(ps(i), ps(id1), ps(id2)) == 0) on(i) = 1;
        }

        var line = true;
        var b0 = -1;
        var b1 = -1;
        for(i <- 0 until n){
            if(on(i) == 0){
                if(b0 == -1) b0 = i;
                else if(b1 == -1) b1 = i;
                else{
                    if(cross(ps(i), ps(b0), ps(b1)) != 0) line = false;
                }
            }
        }

        return line;
    }

    def cross(p0: Array[Int], p1: Array[Int], p2: Array[Int]): Long = {
        var v0x = p1(0).toLong - p0(0).toLong;
        var v0y = p1(1).toLong - p0(1).toLong;
        var v1x = p2(0).toLong - p0(0).toLong;
        var v1y = p2(1).toLong - p0(1).toLong;
        return v0x * v1y - v0y * v1x;
    }
}


Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.

The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.

Print the sequence of operations that will rearrange the animals by non-decreasing height. The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed. The number of operations should not exceed 20 000. If the animals are arranged correctly from the start, you are allowed to output nothing.

NoteNote that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.

object Solution {
  def mrg(x:Vector[Boolean]) = {
    rle(x,0,0).sorted.reverse.headOption
  }
  def rle(x:Vector[Boolean],s:Int,l:Int):Vector[(Int,Int)] = {
    if (x.isEmpty) {
      if (l>0) Vector((l,s)) else Vector.empty[(Int,Int)]
    }
    else if (x.head) rle(x.tail,s,l+1)
    else {
      if (l==0) rle(x.tail,s+1,0)
      else (l,s) +: rle(x.tail,s+l+1,0)
    }
  }
  def gmx(x:Vector[Vector[Int]]) = mrg(x.map(v=>v.length == 2 && v(1) < v(0))).getOrElse((0,0))
  def inv(x:Vector[Int]) = {
    val g = gmx(x.grouped(2).toVector)
    val go = gmx(x.drop(1).grouped(2).toVector)
    if (g._1 > go._1) (g._2*2,g._1*2) else (1+go._2*2,2*go._1)
  }
  def re(x:Vector[Int]):Unit = {
    val g = inv(x)
    if (g._2 > 0) {
      println(s"${g._1+1} ${g._1+g._2}")
      re(flp(x,g))
    }
  }
  def flp(x:Vector[Int],i:(Int,Int)):Vector[Int] = {
    if (i._2 == 0) x else {
      val h = x(i._1)
      val l = x(i._1+1)
      flp(x.updated(i._1,l).updated(i._1+1,h),(i._1+2,i._2-2))
    }
  }
  def main(args: Array[String]) {
    val n = readInt
    val ns = readLine.split(" ").map(_.toInt)
    re(ns.toVector)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toLong).toList
  val sorted = line.sorted
  val (_, ans) = sorted.zipWithIndex.foldLeft(line, List.empty[String]) {
    case ((l, answer), (el, index)) =>
      val lindex = l.indexOf(el)
      (l.take(lindex) ::: l.drop(lindex + 1), (index until lindex + index).map(i => s"${i + 1} ${i + 2}").toList ::: answer)
  }
  println(ans.reverse.mkString("\n"))
}

object B686 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val ai = readInts(n)

    for(i <- 0 until n) {
      val slice = ai.slice(i, n)
      val min = slice.min
      if(slice.head != min) {
        var idx = slice.indexOf(min) + i
        while(idx > i) {
          println(s"${idx} ${idx+1}")

          val temp = ai(idx)
          ai(idx) = ai(idx-1)
          ai(idx-1) = temp

          idx -= 1
        }
      }
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object _686B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val animals = read[Vector[Int]]
    val ans = solve(animals, 0).map(i => s"${i + 1} ${i + 2}")
    if (ans.isEmpty) io else io.writeAll(ans, "\n")
  }

  def solve(animals: Vector[Int], offset: Int): Seq[Int] = if (animals.isEmpty) {
    Nil
  } else {
    val smallest = animals.min
    val pos = animals.indexOf(smallest)
    //debug(animals, offset, smallest, pos)
    (offset until (offset + pos)).reverse ++ solve(animals.patch(pos, Nil, 1), offset + 1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def 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 toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def 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(n.min(x, y), n.max(x, y), 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]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, 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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val ans = new Array[(Int, Int)](20000)
    var ind = 0
    //
    for(i <- (1 to n-1).reverse){
      for(j <- 1 to i){
        if(a(j) > a(j+1)){
          ans(ind) = (j, j+1)
          ind += 1
          val tmp = a(j)
          a(j) = a(j+1)
          a(j + 1) = tmp
        }
      }
    }

    for(i <- 0 until ind){
      println(ans(i)._1 + " " + ans(i)._2)
    }
  }
}

object Main{
  def main(args: Array[String]) {

    def step (list: List[Int]): (List[Int], (Int, Int)) = {
      val size = list.size
      for(i <- 0 to size - 2){
        if (list(i) > list(i+1)){
          return (list.updated(i,list(i+1)).updated(i+1,list(i)), (i, i+1))
        }
      }
      (list, (-1, -1))
    }

    val n = scala.io.StdIn.readInt()
    var list = scala.io.StdIn.readLine().split(" ").map(x => x.toInt).toList

    def recSolve(list: List[Int]): Unit ={
      val (l, (a,b)) = step(list)
      if (a != -1) {
        println((a+1) + " " + (b+1))
        recSolve(l)
      }
    }

    recSolve(list)

  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toLong).toList
  val sorted = line.sorted
  val (_, ans) = sorted.zipWithIndex.foldLeft(line, List.empty[String]) {
    case ((l, answer), (el, index)) =>
      val lindex = l.indexOf(el)
      (l.take(lindex) ::: l.drop(lindex + 1), (index until lindex + index).map(i => s"${i + 1} ${i + 2}").reverse.toList ::: answer)
  }
  println(ans.reverse.mkString("\n"))
}

object B686 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val ai = readInts(n)

    for(i <- 0 until n) {
      val slice = ai.slice(i, n)
      val min = slice.min
      if(slice.head != min) {
        var idx = slice.indexOf(min) + i
        while(idx > i) {
          println(s"${idx+1} ${idx}")

          val temp = ai(idx)
          ai(idx) = ai(idx-1)
          ai(idx-1) = temp

          idx -= 1
        }
      }
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val ans = new Array[(Int, Int)](20000)
    var ind = 0
    //
    for(i <- (2 to n-1).reverse){
      for(j <- 1 to i){
        if(a(j) > a(j+1)){
          ans(ind) = (j, j+1)
          ind += 1
          val tmp = a(j)
          a(j) = a(j+1)
          a(j + 1) = tmp
        }
      }
    }

    for(i <- 0 until ind){
      println(ans(i)._1 + " " + ans(i)._2)
    }
  }
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val ans = new Array[(Int, Int)](20000)
    var ind = 0
    //
    for(i <- 1 to n-1){
      for(j <- i to n-1){
        if(a(j) > a(j+1)){
          ans(ind) = (j, j+1)
          ind += 1
          val tmp = a(j)
          a(j) = a(j+1)
          a(j + 1) = tmp
        }
      }
    }

    for(i <- 0 until ind){
      println(ans(i)._1 + " " + ans(i)._2)
    }
  }
}


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3, 10 d: 4, 8 e: 6 f: 7 z: 1, 5, 9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.

The single line contains a positive integer n (1 ≤ n ≤ 105) — the length of the sought string.

Print on the single line the lexicographically minimal lucky string whose length equals n.

NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val res = "abcd"
  println(res * (n / 4) + res.take(n % 4))
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    print("abcd" * (n / 4))
    n % 4 match {
      case 0 =>
      case 1 => print("a")
      case 2 => print("ab")
      case 3 => println("abc")
    }
  }
}