object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val a: Array[Int] = in.next().split(' ').map(_.toInt - 1)
  val reverse = Array.ofDim[Int](n)
  a.indices.foreach {
    i => reverse(a(i)) = i
  }
  val b: Array[Int] = in.next().split(' ').map(_.toInt - 1)
  println(b.foldLeft(0l) {
    case(count, el) if reverse(el) == 0 => count + 1
    case(count, el) =>
      val position = reverse(el)
      val prevElement = a(position - 1)
      val press = 1 + position / k
      a(position - 1) = el
      a(position) = prevElement
      reverse(prevElement) = position
      reverse(el) = position - 1
      count + press
  })
}

object Smartphone {
  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = readLine.split(' ').map(_.toLong)
    val aa = readLine.split(' ').map(_.toLong).toList
    val bb = readLine.split(' ').map(_.toLong).toList

    val positionToApp = scala.collection.mutable.Map(aa.zipWithIndex.map(_.swap): _*)
    val appToPosition = scala.collection.mutable.Map(aa.zipWithIndex: _*)

    val steps = for (currentApp <- bb) yield {
      val currentAppPosition = appToPosition(currentApp)
      if (currentAppPosition > 0) {
        // Swap
        val appToSwap = positionToApp(currentAppPosition - 1)
        // swap positionToApp Map
        val temp1 = positionToApp(currentAppPosition)
        positionToApp(currentAppPosition) = positionToApp(currentAppPosition - 1)
        positionToApp(currentAppPosition - 1) = temp1
        // swap appToPosition Map
        val temp2 = appToPosition(currentApp)
        appToPosition(currentApp) = appToPosition(appToSwap)
        appToPosition(appToSwap) = temp2
      }
      currentAppPosition / k + 1
    }
    val result = steps.sum

    println(result)
  }
}

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

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val k = nextInt
    //    val screenNumber = new Array[Int](n)
    val rank = new Array[Int](n)
    val valueByRank = new util.HashMap[Int, Int]()
    for (i <- 0 until n) {
      val j: Int = nextInt - 1
      //      screenNumber(j) = Math.ceil(i / k).toInt
      rank(j) = i
      valueByRank.put(i, j)
    }
    var ans = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += Math.ceil(rank(b) / k).toInt + 1
      if (rank(b) != 0) {
        val next = valueByRank.get(rank(b) - 1)
        val pS = rank(b)
        val pN = rank(next)
        rank(b) = pN
        rank(next) = pS
        valueByRank.put(pN, b)
        valueByRank.put(pS, next)
      }
    }
    out.println(ans)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

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

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val k = nextInt
    val order = new Array[Int](n)
    val rank = new Array[Int](n)
    for (i <- 0 until n) {
      val j = nextInt - 1
      order(i) = j
      rank(j) = i
    }
    var ans:Long = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += Math.ceil(rank(b) / k).toLong + 1
      if (rank(b) != 0) {
        val next = order(rank(b) - 1)
        val pS = rank(b)
        val pN = rank(next)
        rank(b) = pN
        rank(next) = pS
        order(pN) = b
        order(pS) = next
      }
    }
    out.println(ans)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import scala.io.StdIn._

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

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

  def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {
    def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {
      case Nil => moves
      case h :: t =>
        if (id2Loc(h) > 0) {
          /*println(s"launching $h")
          println(s"id2Loc = $id2Loc")
          println(s"loc2Id= $loc2Id")*/
          /*assert(id2Loc.keySet == (0 until as.size).toSet, "keys van id2Loc verkeerd")
          assert(id2Loc.keySet.forall{p => loc2Id(id2Loc(p)) == p}, "id2Loc and loc2Id not inverse")*/
          val prevApp = loc2Id(id2Loc(h) - 1)
          go(t,
            id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),
            loc2Id - id2Loc(h) - (id2Loc(h)-1)  + (id2Loc(h)->prevApp) + ((id2Loc(h)-1)-> h),
            moves + id2Loc(h) / k + 1)
        } else {
          go(t,id2Loc,loc2Id,moves+1)
        }
    }
    go(launchOrder,
       as.zipWithIndex.toMap,
       as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,
       0)
  }

  def solve2(as: Array[Int], launchOrder: List[Int], k: Int) : Long = {
    val id2Loc = as.zipWithIndex.toList.sortBy(_._1).map(_._2).toArray
    val loc2Id = as.clone()
    def go(order : List[Int], moves: Long) : Long = order match {
      case Nil => moves
      case h :: t => {
       /* println(s"launching $h")
        println(s"id2Loc = " + id2Loc.mkString(","))
        println(s"loc2Id= " + loc2Id.mkString(","))
        assert((0 until id2Loc.length).forall{i => id2Loc(loc2Id(i)) == i}, "not inverse")*/
        val curAppLoc = id2Loc(h)
        if (curAppLoc > 0) {
          val prevAppIdd = loc2Id(curAppLoc - 1)
          loc2Id(curAppLoc) = prevAppIdd
          loc2Id(curAppLoc - 1) = h
          id2Loc(h) = curAppLoc - 1
          id2Loc(prevAppIdd) = curAppLoc
          go(t, moves + curAppLoc/k + 1)
        } else {
          go(t, moves + 1)
        }
      }
    }
    go(launchOrder, 0)

  }

  def main (args: Array[String]) {
    val (n,m,k) = readTriple()
    val as = readInts().map(_ - 1)
    val launchOrder = readInts().map(_ - 1)

    println(solve2(as,launchOrder.toList,k))

  }

}

import scala.collection.mutable.HashMap

object Main extends App {

   val Array(n,m,k) = readLine.split(" ").map(_.toInt)
   val as = readLine.split(" ").map(_.toInt)
   val bs = readLine.split(" ").map(_.toInt)

   def touch(pos: Int): Int = (pos / k) + 1

   val front = HashMap[Int, Int]()
   val back = HashMap[Int, Int]()

   as.zipWithIndex foreach { case (v, pos) =>
     front += (v -> pos)
     back += (pos -> v)
   }

   println(bs.map({ app =>
     val pos = front.getOrElse(app, 0)
     if(pos != 0) {
       val prevApp = back.getOrElse(pos-1, 0)
       front += (app -> (pos - 1))
       front += (prevApp -> pos)
       back += ((pos-1) -> app)
       back += (pos -> prevApp)
     }
     touch(pos)
   }).map(_.toLong).sum)

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val a: Array[Int] = in.next().split(' ').map(_.toInt - 1)
  val reverse = Array.ofDim[Int](n)
  a.indices.foreach {
    i => reverse(a(i)) = i
  }
  val b: Array[Int] = in.next().split(' ').map(_.toInt - 1)
  println(b.foldLeft(0) {
    case(count, el) if reverse(el) == 0 => count + 1
    case(count, el) =>
      val position = reverse(el)
      val prevElement = a(position - 1)
      val press = 1 + position / k
      a(position - 1) = el
      a(position) = prevElement
      reverse(prevElement) = position
      reverse(el) = position - 1
      count + press
  })
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt - 1).zipWithIndex.toMap
  val b = in.next().split(' ').map(_.toInt - 1)
  println(b.foldLeft((a, a.map(i => i._2 -> i._1), 0)) {
    case((map, reverse, count), 0) =>
      val position = map(0)
      (map, reverse, count + 1)
    case((map, reverse, count), el) =>
      val position = map(el)
      val prevElement = reverse(position - 1)
      val press = 1 + position / k
      (map + (el -> (position - 1)) + (prevElement -> position),
        reverse + (position -> prevElement) + ((position - 1) -> el), count + press)
  }._3)
}

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

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val k = nextInt
    val a = new Array[Int](n)
    val screenNumber = new Array[Int](n)
    for (i <- 0 until n) {
      screenNumber(nextInt - 1) = Math.ceil((i + 1) / k).toInt
    }
    var ans = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += screenNumber(b) + 1
      if (b != 0) {
        val prevS = screenNumber(b)
        val prevN = screenNumber(b - 1)
        screenNumber(b) = prevN
        screenNumber(b - 1) = prevS
      }
    }
    out.println(ans)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

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

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val k = nextInt
    //    val screenNumber = new Array[Int](n)
    val rank = new Array[Int](n)
    val valueByRank = new util.HashMap[Int, Int]()
    for (i <- 0 until n) {
      val j: Int = nextInt - 1
      //      screenNumber(j) = Math.ceil(i / k).toInt
      rank(j) = i
      valueByRank.put(i, j)
    }
    var ans = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += Math.ceil(rank(b) / k).toInt + 1
      if (b != 0) {
        val next = valueByRank.get(rank(b) - 1)
        val pS = rank(b)
        val pN = rank(next)
        rank(b) = pN
        rank(next) = pS
        valueByRank.put(pN, b)
        valueByRank.put(pS, next)
      }
    }
    out.println(ans)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

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

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val k = nextInt
    val a = new Array[Int](n)
    val screenNumber = new Array[Int](n)
    for (i <- 0 until n) {
      screenNumber(nextInt - 1) = Math.ceil(i / k).toInt
    }
    var ans = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += screenNumber(b) + 1
      if (b != 0) {
        val prevS = screenNumber(b)

        val prevN = screenNumber(b - 1)
        screenNumber(b) = prevN
        screenNumber(b - 1) = prevS
      }
    }
    out.println(ans)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import scala.io.StdIn._

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

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

  def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {
    def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {
      case Nil => moves
      case h :: t =>
        if (id2Loc(h) > 0) {
          /*println(s"launching $h")
          println(s"id2Loc = $id2Loc")
          println(s"loc2Id= $loc2Id")*/
          /*assert(id2Loc.keySet == (0 until as.size).toSet, "keys van id2Loc verkeerd")
          assert(id2Loc.keySet.forall{p => loc2Id(id2Loc(p)) == p}, "id2Loc and loc2Id not inverse")*/
          val prevApp = loc2Id(id2Loc(h) - 1)
          go(t,
            id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),
            loc2Id - id2Loc(h) - (id2Loc(h)-1)  + (id2Loc(h)->prevApp) + ((id2Loc(h)-1)-> h),
            moves + id2Loc(h) / k + 1)
        } else {
          go(t,id2Loc,loc2Id,moves+1)
        }
    }
    go(launchOrder,
       as.zipWithIndex.toMap,
       as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,
       0)
  }

  def solve2(as: Array[Int], launchOrder: List[Int], k: Int) : Int = {
    val id2Loc = as.zipWithIndex.toList.sortBy(_._1).map(_._2).toArray
    val loc2Id = as.clone()
    def go(order : List[Int], moves: Int) : Int = order match {
      case Nil => moves
      case h :: t => {
       /* println(s"launching $h")
        println(s"id2Loc = " + id2Loc.mkString(","))
        println(s"loc2Id= " + loc2Id.mkString(","))
        assert((0 until id2Loc.length).forall{i => id2Loc(loc2Id(i)) == i}, "not inverse")*/
        val curAppLoc = id2Loc(h)
        if (curAppLoc > 0) {
          val prevAppIdd = loc2Id(curAppLoc - 1)
          loc2Id(curAppLoc) = prevAppIdd
          loc2Id(curAppLoc - 1) = h
          id2Loc(h) = curAppLoc - 1
          id2Loc(prevAppIdd) = curAppLoc
          go(t, moves + curAppLoc/k + 1)
        } else {
          go(t, moves + 1)
        }
      }
    }
    go(launchOrder, 0)

  }

  def main (args: Array[String]) {
    val (n,m,k) = readTriple()
    val as = readInts().map(_ - 1)
    val launchOrder = readInts().map(_ - 1)

    println(solve2(as,launchOrder.toList,k))

  }

}

import scala.io.StdIn._

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

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

  def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {
    def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {
      case Nil => moves
      case h :: t =>
        if (id2Loc(h) > 0) {
          val prevApp = loc2Id(id2Loc(h) - 1)
          go(t,
            id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),
            loc2Id - loc2Id(h) - (loc2Id(h)-1)  + (loc2Id(h)->prevApp) + ((loc2Id(h)-1)-> h),
            moves + id2Loc(h) / k + 1)
        } else {
          go(t,id2Loc,loc2Id,moves+1)
        }
    }
    go(launchOrder,
       as.zipWithIndex.toMap,
       as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,
       0)
  }

  def main (args: Array[String]) {
    val (n,m,k) = readTriple()
    val as = readInts().map(_ - 1)
    val launchOrder = readInts().map(_ - 1)

    println(solve(as,launchOrder.toList,k))

  }

}

import scala.collection.mutable.HashMap

object Main extends App {

   val Array(n,m,k) = readLine.split(" ").map(_.toInt)
   val as = readLine.split(" ").map(_.toInt)
   val bs = readLine.split(" ").map(_.toInt)

   def touch(pos: Int): Int = (pos / k) + 1

   val front = HashMap[Int, Int]()
   val back = HashMap[Int, Int]()

   as.zipWithIndex foreach { case (v, pos) =>
     front += (v -> pos)
     back += (pos -> v)
   }

   println(bs.map({ app =>
     val pos = front.getOrElse(app, 0)
     if(pos != 0) {
       val prevApp = back.getOrElse(pos-1, 0)
       front += (app -> (pos - 1))
       front += (prevApp -> pos)
       back += ((pos-1) -> app)
       back += (pos -> prevApp)
     }
     touch(pos)
   }).sum)

}

object Smartphone {
  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = readLine.split(' ').map(_.toInt)
    val aa = readLine.split(' ').map(_.toInt).toList
    val bb = readLine.split(' ').map(_.toInt).toList

    val positionToApp = scala.collection.mutable.Map(aa.zipWithIndex.map(_.swap): _*)
    val appToPosition = scala.collection.mutable.Map(aa.zipWithIndex: _*)

    val steps = for (currentApp <- bb) yield {
      val currentAppPosition = appToPosition(currentApp)
      if (currentAppPosition > 0) {
        // Swap
        val appToSwap = positionToApp(currentAppPosition - 1)
        // swap positionToApp Map
        val temp1 = positionToApp(currentAppPosition)
        positionToApp(currentAppPosition) = positionToApp(currentAppPosition - 1)
        positionToApp(currentAppPosition - 1) = temp1
        // swap appToPosition Map
        val temp2 = appToPosition(currentApp)
        appToPosition(currentApp) = appToPosition(appToSwap)
        appToPosition(appToSwap) = temp2
      }
      currentAppPosition / k + 1
    }
    val result = steps.sum

    println(result)
  }
}


import scala.collection.mutable
import scala.io.StdIn._

object C_1187_editorial extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val A         = Array.fill[Int](n + 1)(1)
  val notSorted = mutable.ArrayBuffer[(Int, Int)]()
  val sorted    = mutable.ArrayBuffer[(Int, Int)]()

  1 to m foreach { _ =>
    val Array(t, l, r) = readLine().split(" ").map(_.toInt)

    if (t == 1) {
      sorted += ((l, r))
      (l until r).foreach { i =>
        A(i) = 0
      }
    } else {
      notSorted += ((l, r))
      (l until r).foreach { i =>
        if (A(i) == 1) A(i) = -1
      }
    }
  }

  def isSorted: Boolean = {
    sorted.foreach {
      case (l, r) =>
        (l + 1 to r).foreach { i =>
          if (A(i - 1) > A(i)) {
            return false
          }
        }
    }
    true
  }

  def isNotSorted: Boolean = {
    notSorted.foreach {
      case (l, r) =>
        val allSorted = (l + 1 to r).forall { i =>
          A(i - 1) <= A(i)
        }
        if (allSorted) return false
    }
    true
  }

  var delta = A(1)
  A(1) = 1000000000 / 2

  (2 to n).foreach { i =>
    if (A(i) == 1) A(i) = -1
    val newDelta = A(i)
    A(i) = A(i - 1) + delta
    delta = newDelta
  }

//  println("YES")
//  println(A.tail.mkString(" "))

  if (isSorted && isNotSorted) {
    println("YES")
    println(A.tail.mkString(" "))
  } else {
    println("NO")
  }

}

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

  case class Range(l: Int, r: Int) {
    def contains(rg: Range): Boolean = l <= rg.l && rg.r <= r
  }

  def solve(): Unit = {
    import java.util.{Collections, Comparator}
    val N, M = ni()
    val sorted, unsorted, mergedSorted = new java.util.ArrayList[Range]
    REP(M) { _ =>
      val t, l, r = ni()
      if (t == 1) {
        sorted.add(Range(l, r))
      } else {
        unsorted.add(Range(l, r))
      }
    }

    Collections.sort(sorted, new Comparator[Range] {
      override def compare(o1: Range, o2: Range): Int = {
        Integer.compare(o1.l, o2.l)
      }
    })

    var l = 0
    var r = 0
    REP(sorted.size()) { i =>
      val rg = sorted.get(i)
      if (rg.l <= r) {
        r = max(r, rg.r)
      } else {
        if (l != 0) mergedSorted.add(Range(l, r))
        l = rg.l
        r = rg.r
      }
    }
    if (l != 0) mergedSorted.add(Range(l, r))
    debug(mergedSorted.toArray.mkString(" "))

    val ans = Array.ofDim[Int](N)
    var p = 0
    REP_r(N) { i =>
      p += 1
      ans(i) = p
    }
    REP_r(mergedSorted.size) { i =>
      val rg = mergedSorted.get(i)
      var num = ans(rg.r - 1)
      TO(rg.l, rg.r) { j =>
        ans(j - 1) = num
        num += 1
      }
    }

    def test: Boolean = {
      REP(sorted.size) { i =>
        val rg = sorted.get(i)
        var found = false
        TO(rg.l, rg.r - 1) { j =>
          if (j > rg.l - 1 && ans(j) < ans(j-1)) found = true
        }
        debug(s"found:$found")
        if (found) return false
      }
      REP(unsorted.size) { i =>
        val rg = unsorted.get(i)
        var found = false
        TO(rg.l, rg.r - 1) { j =>
          if (j > rg.l - 1 && ans(j) < ans(j-1)) found = true
        }
        if (!found) return false
      }
      true
    }

    debug(ans)
    if (!test) out.println("NO")
    else {
      out.println("YES")
      out.println(ans.mkString(" "))
    }

  }
}

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

  case class Range(l: Int, r: Int) {
    def contains(rg: Range): Boolean = l <= rg.l && rg.r <= r
  }

  def solve(): Unit = {
    import java.util.{Collections, Comparator}
    val N, M = ni()
    val sorted, unsorted, mergedSorted = new java.util.ArrayList[Range]
    REP(M) { _ =>
      val t, l, r = ni()
      if (t == 1) {
        sorted.add(Range(l, r))
      } else {
        unsorted.add(Range(l, r))
      }
    }

    Collections.sort(sorted, new Comparator[Range] {
      override def compare(o1: Range, o2: Range): Int = {
        Integer.compare(o1.l, o2.l)
      }
    })

    var l = 0
    var r = 0
    REP(sorted.size()) { i =>
      val rg = sorted.get(i)
      if (rg.l <= r) {
        r = rg.r
      } else {
        if (l != 0) mergedSorted.add(Range(l, r))
        l = rg.l
        r = rg.r
      }
    }
    if (l != 0) mergedSorted.add(Range(l, r))
    debug(mergedSorted.toArray.mkString(" "))

    def test: Boolean = {
      REP(unsorted.size()) { i =>
        REP(mergedSorted.size()) { j =>
          if (mergedSorted.get(j).contains(unsorted.get(i))) return false
        }
      }
      true
    }

    if (!test) out.println("NO")
    else {
      out.println("YES")
      val ans = Array.ofDim[Int](N)
      var p = 0
      REP_r(N) { i =>
        p += 1
        ans(i) = p
      }
      REP_r(mergedSorted.size) { i =>
        val rg = mergedSorted.get(i)
        TO(rg.l, rg.r) { j =>
          ans(j - 1) = ans(rg.r - 1)
        }
      }
      out.println(ans.mkString(" "))
    }

  }
}

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

  case class Range(l: Int, r: Int) {
    def contains(rg: Range): Boolean = l <= rg.l && rg.r <= r
  }

  def solve(): Unit = {
    import java.util.{Collections, Comparator}
    val N, M = ni()
    val sorted, unsorted, mergedSorted = new java.util.ArrayList[Range]
    REP(M) { _ =>
      val t, l, r = ni()
      if (t == 1) {
        sorted.add(Range(l, r))
      } else {
        unsorted.add(Range(l, r))
      }
    }

    Collections.sort(sorted, new Comparator[Range] {
      override def compare(o1: Range, o2: Range): Int = {
        Integer.compare(o1.l, o2.l)
      }
    })

    var l = 0
    var r = 0
    REP(sorted.size()) { i =>
      val rg = sorted.get(i)
      if (rg.l <= r) {
        r = rg.r
      } else {
        if (l != 0) mergedSorted.add(Range(l, r))
        l = rg.l
        r = rg.r
      }
    }
    if (l != 0) mergedSorted.add(Range(l, r))
    debug(mergedSorted.toArray.mkString(" "))

    val ans = Array.ofDim[Int](N)
    var p = 0
    REP_r(N) { i =>
      p += 1
      ans(i) = p
    }
    REP_r(mergedSorted.size) { i =>
      val rg = mergedSorted.get(i)
      var num = ans(rg.r - 1)
      TO(rg.l, rg.r) { j =>
        ans(j - 1) = num
        num += 1
      }
    }

    def test: Boolean = {
      REP(sorted.size) { i =>
        val rg = sorted.get(i)
        var found = false
        TO(rg.l, rg.r - 1) { j =>
          if (j > rg.l - 1 && ans(j) < ans(j-1)) found = true
        }
        debug(s"found:$found")
        if (found) return false
      }
      REP(unsorted.size) { i =>
        val rg = unsorted.get(i)
        var found = false
        TO(rg.l, rg.r - 1) { j =>
          if (j > rg.l - 1 && ans(j) < ans(j-1)) found = true
        }
        if (!found) return false
      }
      true
    }

    debug(ans)
    if (!test) out.println("NO")
    else {
      out.println("YES")
      out.println(ans.mkString(" "))
    }

  }
}

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

  case class Range(l: Int, r: Int) {
    def contains(rg: Range): Boolean = l <= rg.l && rg.r <= r
  }

  def solve(): Unit = {
    import java.util.{Collections, Comparator}
    val N, M = ni()
    val sorted, unsorted, mergedSorted = new java.util.ArrayList[Range]
    REP(M) { _ =>
      val t, l, r = ni()
      if (t == 1) {
        sorted.add(Range(l, r))
      } else {
        unsorted.add(Range(l, r))
      }
    }

    Collections.sort(sorted, new Comparator[Range] {
      override def compare(o1: Range, o2: Range): Int = {
        Integer.compare(o1.l, o2.l)
      }
    })

    var l = 0
    var r = 0
    REP(sorted.size()) { i =>
      val rg = sorted.get(i)
      if (rg.l <= r) {
        r = rg.r
      } else {
        if (l != 0) mergedSorted.add(Range(l, r))
        l = rg.l
        r = rg.r
      }
    }
    if (l != 0) mergedSorted.add(Range(l, r))
    debug(mergedSorted.toArray.mkString(" "))

    def test: Boolean = {
      REP(unsorted.size()) { i =>
        REP(mergedSorted.size()) { j =>
          if (mergedSorted.get(j).contains(unsorted.get(i))) return false
        }
      }
      true
    }

    if (!test) out.println("NO")
    else {
      out.println("YES")
      val ans = Array.ofDim[Int](N)
      var p = 0
      REP_r(mergedSorted.size) { i =>
        p += 1
        val rg = mergedSorted.get(i)
        TO(rg.l, rg.r) { j =>
          ans(j - 1) = p
        }
      }
      REP_r(N) { i =>
        if (ans(i) == 0) {
          p += 1
          ans(i) = p
        }
      }
      out.println(ans.mkString(" "))
    }

  }
}

import scala.collection.mutable
import scala.io.StdIn._

object C_1187 extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)

  var sorted   = mutable.ArrayBuffer[(Int, Int)]()
  var unsorted = mutable.ArrayBuffer[(Int, Int)]().sortBy(_._1)

  val answer = Array.ofDim[Int](n)

  1 to m foreach { _ =>
    val Array(t, l, r) = readLine().split(" ").map(_.toInt)
    if (t == 1) sorted.append((l, r))
    else unsorted.append((l, r))
  }

  var counter    = 1
  var lastSorted = counter - 1

  sorted.foreach {
    case (l, r) =>
      l to r foreach { i =>
        answer(i - 1) = counter
        lastSorted = counter
        counter += 1
      }
  }

  (0 until n).reverse foreach { i =>
    if (answer(i) == 0) {
      answer(i) = counter
      counter += 1
    }
  }

  unsorted.foreach {
    case (l, r) => {
      l to r foreach { i =>
        answer(i - 1) = counter
        counter += 1
      }

      if (answer(l - 1) < answer(r - 1)) {
        val tmp = answer(l - 1)
        answer(l - 1) = answer(r - 1)
        answer(r - 1) = tmp
      } else {
        // cannot fix or it's fixed
      }
    }
  }

  val isSorted = {
    sorted.forall {
      case (l, r) =>
        l until r forall { i =>
          answer(i - 1) <= answer(i)
        }
    }
  }

  if (isSorted) {
    println("YES")
    println(answer.mkString(" "))
  } else {
    println("NO")
  }
}

import scala.collection.mutable
import scala.io.StdIn._

object C_1187 extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)

  var sorted   = mutable.ArrayBuffer[(Int, Int)]()
  var unsorted = mutable.ArrayBuffer[(Int, Int)]().sortBy(_._1)

  val answer = Array.ofDim[Int](n)

  1 to m foreach { _ =>
    val Array(t, l, r) = readLine().split(" ").map(_.toInt)
    if (t == 1) sorted.append((l, r))
    else unsorted.append((l, r))
  }

  var counter    = 1
  var lastSorted = counter - 1

  sorted.foreach {
    case (l, r) =>
      l to r foreach { i =>
        answer(i - 1) = counter
        lastSorted = counter
        counter += 1
      }
  }

  (0 until n).reverse foreach { i =>
    if (answer(i) == 0) {
      answer(i) = counter
      counter += 1
    }
  }

  unsorted.foreach {
    case (l, r) => {
      l to r foreach { i =>
        answer(i - 1) = counter
        counter += 1
      }

      if (answer(l - 1) < answer(r - 1)) {
        val tmp = answer(l - 1)
        answer(l - 1) = answer(r - 1)
        answer(r - 1) = tmp
      } else {
        // cannot fix or it's fixed
      }
    }
  }

  val isSorted = {
    sorted.forall {
      case (l, r) =>
        l + 1 until r forall { i =>
          answer(i - 1) <= answer(i)
        }
    }
  }

  if (isSorted) {
    println("YES")
    println(answer.mkString(" "))
  } else {
    println("NO")
  }
}

import scala.collection.mutable
import scala.io.StdIn._

object C_1187_editorial extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val A         = Array.fill[Int](n + 1)(1)
  val notSorted = mutable.ArrayBuffer[(Int, Int)]()
  val sorted    = mutable.ArrayBuffer[(Int, Int)]()

  1 to m foreach { _ =>
    val Array(t, l, r) = readLine().split(" ").map(_.toInt)

    if (t == 1) {
      sorted += ((l, r))
      (l until r).foreach { i =>
        A(i) = 0
      }
    } else {
      notSorted += ((l, r))
      (l until r).foreach { i =>
        if (A(i) == 1) A(i) = -1
      }
    }
  }

  def isSorted: Boolean = {
    sorted.foreach {
      case (l, r) =>
        (l + 1 to r).foreach { i =>
          if (A(i - 1) > A(i)) {
            return false
          }
        }
    }
    true
  }

  def isNotSorted: Boolean = {
    notSorted.foreach {
      case (l, r) =>
        val allSorted = (l + 1 to r).forall { i =>
          A(i - 1) <= A(i)
        }
        if (allSorted) return false
    }
    true
  }

  var delta = A(1)
  A(1) = 0

  (2 to n).foreach { i =>
    if (A(i) == 1) A(i) = -1
    val newDelta = A(i)
    A(i) = A(i - 1) + delta
    delta = newDelta
  }

//  println("YES")
//  println(A.tail.mkString(" "))

  if (isSorted && isNotSorted) {
    println("YES")
    println(A.tail.mkString(" "))
  } else {
    println("NO")
  }

}


object CF_523_2_B extends App {
  def solve(as: Seq[Int]): Long = loop(as.filter(_>0).sortWith(_>_))

  def loop(as: Seq[Int], removed: Long = 0):Long =  as match {
    // last column, keep them all and return result
    case Seq(last) => removed
    case c1 +: c2 +: _ =>
      // remove all blocks in c1 below height of c2
      if(c1 > c2) loop(as.tail, removed + c2)
      // if c2 same height or more, remove all but 1 of c1 reduce c2 to 1 below c1 if c1 is > 1
      else  {
        val newc2 = math.max(1, c1 - 1)
        val toRemove = math.max(0, c1 - 1) + (c2 - newc2)
        loop(as.tail.updated(0, newc2), removed + toRemove)
      }
  }
  val io = new IO(System.in)
  io.int(); io.int()
  println(solve(io.intSeq()))
}

/// boilerplate utility methods:
import java.util.Scanner

class IO(sc: Scanner) {
  def this(i: java.io.InputStream) = this(new Scanner(i))
  def this(s: String) = this(new Scanner(s))
  // methods are side-effecting because they advance Scanner's pointer
  // extra nextLine is required to advance past the newline on the ints line
  def collect[T](f: String => T) = {sc.nextLine();sc.nextLine().split(" ").toVector.map(f)}
  def intSeq() = collect(_.toInt)
  def doubleSeq() = collect(_.toDouble)
  def int() = sc.nextInt()
  def double() = sc.nextDouble()
}

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    radixSort(A)
    var p = 0
    rep(N - 1) { i =>
      if (A(i) > p) p += 1
    }
    val remain = N - 1 + max(1, A(N - 1) - p) // [1, N - 1]に１こずつ配置
    val ans = sumL(A) - remain
    out.println(ans)
  }

  /**
    * 正の値のみのときだけ
    */
  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
  }

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

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

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

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

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

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

object MainB extends App {
  val (n, m) = {
    val l = scala.io.StdIn.readLine().split(" ")
    (math.BigInt(l(0).toInt), math.BigInt(l(1).toInt))
  }
  val ns = scala.io.StdIn.readLine().split(" ").map(i => math.BigInt(i.toInt)).sorted
  var d = 0
  for (i <- ns.indices) if (ns(i) > d) d += 1
  println(ns.sum - n - ns.max + d)
}

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    if (N == 1) {
      out.println(0)
    } else {
      radixSort(A)

      val remain = N - 1 + max(1, A(N - 1) - A(N - 2))
      val ans = sumL(A) - remain
      out.println(ans)
    }
  }

  /**
    * 正の値のみのときだけ
    */
  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
  }

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

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

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

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

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

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

object CF_523_2_B extends App {
  def solve(as: Seq[Int]): Int = loop(as.filter(_>0).sortWith(_>_))

  def loop(as: Seq[Int], removed: Int = 0):Int =  as match {
    // last column, keep them all and return result
    case Seq(last) => removed
    case c1 +: c2 +: _ =>
      // remove all blocks in c1 below height of c2
      if(c1 > c2) loop(as.tail, removed + c2)
      // if c2 same height or more, remove all but 1 of c1 reduce c2 to 1 below c1 if c1 is > 1
      else  {
        val newc2 = math.max(1, c1 - 1)
        val toRemove = math.max(0, c1 - 1) + (c2 - newc2)
        loop(as.tail.updated(0, newc2), removed + toRemove)
      }
  }
  val io = new IO(System.in)
  io.int(); io.int()
  println(solve(io.intSeq()))
}

/// boilerplate utility methods:
import java.util.Scanner

class IO(sc: Scanner) {
  def this(i: java.io.InputStream) = this(new Scanner(i))
  def this(s: String) = this(new Scanner(s))
  // methods are side-effecting because they advance Scanner's pointer
  // extra nextLine is required to advance past the newline on the ints line
  def collect[T](f: String => T) = {sc.nextLine();sc.nextLine().split(" ").toVector.map(f)}
  def intSeq() = collect(_.toInt)
  def doubleSeq() = collect(_.toDouble)
  def int() = sc.nextInt()
  def double() = sc.nextDouble()
}

object CF_523_2_B extends App {
  def solve(as: Seq[Int]): Int = loop(as.filter(_>0).sortWith(_>_))

  def loop(as: Seq[Int], removed: Int = 0):Int =  as match {
    // last column, keep them all and return result
    case Seq(last) => removed
    case c1 +: c2 +: _ =>
      // remove all blocks in c1 below height of c2
      if(c1 > c2) loop(as.tail, removed + c2)
      // if c2 same height or more, remove all but 1 of c1 reduce c2 to 1 below c1 if c1 is > 1
      else  {
        val newc2 = math.max(1, c1 - 1)
        val toRemove = math.max(0, c1 - 1) + (c2 - newc2)
        loop(as.tail.updated(0, newc2), removed + toRemove)
      }
  }
  val io = new IO(System.in)
  io.int(); io.int()
  solve(io.intSeq())
}

/// boilerplate utility methods:
import java.util.Scanner

class IO(sc: Scanner) {
  def this(i: java.io.InputStream) = this(new Scanner(i))
  def this(s: String) = this(new Scanner(s))
  // methods are side-effecting because they advance Scanner's pointer
  // extra nextLine is required to advance past the newline on the ints line
  def collect[T](f: String => T) = {sc.nextLine();sc.nextLine().split(" ").toVector.map(f)}
  def intSeq() = collect(_.toInt)
  def doubleSeq() = collect(_.toDouble)
  def int() = sc.nextInt()
  def double() = sc.nextDouble()
}

object MainB extends App {
  val (n, m) = {
    val l = scala.io.StdIn.readLine().split(" ")
    (math.BigInt(l(0).toInt), math.BigInt(l(1).toInt))
  }
  val ns = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted
  var d = 0
  for (i <- ns.indices) if (ns(i) > d) d += 1
  println(ns.sum - n - ns.max + d)
}

object MainB extends App {
  val (n, m) = {
    val l = scala.io.StdIn.readLine().split(" ")
    (l(0).toInt, l(1).toInt)
  }
  val ns = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted
  var d = 0
  for (i <- ns.indices) if (ns(i) > d) d += 1
  println(ns.sum - n - ns.max + d)
}


object P7C {
    def eGcd(a : Long, b : Long) : (Long, Long, Long) = () match {
        case _ if a < 0L => eGcd(-a, b) match {case (p, q, d) => (-p, q, d)}
        case _ if b < 0L => eGcd(a, -b) match {case (p, q, d) => (p, -q, d)}
        case _ if a < b  => eGcd(b, a) match {case (p, q, d) => (q, p, d)}
        case _ if b == 0L => (1, 0, a)
        case _ => eGcd(b, a % b) match {
            case (p, q, d) => (q, p - a / b * q, d)
        }
    }

    def main(args : Array[String]) {
        val Array(a, b, c) = readLine split ' ' map {_.toInt}
        val (p, q, d) = eGcd(a, b)
        if (c % d == 0) {
            val m = -c / d
            println(p * m + " " + q * m)
        } else {
            println("-1")
        }
    }
}

import java.util.Scanner

object CStraight extends App {

  val scanner = new Scanner(System.in)

  val a = scanner.nextLong()
  val b = scanner.nextLong()
  val c = -scanner.nextLong()

  val res = gcd(a, b)
  if (c % res._1 == 0) {
    val x0 = res._2 * (c / res._1)
    val y0 = res._3 * (c / res._1)
    println(x0 + " " + y0)
  } else {
    println("-1")
  }

  def gcd(a: Long, b: Long): (Long, Long, Long) = {
    if (a == 0) (b, 0, 1)
    else {
      val (g, x1, y1) = gcd(b % a, a)
      val x = y1 - (b / a) * x1
      val y = x1
      (g, x, y)
    }
  }

}

import java.util.Scanner

object CStraight extends App {

  val scanner = new Scanner(System.in)

  val a = scanner.nextInt()
  val b = scanner.nextInt()
  val c = -scanner.nextInt()

  val res = gcd(a, b)
  if (c % res._1 == 0) {
    val x0 = res._2 * (c / res._1)
    val y0 = res._3 * (c / res._1)
    println(x0 + " " + y0)
  } else {
    println("-1")
  }

  def gcd(a: Int, b: Int): (Int, Int, Int) = {
    if (a == 0) (b, 0, 1)
    else {
      val (g, x1, y1) = gcd(b % a, a)
      val x = y1 - (b / a) * x1
      val y = x1
      (g, x, y)
    }
  }

}


object B {

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

    //System.setIn(new FileInputStream("src/b.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/b.out")))

    var Array(n, k, q) = readLine().split(" ").map(_.toInt)
    var friends: Array[Int] = readLine().split(" ").map(_.toInt)
    var screen: Set[Int] = Set.empty[Int]

    for(i <- 0 until q) {
      var Array(tp, id) = readLine().split(" ").map(_.toInt)
      if(tp == 1) {
        if(screen.size < k || friends(id - 1) > screen.min) {
          screen += friends(id - 1)
          if(screen.size > k) {
            screen -= screen.min
          }
        }
      }
      else {
        if(screen.contains(friends(id - 1))) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k, q) = in.next().split(' ').map(_.toInt)
  val t = in.next().split(' ').map(_.toInt)
  val window = Array.ofDim[Int](k)
  (1 to q).foreach { _ =>
    val Array(ty, id) = in.next().split(' ').map(_.toInt)
    if (ty == 1) {
      if (!window.contains(id)) {
        val min = window.indices.find(i => window(i) == 0).getOrElse(
          window.indices.minBy(i => t(window(i) - 1)))
        if (window(min) == 0 || t(window(min) - 1) < t(id - 1))
          window(min) = id
      }
    } else {
      if (window.contains(id))
        println("YES")
      else
        println("NO")
    }
  }
}

import scala.collection._

object B extends App {

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

  val Array(n, k, q) = readInts(3)
  val ts = readInts(n)

  val sb = new StringBuilder

  val active = new mutable.TreeSet[Int]()(Ordering.by(ts))

  for (_ <- 0 until q) {
    readInts(2) match {
      case Array(1, id) =>
        active += (id - 1)
        while (active.size > k) {
          val min = active.head
          active.remove(min)
        }
      case Array(2, id) =>
        sb.append(if (active.contains(id - 1)) "YES\n" else "NO\n")
    }
  }

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

  println(sb.result())

  Console.flush
}

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

object _658B extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, k, q = io[Int]
    val t = io[IndexedSeq, Int](n)
    val pq = mutable.PriorityQueue.empty[Int](Ordering.by(id => -t(id - 1)))
    val ans = Vector.empty[Boolean]
    io.separator = "\n"
    repeat(q) {
      val _ = io[(Int, Int)] match {
        case (1, id) =>
          pq += id
          if (pq.size > k) pq.dequeue()
        case (2, id) =>
          io += pq.exists(_ == id)
      }
    }
    io
  }
}
/****************************[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 sum[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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


import java.util.Scanner
import java.math._

object B extends App
{
	val cin=new Scanner(System.in)
	val n=cin.nextInt()
	if(n<3) println(-1)
	else if(n==3) println(210)
	else
	{
		val mod=math.BigInt(10).modPow(math.BigInt((n-1).toString),math.BigInt(210)).toInt
		val add=210-mod
		println("1"+"0"*(n-4+3-add.toString.length)+add)
	}
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val x = 2 * 3 * 5 * 7
  val n = in.next().toInt
  if (n < 3)
    println(-1)
  else if (n == 3)
    println("210")
  else {
    val t = n - 3
    val left = Map(0 -> "110", 1 -> "050", 2 -> "080", 3 -> "170", 4 -> "020", 5 -> "200")(t % 6)
    println("1" + "0" * (n - 4) + left)
  }
}

object B248 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    if(n < 3)
      println("-1")
    else
      println((BigInt(10).pow(n-1)/210 + 1)*210)
  }

  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 collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}
    if(n==3){println(210);exit}

    var last=7-(1 until n-1).foldLeft(1){(x,y)=>x*10%7}
    while((last.toString.map(_-'0').sum+1)%3!=0) last+=7
    println("1"+"0"*(n-2-last.toString.length)+last+"0")
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}
    if(n==3){println(210);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

    var last=7-dp(n-2)
    while((last.toString.map(_-'0').sum+1)%3!=0) last+=7
    println("1"+"0"*(n-2-last.toString.length)+last+"0")
}

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

    val n=readLine.toInt

    if(n<=2){
      println(-1)
    }else if(n==3){
      println(210)
    }else{
      val amari=
        (1 to n-1).fold(1)((x,y)=> x*10%210)

      val add=210-amari
      print("1")
      print("0"*(n-4))
      println("%03d".format(add))
    }
  }
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

   for(i<- 1 until n-1 reverse)
   {
	   var last=7%dp(i)
	   while((last.toString.map(_-'0').sum+1)%3!=0)
	  	   last+=7

	   println("1"+"0"*(i-last.toString.length)+last+"0"*(n-i-1))
	   exit
   }
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

    var i=n-2
    var last=7-dp(i)

    while((last.toString.map(_-'0').sum+1)%3!=0) last+=7

    println("1"+"0"*(i-last.toString.length)+last+"0"*(n-i-1))
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

   for(i<- 1 until n-1 reverse)
   {
	   var last=7%dp(i)
       if((last+1)%3!=0 && last<3) last+=7
       if((last+1)%3==0)
       {
    	   println("1"+"0"*(i-1)+last+"0"*(n-i-1))
    	   exit
       }
   }
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    if(n<=2){println(-1);exit}

    var start=1
    val dp=for(i<- 1 to n) yield
    {
    	val mod=start%7
    	start=mod*10
    	mod
    }

   for(i<- 1 until n-1 reverse)
   {
	   var last=7-dp(i)

	   while((last.toString.map(_-'0').sum+1)%3!=0)
	   {
	  	       println(last)
	  	       last+=7
	   }

	   println("1"+"0"*(i-last.toString.length)+last+"0"*(n-i-1))
	   exit
   }
}


import scala.annotation.tailrec
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.io.PrintWriter
object Main {

  def main(args: Array[String]): Unit = {
    @tailrec
    def rec(ind:Int,seq:List[Char],left:List[Int],right:List[Int]):List[Int]=seq match{
      case List() => return left.reverse++right
      case _ if(seq.head=='l') => return rec(ind+1,seq.tail,left,ind+:right)
      case _ => return rec(ind+1,seq.tail,ind+:left,right)
    }
    val br = new BufferedReader(new InputStreamReader(System.in))
    val pw = new PrintWriter(new OutputStreamWriter(System.out))
    rec(1,br.readLine().toList,List(),List()).map(pw.println(_))
    pw.flush()
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val str = in.next()
  val res = Array.ofDim[Int](str.length)
  str.foldLeft((0, str.length - 1, 1)) {
    case ((left, right, number), 'l') => res(right) = number
      (left, right - 1, number + 1)
    case ((left, right, number), 'r') => res(left) = number
      (left + 1, right, number + 1)
  }
  println(res.mkString("\n"))
}

import scala.collection.mutable.ListBuffer

object Test2 {
def main(args: Array[String]) {
    val (_,left,right) = readLine.foldLeft((1, ListBuffer[Int](), ListBuffer[Int]()))((r, c) =>{
      c match {
        case 'l' =>  r._1 +=:r._3
        case _ => r._2 +=r._1
      }
      (r._1 + 1, r._2,  r._3)
    }
    )

    println(left.mkString("\n"));
    println(right.mkString("\n"));

  }
}

object Test1 {
  def main(args: Array[String]) {
    val (_,left,right) = readLine.foldLeft((1, List[Int](), List[Int]()))((r, c) =>
      c match {
        case 'l' => (r._1 + 1, r._2, r._1 :: r._3)
        case _ => (r._1 + 1, r._1 :: r._2, r._3)
      })

    println(left.reverse.mkString("\n"));
    println(right.mkString("\n"));

  }

}

object Test3 {

   def main(args: Array[String]) {
    val s = readLine;
    val (_,_,_,result) = s.foldLeft(1,0,s.length-1,new Array[Int](s.length))((r, c) =>c match {
        case 'l' => r._4(r._3) = r._1; (r._1+1,r._2,r._3-1,r._4)
        case _ => r._4(r._2) = r._1; (r._1+1,r._2+1,r._3,r._4)
      })
    println(result.mkString("\n"));

  }

}

object test {
  def main(args: Array[String]): Unit = {
      val s=readLine
      val a=new Array[Int](s.length())
      var i=0
      var j=s.length-1
      var k=0
      while(k<s.length)
      {
        if(s(k)=='l')
        {
          a(j)=k+1
          j-=1
        }
        else
        {
          a(i)=k+1
          i+=1
        }
        k+=1
      }
      println(a.mkString("\n"))
  }

}

object test {
  def main(args: Array[String]): Unit = {
val beforeRead = System.currentTimeMillis
      val s = readLine
      val ss = s.zipWithIndex.partition(_._1 != 'l')
      val a = ss._1.map(_._2 + 1).mkString("\n") + "\n" +
              ss._2.reverseMap(_._2 + 1).mkString("\n")
      println(a)
  }
}

object test {
  def main(args: Array[String]): Unit = {
      val s=readLine
      val a=new Array[Int](s.length())
      var i=0
      var j=s.length-1

      for(k <- 0 to s.length-1)
        if(s(k)=='l')
        {
          a(j)=k+1
          j-=1
        }
        else
        {
          a(i)=k+1
          i+=1
        }
      println(a.mkString("\n"))
  }
}

import scala.annotation.tailrec
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
object Main {

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val pw = new PrintWriter(new OutputStreamWriter(System.out))
    val inp = br.readLine()
    var res = new Array[Int](inp.length())
    @tailrec
    def rec(ind:Int,seq:List[Char],left:Int,right:Int):Unit=seq match{
      case List() => return
      case _ => {
        res(if(seq.head=='l') right else left) = ind
        if(seq.head=='l')rec(ind+1,seq.tail,left,right-1) else rec(ind+1,seq.tail,left+1,right)
      }
    }
    rec(1,inp.toList,0,inp.length()-1)
    res.map(pw.println(_))
    pw.flush()
  }

}

import scala.annotation.tailrec
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
object Main {

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val pw = new PrintWriter(System.out)
    val inp = br.readLine()
    var res = new Array[Int](inp.length())
    @tailrec
    def rec(ind:Int,seq:List[Char],left:Int,right:Int):Unit={
      if(!seq.isEmpty)seq.head match{
        case 'l' => {res(right) = ind;rec(ind+1,seq.tail,left,right-1)}
        case 'r' => {res(left)  = ind;rec(ind+1,seq.tail,left+1,right)}
      }
    }
    rec(1,inp.toList,0,inp.length()-1)
    res.map(pw.println(_))
    pw.flush()
  }

}

import scala.collection.mutable.LinkedList
object Main265C {
  def main(args: Array[String]) {
    val cmds = readLine
    val array1 = Array.ofDim[Int](cmds length)
    val array2 = Array.ofDim[Int](cmds length)
    var pos1, pos2 = 0
    var nextNum = 1
    for (c <- cmds) {
      if (c == 'l') {
        array1(pos1) = nextNum
        pos1 += 1
      }
      else {
        array2(pos2) = nextNum
        pos2 += 1
      }
      nextNum += 1
    }
    val sb = new StringBuilder()
    for (i <- 0 to (pos2-1))
      sb.append(array2(i)).append("\n")
    for (i <- (pos1-1) to 0 by -1)
      sb.append(array1(i)).append("\n")
    print(sb)
  }
}

object C265 {

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

  def main(args: Array[String]): Unit = {
    val in = read
    val a = cu.ArrayBuffer.empty[Int]
    val b = cu.ArrayBuffer.empty[Int]
    for(i <- 0 until in.length)
      if(in(i) == 'l') a.append(i+1)
      else b.append(i+1)
    println(b.mkString("\n"))
    println(a.reverse.mkString("\n"))
  }

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

    @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 CF265C {
  def main(args: Array[String]) {
    val s = readLine()
    print((1 to s.length)
      .sortWith((i, j) => (i < j && s(i - 1) == 'r') | (i > j && s(j - 1) == 'l'))
      .mkString("\n"))
  }
}

object CF265C {
  def main(args: Array[String]) {
    val s = readLine()
    print((0 until s.length)
      .sortWith((i, j) => (i < j && s(i) == 'r') | (i > j && s(j) == 'l'))
      .map(_ + 1)
      .mkString("\n"))
  }
}

object Main extends App {
  import scala.io._
  val input = Source.stdin
  val s = input.getLines().next
  val n = s.length
  println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).toList.mkString("", "\n", ""))
  println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).toList.mkString("", "\n", ""))
}

object Main extends App {
  import scala.io._
  val input = Source.stdin
  val s = input.getLines().next
  val n = s.length
  println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).mkString("", "\n", ""))
  println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).mkString("", "\n", ""))
}

object Main extends App {
  import scala.io._
  val input = Source.stdin
  val s = input.getLines().next
  val n = s.length
  println((for(i <- 0 until n; if s(i) == 'r') yield (i+1)).mkString("\n"))
  println((for(i <- (n-1) to 0 by -1; if s(i) == 'l') yield (i+1)).mkString("\n"))
}

import scala.collection.mutable.LinkedList
object Main265C {
  def main(args: Array[String]) {
    val cmds = readLine
    val list = LinkedList(-1, -1)
    var beginning = list
    var ending = list.next
    var nextNum = 1
    for (c <- cmds) {
      beginning.next = new LinkedList(nextNum, ending)
      if (c == 'l')
        ending = beginning.next
      else
        beginning = beginning.next
      nextNum += 1
    }
    var next = list.next
    val sb = new StringBuilder()
    while (next.elem != -1) {
      sb.append(next.elem).append("\n")
      next = next.next
    }
    print(sb)
  }
}


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[this] 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 = {
    if (oj){ System.err.println(s) }
  }
  def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    private[this] 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
  }
}

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

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
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve2(): Int = {
    val A, B = ni()
    val D = abs(A - B)
    var i = 0
    while(true) {
      val s = i.toLong * (i + 1) / 2
      if (s >= D && s % 2 == D % 2) {
        return i
      }
      i += 1
    }

    ???
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      out.println(solve2())
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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