An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code $$$091$$$), a colon (ASCII code $$$058$$$), some (possibly zero) vertical line characters (ASCII code $$$124$$$), another colon, and a closing bracket (ASCII code $$$093$$$). The length of the accordion is the number of characters in it.For example, [::], [:||:] and [:|||:] are accordions having length $$$4$$$, $$$6$$$ and $$$7$$$. (:|:), {:||:}, [:], ]:||:[ are not accordions. You are given a string $$$s$$$. You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from $$$s$$$, and if so, what is the maximum possible length of the result?

The only line contains one string $$$s$$$ ($$$1 \le |s| \le 500000$$$). It consists of lowercase Latin letters and characters [, ], : and |.

If it is not possible to obtain an accordion by removing some characters from $$$s$$$, print $$$-1$$$. Otherwise print maximum possible length of the resulting accordion.

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 S = ns()
    val open = S.indexWhere(_ == '[')
    val close = S.lastIndexWhere(_ == ']')

    if (open != -1 && close != -1) {
      val first = S.indexWhere(_ == ':', open + 1)
      val last = S.lastIndexWhere(_ == ':', close - 1)
      if (first != -1 && last != -1 && open < first && first < last && last < close) {
        val ans = S.slice(first + 1, last).count(_ == '|') + 4
        out.println(ans)
      } else {
        out.println(-1)
      }
    } else {
      out.println(-1)
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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

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

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

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

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

object EDU_58_B {

  type In = (String)
  type Out = Int

  def solve(in: In): Out = {
    val (s) = in

    def eat(s: String, c: Char): Option[String] =
      s.indexOf(c) match {
        case -1 => None
        case i  => Some(s.substring(i + 1))
      }

    val lines = for {
      p1 <- eat(s, '[')
      p2 <- eat(p1, ':')
      r = p2.reverse
      p4 <- eat(r, ']')
      p3 <- eat(p4, ':')
    } yield p3.count(_ == '|')

    lines match {
      case None => -1
      case Some(i) => i + 4
    }
  }

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

  def formatIn(i: Input): In       = (i.nextLine)
  def formatOut(out: Out): String  = out.toString

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

  import java.io.InputStream
  import java.util.Scanner

  import language.implicitConversions

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

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

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

  // A frequently used number
  val modulo = 1000000007

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

import java.util.regex.Pattern

import scala.io.StdIn

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

  val magicMod = 1000000007

  def doCase(caseNo: Int): Unit = {
    val str = readLine()

    var state = 0
    var i = 0
    while (i < str.length) {
        if (state == 0 && str(i) == '[') {
          state += 1
        } else if (state == 1 && str(i) == ':') {
          state += 1
        } else if (state == 2 && str(i) == ':') {
          state += 1
        } else if (state == 3 && str(i) == ']') {
        state += 1
        }
      i += 1
    }

    if (state != 4) {
      println(-1)
      return
    }

    var firstLBracket : Option[Int] = None
    var lastRBracket : Option[Int] = None

    i = 0
    while (i < str.length) {
      if (str(i) == '[') {
        firstLBracket = firstLBracket.orElse(Some(i))
      } else if (str(i) == ']') {
        lastRBracket = Some(i)
      }
      i += 1
    }

    if (firstLBracket.isEmpty || lastRBracket.isEmpty || firstLBracket.get > lastRBracket.get) {
      println(-1)
      return
    }

    var barCount = 0
    val cumulativeBars = Array.fill(str.length + 1)(0)

    i = 0
    while (i <= str.length) {
      cumulativeBars(i) = barCount
      if (i < str.length && str(i) == '|') {
        barCount += 1
      }
      i += 1
    }

    var colons : List[Int] = List()
    i = firstLBracket.get
    while (i < lastRBracket.get) {
      if (str(i) == ':') {
        colons ::= i
      }
      i += 1
    }
    colons = colons.reverse

    var bestCount = 0

    val l = colons.head
    val r = colons.last
    val count = cumulativeBars(r) - cumulativeBars(l)
    bestCount = if (bestCount < count) count else bestCount

    println(bestCount + 4)
  }

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

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

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

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

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 S = ns()
    val open = S.indexWhere(_ == '[')
    val first = S.indexWhere(_ == ':')
    val last = S.lastIndexWhere(_ == ':')
    val close = S.lastIndexWhere(_ == ']')
    val found = open != -1 && first != -1 && last != -1 && close != -1
    if (found && open < first && first < last && last < close) {
      val ans = S.slice(first + 1, last).count(_ == '|') + 4
      out.println(ans)
    } else {
      out.println(-1)
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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

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

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

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

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

object 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 S = ns()
    val open = S.indexWhere(_ == '[')
    val first = S.indexWhere(_ == ':')
    val last = S.lastIndexWhere(_ == ':')
    val close = S.lastIndexWhere(_ == ']')
    if (open < first && first < last && last < close) {
      val ans = S.slice(first + 1, last).count(_ == '|') + 4
      out.println(ans)
    } else {
      out.println(-1)
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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

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

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

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

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

object EDU_58_B {

  type In = (String)
  type Out = Int

  def solve(in: In): Out = {
    val (s) = in

    val model = "[::]"

    val ans = {
      def loop(in: Seq[Char], out: String, nextChars: String, colonCount: Int): String = in match {
        case Seq() => out
        case _ if nextChars.isEmpty => out
        case _ => in.head match {
          case h if h == nextChars.head             => loop(in.tail, out + h, nextChars.tail, colonCount)
          case h if h == nextChars.head && h == ':' => loop(in.tail, out + h, nextChars.tail, colonCount + 1)
          case h if h == '|' && colonCount == 1     => loop(in.tail, out + h, nextChars, colonCount)
          case _                                    => loop(in.tail, out, nextChars, colonCount)
        }
      }
      loop(s, "", model, 0)
    }

    /*s.foldLeft("") { (acc, c) =>
      (acc, c) match {
        case ("", '[') => "["
        case ("[", ':') => "[:"
        case (_, '|') if acc.matches("""^\[\:\|*""") => acc + '|'
        case (_, ':') if acc.matches("""^\[\:\|*""") => acc + ':'
        case (_, ']') if acc.matches("""^\[\:\|*\:""") => acc + ']'
        case _ => acc
      }
    }*/

    if(ans.matches("""^\[\:\|*\:\]$""")) ans.length else -1

  }

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

  def formatIn(i: Input): In       = (i.nextLine)
  def formatOut(out: Out): String  = out.toString

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

  import java.io.InputStream
  import java.util.Scanner

  import language.implicitConversions

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

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

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

  // A frequently used number
  val modulo = 1000000007

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

object EDU_58_B {

  type In = (String)
  type Out = Int

  def solve(in: In): Out = {
    val (s) = in

    val Reg = """^\[\:\|*\:\]$"""
    def isAccordian(s: String) = s matches Reg

    val a = "[::]"

    val p1 = s.dropWhile(_ != '[')

    val ans = s.foldLeft("") { (acc, c) =>
      (acc, c) match {
        case ("", '[') => "["
        case ("[", ':') => "[:"
        case (_, '|') if acc.matches("""^\[\:\|*""") => acc + '|'
        case (_, ':') if acc.matches("""^\[\:\|*""") => acc + ':'
        case (_, ']') if acc.matches("""^\[\:\|*\:""") => acc + ']'
        case _ => acc
      }
    }

    if(ans.matches(Reg)) ans.length else -1

  }

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

  def formatIn(i: Input): In       = (i.nextLine)
  def formatOut(out: Out): String  = out.toString

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

  import java.io.InputStream
  import java.util.Scanner

  import language.implicitConversions

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

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

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

  // A frequently used number
  val modulo = 1000000007

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

import java.util.regex.Pattern

import scala.io.StdIn

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

  val magicMod = 1000000007

  def doCase(caseNo: Int): Unit = {
    val str = readLine()

    if (!Pattern.matches(".*\\[.*:.*:.*\\].*", str)) {
      println(-1)
      return
    }

    var firstLBracket : Option[Int] = None
    var lastRBracket : Option[Int] = None

    var i = 0
    while (i < str.length) {
      if (str(i) == '[') {
        firstLBracket = firstLBracket.orElse(Some(i))
      } else if (str(i) == ']') {
        lastRBracket = Some(i)
      }
      i += 1
    }

    if (firstLBracket.isEmpty || lastRBracket.isEmpty || firstLBracket.get > lastRBracket.get) {
      println(-1)
      return
    }

    var barCount = 0
    val cumulativeBars = Array.fill(str.length + 1)(0)

    i = 0
    while (i <= str.length) {
      cumulativeBars(i) = barCount
      if (i < str.length && str(i) == '|') {
        barCount += 1
      }
      i += 1
    }

    var colons : List[Int] = List()
    i = firstLBracket.get
    while (i < lastRBracket.get) {
      if (str(i) == ':') {
        colons ::= i
      }
      i += 1
    }
    colons = colons.reverse

    var bestCount = 0
    for (List(l, r) <- colons.sliding(2)) {
      val count = cumulativeBars(r) - cumulativeBars(l)
      bestCount = if (bestCount < count) count else bestCount
    }

    println(bestCount + 4)
  }

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

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

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

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


You are given a tree (an undirected connected acyclic graph) consisting of $$$n$$$ vertices and $$$n - 1$$$ edges. A number is written on each edge, each number is either $$$0$$$ (let's call such edges $$$0$$$-edges) or $$$1$$$ (those are $$$1$$$-edges).Let's call an ordered pair of vertices $$$(x, y)$$$ ($$$x \ne y$$$) valid if, while traversing the simple path from $$$x$$$ to $$$y$$$, we never go through a $$$0$$$-edge after going through a $$$1$$$-edge. Your task is to calculate the number of valid pairs in the tree.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 200000$$$) — the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each denoting an edge of the tree. Each edge is represented by three integers $$$x_i$$$, $$$y_i$$$ and $$$c_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$0 \le c_i \le 1$$$, $$$x_i \ne y_i$$$) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree.

Print one integer — the number of valid pairs of vertices.

NoteThe picture corresponding to the first example:

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

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

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[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
  import scala.reflect.ClassTag

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

  def solve(): Unit = {
    val N = ni()
    val uf0, uf1 = new UnionFind(N)
    val flg0, flg1 = Array.ofDim[Boolean](N)
    REP(N - 1) { i =>
      val v, u = ni() - 1
      val w = ni()
      (if (w == 0) uf0 else uf1).unite(v, u)
      val flg = if (w == 0) flg0 else flg1
      flg(v) = true
      flg(u) = true
    }

    var ans = 0L
    val used0, used1 = Array.ofDim[Boolean](N)
    REP(N) { i =>
      val id0 = uf0.find(i)
      val id1 = uf1.find(i)

      // 0-0
      if (!used0(id0)) {
        used0(id0) = true
        val n = uf0.cntNodes(id0)
        debug(s"0-0 n:$n")
        ans += n.toLong * (n - 1)
      }

      // 1-1
      if (!used1(id1)) {
        used1(id1) = true
        val n = uf1.cntNodes(id1)
        debug(s"1-1 n:$n")
        ans += n.toLong * (n - 1)
      }

      // 0-1
      if (flg0(i) && flg1(i)) {
        val n0 = uf0.cntNodes(id0)
        val n1 = uf1.cntNodes(id1)
        debug(s"0-1 n0:$n0 n1:$n1")
        ans += (n0 - 1).toLong * (n1 - 1)
      }
    }
    out.println(ans)
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    REP(n) (i => par(i) = i)
    val rank: Array[Int] = Array.fill[Int](n)(1) // 集合の要素数
    private val visits = Array.ofDim[Int](n) // 訪れた場所をfind毎に用意するのがもったいないのでつかいまわす

    def find(x: Int): Int = {
      var ptr = 0
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          visits(ptr) = x
          ptr += 1
          step(par(x))
        }
      }

      val res = step(x)
      REP(ptr){ i => par(visits(i)) = res }
      res
    }

    private def merge(node: Int, rt: Int): Int = {
      par(node) = rt
      rank(rt) += rank(node)
      rt
    }

    def unite(x: Int, y: Int): Int = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 == y1) x1
      else {
        if (rank(x1) < rank(y1))
          merge(x1, y1)
        else
          merge(y1, x1)
      }
    }

    /**
      * xを解決する必要がないときは直にrankをみる
      */
    def cntNodes(x: Int): Int = rank(find(x))
  }
}


In the Isle of Guernsey there are n different types of coins. For each i (1 ≤ i ≤ n), coin of type i is worth ai cents. It is possible that ai = aj for some i and j (i ≠ j). Bessie has some set of these coins totaling t cents. She tells Jessie q pairs of integers. For each i (1 ≤ i ≤ q), the pair bi, ci tells Jessie that Bessie has a strictly greater number of coins of type bi than coins of type ci. It is known that all bi are distinct and all ci are distinct. Help Jessie find the number of possible combinations of coins Bessie could have. Two combinations are considered different if there is some i (1 ≤ i ≤ n), such that the number of coins Bessie has of type i is different in the two combinations. Since the answer can be very large, output it modulo 1000000007 (109 + 7). If there are no possible combinations of coins totaling t cents that satisfy Bessie's conditions, output 0.

The first line contains three space-separated integers, n, q and t (1 ≤ n ≤ 300; 0 ≤ q ≤ n; 1 ≤ t ≤ 105). The second line contains n space separated integers, a1, a2, ..., an (1 ≤ ai ≤ 105). The next q lines each contain two distinct space-separated integers, bi and ci (1 ≤ bi, ci ≤ n; bi ≠ ci). It's guaranteed that all bi are distinct and all ci are distinct.

A single integer, the number of valid coin combinations that Bessie could have, modulo 1000000007 (109 + 7).

NoteFor the first sample, the following 3 combinations give a total of 17 cents and satisfy the given conditions: {0 of type 1, 1 of type 2, 3 of type 3, 2 of type 4}, {0, 0, 6, 1}, {2, 0, 3, 1}.No other combinations exist. Note that even though 4 occurs in both bi and ci,  the problem conditions are still satisfied because all bi are distinct and all ci are distinct.

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

object A extends App {
  val Array(n, q, t) = readLine split ' ' map (_.toInt)
  val a = readLine split ' ' map (_.toInt)
  val b = Array.fill(n)(-1)

  val less = Array.fill(n)(-1)
  val greater = Array.fill(n)(-1)
  for (i <- 1 to q) {
    val Array(u, v) = readLine split ' ' map (_.toInt - 1)
    less(u) = v
    greater(v) = u
  }

  var tt = t.toLong
  for (i <- 0 until n) {
    if (greater(i) == -1) {
      b(i) = a(i)
      var u = less(i)
      while (u != -1) {
        b(u) = b(greater(u)) + a(u)
        u = less(u)
      }
    }
    if (less(i) == -1) {
      var cnt = 0L
      var u = greater(i)
      while (u != -1) {
        cnt += 1
        tt -= cnt * a(u)
        u = greater(u)
      }
    }
  }

  if (tt < 0) {
    println("0")
    System.exit(0)
  }
  for (i <- 0 until n)
    if (b(i) == -1) {
      println("0")
      System.exit(0)
    }

  val ttt = tt.toInt
  val dp = Array.fill(ttt+1)(0)
  dp(0) = 1
  for (v <- b)
    for (i <- v to ttt)
      dp(i) = (dp(i) + dp(i-v)) % 1000000007
  println(dp(ttt))
}

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

object A extends App {
  val Array(n, q, t) = readLine split ' ' map (_.toInt)
  val a = readLine split ' ' map (_.toInt)
  val b = Array.fill(n)(-1)

  val less = Array.fill(n)(-1)
  val greater = Array.fill(n)(-1)
  for (i <- 1 to q) {
    val Array(u, v) = readLine split ' ' map (_.toInt - 1)
    less(u) = v
    greater(v) = u
  }

  var tt = t.toLong
  for (i <- 0 until n) {
    if (greater(i) == -1) {
      b(i) = a(i)
      var u = less(i)
      while (u != -1) {
        b(u) = b(greater(u)) + a(u)
        u = less(u)
      }
    }
    if (less(i) == -1) {
      var cnt = 0L
      var u = greater(i)
      while (u != -1) {
        cnt += 1
        tt -= cnt * a(u)
        u = greater(u)
      }
    }
  }

  if (tt < 0) {
    println("0")
    System.exit(0)
  }
  for (i <- 0 until n)
    if (b(i) == -1) {
      println("0")
      System.exit(0)
    }

  val ttt = tt.toInt
  val dp = Array.fill(ttt+1)(0)
  dp(0) = 1
  for (v <- b)
    for (i <- v to ttt)
      dp(i) += dp(i-v)
  println(dp(ttt))
}

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

object A extends App {
  val Array(n, q, t) = readLine split ' ' map (_.toInt)
  val a = readLine split ' ' map (_.toInt)
  val b = Array.fill(n)(-1)

  val less = Array.fill(n)(-1)
  val greater = Array.fill(n)(-1)
  for (i <- 1 to q) {
    val Array(u, v) = readLine split ' ' map (_.toInt - 1)
    less(u) = v
    greater(v) = u
  }

  var tt = t.toLong
  for (i <- 0 until n) {
    if (greater(i) == -1) {
      b(i) = a(i)
      var u = less(i)
      while (u != -1) {
        b(u) = b(greater(u)) + a(u)
        u = less(u)
      }
    }
    if (less(i) == -1) {
      var cnt = 0L
      var u = greater(i)
      while (u != -1) {
        cnt += 1
        tt -= cnt * a(u)
        u = greater(u)
      }
    }
  }

  if (tt < 0) {
    println("0")
    System.exit(0)
  }
  for (i <- 0 until n)
    if (b(i) == -1) {
      println("0")
      System.exit(0)
    }

  val ttt = tt.toInt
  val dp = Array.fill(ttt+1)(0L)
  dp(0) = 1
  for (v <- b)
    for (i <- v to ttt)
      dp(i) += dp(i-v)
  println(dp(ttt))
}


Initially there was an array $$$a$$$ consisting of $$$n$$$ integers. Positions in it are numbered from $$$1$$$ to $$$n$$$.Exactly $$$q$$$ queries were performed on the array. During the $$$i$$$-th query some segment $$$(l_i, r_i)$$$ $$$(1 \le l_i \le r_i \le n)$$$ was selected and values of elements on positions from $$$l_i$$$ to $$$r_i$$$ inclusive got changed to $$$i$$$. The order of the queries couldn't be changed and all $$$q$$$ queries were applied. It is also known that every position from $$$1$$$ to $$$n$$$ got covered by at least one segment.We could have offered you the problem about checking if some given array (consisting of $$$n$$$ integers with values from $$$1$$$ to $$$q$$$) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to $$$0$$$.Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.If there are multiple possible arrays then print any of them.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of elements of the array and the number of queries perfomed on it. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le q$$$) — the resulting array. If element at some position $$$j$$$ is equal to $$$0$$$ then the value of element at this position can be any integer from $$$1$$$ to $$$q$$$.

Print "YES" if the array $$$a$$$ can be obtained by performing $$$q$$$ queries. Segments $$$(l_i, r_i)$$$ $$$(1 \le l_i \le r_i \le n)$$$ are chosen separately for each query. Every position from $$$1$$$ to $$$n$$$ should be covered by at least one segment.  Otherwise print "NO". If some array can be obtained then print $$$n$$$ integers on the second line — the $$$i$$$-th number should be equal to the $$$i$$$-th element of the resulting array and should have value from $$$1$$$ to $$$q$$$. This array should be obtainable by performing exactly $$$q$$$ queries. If there are multiple possible arrays then print any of them.

NoteIn the first example you can also replace $$$0$$$ with $$$1$$$ but not with $$$3$$$.In the second example it doesn't really matter what segments to choose until query $$$10$$$ when the segment is $$$(1, 3)$$$.The third example showcases the fact that the order of queries can't be changed, you can't firstly set $$$(1, 3)$$$ to $$$6$$$ and after that change $$$(2, 2)$$$ to $$$5$$$. The segment of $$$5$$$ should be applied before segment of $$$6$$$.There is a lot of correct resulting arrays for the fourth example.

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, Q = ni()
    val A = na(N)

    val seg = new SegmentTree(N)
    rep(N) { i =>
      val a = A(i)
      if (a != 0) seg.update(i, a)
    }

    val L = Array.fill[Int](Q + 1)(-1)
    val R = Array.fill[Int](Q + 1)(-1)

    val zeros = ArrayBuffer[(Int, Int)]()
    var zero = -1

    rep(N) { i =>
      val a = A(i)
      if (L(a) == -1) L(a) = i
      R(a) = i

      if (a == 0) {
        if (zero == -1) zero = i
      } else if (zero != -1) {
        zeros += ((zero, i))
        zero = -1
      }
    }
    if (zero != -1) {
      zeros += ((zero, N))
    }

    var ok = true
    rep(Q, 1) { q =>
      if (L(q) != -1) {
        val ms = seg.query(L(q), R(q) + 1)
        ok &= ms == q
      }
    }

    // Qがでてくるか、0があれば
    val hasQ = L(Q) != -1
    ok &= hasQ || zeros.nonEmpty

    if (ok) {
      out.println("YES")

      def fillZero(zero: (Int, Int)): Unit = {
        val (l, r) = zero
        val x = if (l > 0) A(l - 1) else A(r)
        fillZeroBy(zero, x)
      }

      def fillZeroBy(zero: (Int, Int), x: Int): Unit = {
        val (l, r) = zero
        rep(r - l)(i => A(l + i) = x)
      }

      // 全部0の場合も!hasQかつzeros.length == 1 なのでこれで大丈夫
      if (!hasQ) {
        rep(zeros.length - 1)(i => fillZero(zeros(i)))
        fillZeroBy(zeros.last, Q) // 一箇所Qで埋める
      } else {
        rep(zeros.length)(i => fillZero(zeros(i)))
      }

      out.println(A.mkString(" "))
    } else {
      out.println("NO")
    }
  }

  class SegmentTree(n: Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = Array.fill(2 * N - 1)(Integer.MAX_VALUE)

    def update(i: Int, a: Int): Unit = {
      var k = N - 1 + i
      dat(k) = a
      while(k > 0) {
        k = (k - 1) / 2
        dat(k) = min(dat(2 * k + 1), dat(2 * k + 2))
      }
    }

    def query(a: Int, b: Int): Int = {
      def step(k: Int, l: Int, r: Int): Int = {
        if (r <= a || b <= l) {
          Integer.MAX_VALUE
        } else if (a <= l && r <= b) {
          dat(k)
        } else {
          val vl = step(k * 2 + 1, l, (l + r) / 2)
          val vr = step(k * 2 + 2, (l + r) / 2, r)
          min(vl, vr)
        }
      }

      step(0, 0, N)
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

import java.util.StringTokenizer
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.security.SecureRandom

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

    //COMMENT ME !
    runTest(Test.t7)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val Q = l1.int
    val arrLine = readLine
    val arr = new Array[Int](n)
    val startTime = System.currentTimeMillis()

    class Cell(val ind: Int, val value: Int) {
      var prev: Cell = null
      var next: Cell = null
    }

    class ArrList() {
      var first: Cell = null
      var last: Cell = null

      def add(cc: Cell) {
        if (first == null) {
          first = cc
        } else {
          last.next = cc
          cc.prev = last
        }
        last = cc
      }
      def remove(cc: Cell) {
        if (cc.prev != null) {
            cc.prev.next = cc.next
        }
        if (cc.next != null) {
          cc.next.prev = cc.prev
        }
        if (cc == first) {
          first = cc.next
        }
        if (cc == last) {
          last = cc.prev
        }
      }
      def mkString: String= {
        var cur = first
        var res = ""
        while (cur != null) {
//          res += cur.ind+"-"+cur.value + ","
          res += cur.value + ","
          cur = cur.next
        }
        res
      }
    }
    val aList = new ArrList()

    for(i <- 0 until n) {
      val vv = arrLine.int
      arr(i) = vv
    }

    var cur = aList.first
    while (cur != null) {
      print(cur.value + " ")
      cur = cur.next
    }
    println

//    if (arr(0) == 1912) {
//      var acc = ""
//      for(i <- 0 until n) {
//        acc += arr(i) + " "
//        if (i % 50 == 0) {
//          println(acc)
//          acc = ""
//        }
//      }
//    }

    var lastPresent = false
    var zeroInd = -1
    for( i <- 0 until n) {
      if (arr(i) == Q) lastPresent = true
      if (arr(i) == 0) zeroInd = i
    }
    if (!lastPresent && zeroInd != -1) arr(zeroInd) = Q

    //copy to linked list
    val starts = new Array[Cell](Q+1)
    val counts = new Array[Int](Q+1)
    for(i <- 0 until n) {
      val q = arr(i)
      val cc = new Cell(i, q)
      if (starts(q) == null) { starts(q) = cc }
      counts(q) += 1
      aList.add(cc)
    }

    val resArr = new Array[Int](n)
    var good = true

//    def calc(): Unit = {
//      for(qu <- Q to 1 by -1) {
//        var started = false
//        var finished = false
//        for(i <- 0 until n) {
//          (started, finished) match {
//            case (false, false) => {
//              if (arr(i) == qu) {
//                started = true
//                arr(i) = -1
//                resArr(i) = qu
//              }
//            }
//            case (true, false) => {
//              if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {
//                finished = true
//              } else { //still continue
//                if (arr(i) != -1) {
//                  resArr(i) = qu
//                  arr(i) = -1
//                }
//              }
//            }
//            case (true, true) => {
//              if (arr(i) == qu) {
//                good = false
//  //              if (arr(0) == 1912) {
//  //                println("Break on " + qu + " i=" + i)
//  //              }
//              }
//            }
//          }
//          if (!good) return
//        }
////        debug("After: " + qu)
//      }
//    }
//    calc()

    debug("After query " + "0" + ": " + aList.mkString)

    val sss = System.currentTimeMillis()
    var totalSteps = 0
    def calc2(): Unit = {
      for(qu <- Q to 1 by -1) {
        var started = false
        var finished = false
        var curCell = starts(qu)
        while(good && curCell != null && counts(qu) > 0) {
          totalSteps += 1
          (started, finished) match {
            case (false, false) => {
              if (curCell.value == qu) {
                started = true
                aList.remove(curCell)
                resArr(curCell.ind) = qu
                counts(qu) -= 1
//                debug("Removed first cell" + curCell)
              }
            }
            case (true, false) => {
              if (curCell.value != qu && curCell.value != 0) {
                finished = true
//                debug("finished")
              } else { //still continue
                aList.remove(curCell)
                resArr(curCell.ind) = qu
                if (curCell.value == qu) { counts(qu) -= 1 }
//                debug("Removed subseq cell" + curCell)
              }
            }
            case (true, true) => {
              if (curCell.value == qu) {
                debug("Fail at secondary piece: " + qu)
                good = false
              }
            }
          }
//          debug(" - After step " + qu + ": " + aList.mkString)
          curCell = curCell.next
        }
        debug("After query " + qu + ": " + aList.mkString)
      }
    }
    calc2
    val ddd = System.currentTimeMillis() - sss
    debug("calc2 dur " + ddd + "  steps=" + totalSteps)

    var last = resArr(n-1)
//    if (last == 0) last = Q
    for(i <- n-1 to 0 by -1) {
      if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }
    last = resArr(0)
    for(i <- 0 until n) {
       if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }

    lastPresent = false
    for( i <- 0 until n) {
      if (resArr(i) == Q) lastPresent = true
    }
    if (!lastPresent) {
      debug("Fail at top query absent")
      good = false
    }

    if (good) {
      outLn("YES")
      outLn(resArr.mkString(" "))
    } else {
      outLn("NO")
    }

    debug("================= RESULT ================== ")
    val endTime = System.currentTimeMillis() - startTime
    debug("Exec time: " + endTime)
    finish
  }

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

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

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

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

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

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

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

val sa2 = """
"""

val t7 = """
50 2
0 1 0 1 0 0 1 0 1 1 0 1 1 1 2 2 0 2 0 2 0 2 0 0 2 2 2 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 1 0 1 1 0 1 0 0
"""

val m1 = """
4 3
1 0 2 3
"""

val m2 = """
20 20
17 17 19 19 17 20 20 17 16 16 16 16 16 18 18 18 18 18 6 0
"""

def gen = {
  val runStart = System.currentTimeMillis()
  val n = 200000
  val q = 200000
  val rr = new SecureRandom
  val arr = new Array[Int](n)
  for(i <- 1 to q) {
    val start = rr.nextInt(n-1)
    val length = 1 //rr.nextInt(n-start-1)
//    val length = n-q
    val end = length + start
    for (j <- start to end) {
      arr(j) = i
    }
  }
  val res = s"$n $q" + "\n" + arr.mkString(" ")
  val runEnd = System.currentTimeMillis() - runStart
  println("Gen time " + runEnd)
  println(res)
  res
}

}

}

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, Q = ni()
    val A = na(N)

    val seg = new SegmentTree(N)
    rep(N) { i =>
      val a = A(i)
      seg.update(i, a)
    }

    val L = Array.fill[Int](Q + 1)(-1)
    val R = Array.fill[Int](Q + 1)(-1)

    rep(N) { i =>
      val a = A(i)
      if (L(a) == -1) L(a) = i
      R(a) = i
    }

    var ok = true
    rep(Q, 1) { q =>
      val ms = seg.query(L(q), R(q) + 1)
      ok &= ms == Integer.MAX_VALUE || ms == q
    }

    if (ok) {
      out.println("YES")
      rep(N - 1, 1) { i =>
        if (A(i) == 0) A(i) = A(i - 1)
      }

      rep_r(N - 1) { i =>
        if (A(i) == 0) A(i) = A(i + 1)
      }

      if (A(0) == 0) {
        rep(N)(i => A(i) = Q)
      }

      out.println(A.mkString(" "))
    } else {
      out.println("NO")
    }
  }

  class SegmentTree(n: Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = Array.fill(2 * N - 1)(0)

    def update(i: Int, a: Int): Unit = {
      var k = N - 1 + i
      dat(k) = a
      while(k > 0) {
        k = (k - 1) / 2
        dat(k) = min(dat(2 * k + 1), dat(2 * k + 2))
      }
    }

    def query(a: Int, b: Int): Int = {
      def step(k: Int, l: Int, r: Int): Int = {
        if (r <= a || b <= l) {
          Integer.MAX_VALUE
        } else if (a <= l && r <= b) {
          dat(k)
        } else {
          val vl = step(k * 2 + 1, l, (l + r) / 2)
          val vr = step(k * 2 + 2, (l + r) / 2, r)
          min(vl, vr)
        }
      }

      step(0, 0, N)
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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, Q = ni()
    val A = na(N)

    val seg = new SegmentTree(N)
    rep(N) { i =>
      val a = A(i)
      seg.update(i, a)
    }

    val L = Array.fill[Int](Q + 1)(-1)
    val R = Array.fill[Int](Q + 1)(-1)

    val zeros = ArrayBuffer[(Int, Int)]()
    var zero = -1

    rep(N) { i =>
      val a = A(i)
      if (L(a) == -1) L(a) = i
      R(a) = i

      if (a == 0) {
        if (zero == -1) zero = i
      } else if (zero != -1) {
        zeros += ((zero, i))
        zero = -1
      }
    }
    if (zero != -1) {
      zeros += ((zero, N))
    }

    var ok = true
    rep(Q, 1) { q =>
      val ms = seg.query(L(q), R(q) + 1)
      ok &= ms == Integer.MAX_VALUE || ms == q
    }

    // Qがでてくるか、0があれば
    val hasQ = L(Q) != -1
    ok &= hasQ || zeros.nonEmpty

    if (ok) {
      out.println("YES")

      def fillZero(zero: (Int, Int)): Unit = {
        val (l, r) = zero
        val x = if (l > 0) A(l - 1) else A(r)
        fillZeroBy(zero, x)
      }

      def fillZeroBy(zero: (Int, Int), x: Int): Unit = {
        val (l, r) = zero
        rep(r - l)(i => A(l + i) = x)
      }

      // 全部0の場合も!hasQかつzeros.length == 1 なのでこれで大丈夫
      if (!hasQ) {
        rep(zeros.length - 1)(i => fillZero(zeros(i)))
        fillZeroBy(zeros.last, Q) // 一箇所Qで埋める
      } else {
        rep(zeros.length)(i => fillZero(zeros(i)))
      }

      out.println(A.mkString(" "))
    } else {
      out.println("NO")
    }
  }

  class SegmentTree(n: Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = Array.fill(2 * N - 1)(0)

    def update(i: Int, a: Int): Unit = {
      var k = N - 1 + i
      dat(k) = a
      while(k > 0) {
        k = (k - 1) / 2
        dat(k) = min(dat(2 * k + 1), dat(2 * k + 2))
      }
    }

    def query(a: Int, b: Int): Int = {
      def step(k: Int, l: Int, r: Int): Int = {
        if (r <= a || b <= l) {
          Integer.MAX_VALUE
        } else if (a <= l && r <= b) {
          dat(k)
        } else {
          val vl = step(k * 2 + 1, l, (l + r) / 2)
          val vr = step(k * 2 + 2, (l + r) / 2, r)
          min(vl, vr)
        }
      }

      step(0, 0, N)
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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, Q = ni()
    val A = na(N)

    val seg = new SegmentTree(N)
    rep(N) { i =>
      val a = A(i)
      seg.update(i, a)
    }

    val L = Array.fill[Int](Q + 1)(-1)
    val R = Array.fill[Int](Q + 1)(-1)

    rep(N) { i =>
      val a = A(i)
      if (L(a) == -1) L(a) = i
      R(a) = i
    }

    var ok = true
    rep(Q, 1) { q =>
      val ms = seg.query(L(q), R(q) + 1)
      ok &= ms == Integer.MAX_VALUE || ms == q
    }

    if (ok) {
      out.println("YES")
      rep(N - 1, 1) { i =>
        if (A(i) == 0) A(i) = A(i - 1)
      }

      rep_r(N - 1) { i =>
        if (A(i) == 0) A(i) = A(i + 1)
      }

      if (A(0) == 0) {
        rep(N)(i => A(i) = 1)
      }

      out.println(A.mkString(" "))
    } else {
      out.println("NO")
    }
  }

  class SegmentTree(n: Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = Array.fill(2 * N - 1)(0)

    def update(i: Int, a: Int): Unit = {
      var k = N - 1 + i
      dat(k) = a
      while(k > 0) {
        k = (k - 1) / 2
        dat(k) = min(dat(2 * k + 1), dat(2 * k + 2))
      }
    }

    def query(a: Int, b: Int): Int = {
      def step(k: Int, l: Int, r: Int): Int = {
        if (r <= a || b <= l) {
          Integer.MAX_VALUE
        } else if (a <= l && r <= b) {
          dat(k)
        } else {
          val vl = step(k * 2 + 1, l, (l + r) / 2)
          val vr = step(k * 2 + 2, (l + r) / 2, r)
          min(vl, vr)
        }
      }

      step(0, 0, N)
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

import java.util.StringTokenizer
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

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

    //COMMENT ME !
//    runTest(Test.t1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val Q = l1.int
    val arrLine = readLine
    val arr = new Array[Int](n)

    for(i <- 0 until n) {
      arr(i) = arrLine.int
    }

    val resArr = new Array[Int](n)
    var good = true
    for(qu <- Q to 1 by -1) {
      var started = false
      var finished = false
      for(i <- 0 until n) {
        (started, finished) match {
          case (false, false) => {
            if (arr(i) == qu) {
              started = true
              arr(i) = -1
              resArr(i) = qu
            }
          }
          case (true, false) => {
            if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {
              finished = true
            } else {
              if (arr(i) != -1)
                resArr(i) = qu
            }
          }
          case (true, true) => {
            if (arr(i) == qu) {
              good = false
            }
          }
        }
      }
      debug("After: " + qu)
    }
    var last = resArr(n-1)
    if (last == 0) last = Q
    for(i <- n-1 to 0 by -1) {
      if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }
    if (good) {
      outLn("YES")
      outLn(resArr.mkString(" "))
    } else {
      outLn("NO")
    }

    debug("================= RESULT ================== ")
    finish
  }

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

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

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

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

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

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

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

val sa2 = """
"""

val t1 = """
4 3
0 1 2 3
"""

}

}

import java.util.StringTokenizer
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

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

    //COMMENT ME !
//    runTest(Test.t1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val Q = l1.int
    val arrLine = readLine
    val arr = new Array[Int](n)

    for(i <- 0 until n) {
      arr(i) = arrLine.int
    }

//    if (arr(0) == 1912) {
//      var acc = ""
//      for(i <- 0 until n) {
//        acc += arr(i) + " "
//        if (i % 50 == 0) {
//          println(acc)
//          acc = ""
//        }
//      }
//    }

    val resArr = new Array[Int](n)
    var good = true
    for(qu <- Q to 1 by -1) {
      var started = false
      var finished = false
      for(i <- 0 until n) {
        (started, finished) match {
          case (false, false) => {
            if (arr(i) == qu) {
              started = true
              arr(i) = -1
              resArr(i) = qu
            }
          }
          case (true, false) => {
            if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {
              finished = true
            } else { //still continue
              if (arr(i) != -1) {
                resArr(i) = qu
                arr(i) = -1
              }
            }
          }
          case (true, true) => {
            if (arr(i) == qu) {
              good = false
              if (arr(0) == 1912) {
                println("Break on " + qu + " i=" + i)
              }
            }
          }
        }
      }
      debug("After: " + qu)
    }
    var last = resArr(n-1)
    if (last == 0) last = Q
    for(i <- n-1 to 0 by -1) {
      if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }
    var lastPresent = false
    for( i <- 0 until n) {
      if (resArr(i) == Q) lastPresent = true
    }
    if (!lastPresent) good = false

    if (good) {
      outLn("YES")
      outLn(resArr.mkString(" "))
    } else {
      outLn("NO")
    }

    debug("================= RESULT ================== ")
    finish
  }

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

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

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

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

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

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

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

val sa2 = """
"""

val t1 = """
4 3
0 1 2 3
"""

}

}

import java.util.StringTokenizer
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

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

    //COMMENT ME !
//    runTest(Test.t1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val Q = l1.int
    val arrLine = readLine
    val arr = new Array[Int](n)

    for(i <- 0 until n) {
      arr(i) = arrLine.int
    }

    val resArr = new Array[Int](n)
    var good = true
    for(qu <- Q to 1 by -1) {
      var started = false
      var finished = false
      for(i <- 0 until n) {
        (started, finished) match {
          case (false, false) => {
            if (arr(i) == qu) {
              started = true
              arr(i) = -1
              resArr(i) = qu
            }
          }
          case (true, false) => {
            if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {
              finished = true
            } else {
              if (arr(i) != -1)
                resArr(i) = qu
            }
          }
          case (true, true) => {
            if (arr(i) == qu) {
              good = false
            }
          }
        }
      }
      debug("After: " + qu)
    }
    var last = resArr(n-1)
    if (last == 0) last = 1
    for(i <- n-1 to 0 by -1) {
      if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }
    if (good) {
      outLn("YES")
      outLn(resArr.mkString(" "))
    } else {
      outLn("NO")
    }

    debug("================= RESULT ================== ")
    finish
  }

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

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

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

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

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

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

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

val sa2 = """
"""

val t1 = """
4 3
0 1 2 3
"""

}

}

import java.util.StringTokenizer
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.security.SecureRandom

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

    //COMMENT ME !
//    runTest(Test.gen)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val Q = l1.int
    val arrLine = readLine
    val arr = new Array[Int](n)
    val startTime = System.currentTimeMillis()

    class Cell(val ind: Int, val value: Int) {
      var prev: Cell = null
      var next: Cell = null
    }

    class ArrList() {
      var first: Cell = null
      var last: Cell = null

      def add(cc: Cell) {
        if (first == null) {
          first = cc
        } else {
          last.next = cc
          cc.prev = last
        }
        last = cc
      }
      def remove(cc: Cell) {
        if (cc.prev != null) {
            cc.prev.next = cc.next
        }
        if (cc.next != null) {
          cc.next.prev = cc.prev
        }
        if (cc == first) {
          first = cc.next
        }
        if (cc == last) {
          last = cc.prev
        }
      }
      def mkString: String= {
        var cur = first
        var res = ""
        while (cur != null) {
//          res += cur.ind+"-"+cur.value + ","
          res += cur.value + ","
          cur = cur.next
        }
        res
      }
    }
    val aList = new ArrList()

    for(i <- 0 until n) {
      val vv = arrLine.int
      arr(i) = vv
    }

    var cur = aList.first
    while (cur != null) {
      print(cur.value + " ")
      cur = cur.next
    }
    println

//    if (arr(0) == 1912) {
//      var acc = ""
//      for(i <- 0 until n) {
//        acc += arr(i) + " "
//        if (i % 50 == 0) {
//          println(acc)
//          acc = ""
//        }
//      }
//    }

    var lastPresent = false
    var zeroInd = -1
    for( i <- 0 until n) {
      if (arr(i) == Q) lastPresent = true
      if (arr(i) == 0) zeroInd = i
    }
    if (!lastPresent && zeroInd != -1) arr(zeroInd) = Q

    //copy to linked list
    val starts = new Array[Cell](Q+1)
    val counts = new Array[Int](Q+1)
    for(i <- 0 until n) {
      val q = arr(i)
      val cc = new Cell(i, q)
      if (starts(q) == null) { starts(q) = cc }
      counts(q) += 1
      aList.add(cc)
    }

    val resArr = new Array[Int](n)
    var good = true

//    def calc(): Unit = {
//      for(qu <- Q to 1 by -1) {
//        var started = false
//        var finished = false
//        for(i <- 0 until n) {
//          (started, finished) match {
//            case (false, false) => {
//              if (arr(i) == qu) {
//                started = true
//                arr(i) = -1
//                resArr(i) = qu
//              }
//            }
//            case (true, false) => {
//              if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {
//                finished = true
//              } else { //still continue
//                if (arr(i) != -1) {
//                  resArr(i) = qu
//                  arr(i) = -1
//                }
//              }
//            }
//            case (true, true) => {
//              if (arr(i) == qu) {
//                good = false
//  //              if (arr(0) == 1912) {
//  //                println("Break on " + qu + " i=" + i)
//  //              }
//              }
//            }
//          }
//          if (!good) return
//        }
////        debug("After: " + qu)
//      }
//    }
//    calc()

//    debug("After query " + "0" + ": " + aList.mkString)

    val sss = System.currentTimeMillis()
    var totalSteps = 0
    def calc2(): Unit = {
      for(qu <- Q to 1 by -1) {
        var started = false
        var finished = false
        var curCell = starts(qu)
        while(good && curCell != null && counts(qu) > 0) {
          totalSteps += 1
          (started, finished) match {
            case (false, false) => {
              if (curCell.value == qu) {
                started = true
                aList.remove(curCell)
                resArr(curCell.ind) = qu
                counts(qu) -= 1
//                debug("Removed first cell" + curCell)
              }
            }
            case (true, false) => {
              if (curCell.value != qu && curCell.value != 0) {
                finished = true
//                debug("finished")
              } else { //still continue
                aList.remove(curCell)
                resArr(curCell.ind) = qu
                counts(qu) -= 1
//                debug("Removed subseq cell" + curCell)
              }
            }
            case (true, true) => {
              if (curCell.value == qu) {
//                debug("Fail at secondary piece: " + qu)
                good = false
              }
            }
          }
//          debug(" - After step " + qu + ": " + aList.mkString)
          curCell = curCell.next
        }
//        debug("After query " + qu + ": " + aList.mkString)
      }
    }
    calc2
    val ddd = System.currentTimeMillis() - sss
    debug("calc2 dur " + ddd + "  steps=" + totalSteps)

    var last = resArr(n-1)
    if (last == 0) last = Q
    for(i <- n-1 to 0 by -1) {
      if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }
    lastPresent = false
    for( i <- 0 until n) {
      if (resArr(i) == Q) lastPresent = true
    }
    if (!lastPresent) {
//      debug("Fail at top query absent")
      good = false
    }

    if (good) {
      outLn("YES")
      outLn(resArr.mkString(" "))
    } else {
      outLn("NO")
    }

    debug("================= RESULT ================== ")
    val endTime = System.currentTimeMillis() - startTime
    debug("Exec time: " + endTime)
    finish
  }

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

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

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

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

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

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

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

val sa2 = """
"""

val t1 = """
4 3
1 0 2 3
"""

val t2 = """
20 20
17 17 19 19 17 20 20 17 16 16 16 16 16 18 18 18 18 18 6 0
"""

def gen = {
  val runStart = System.currentTimeMillis()
  val n = 200000
  val q = 200000
  val rr = new SecureRandom
  val arr = new Array[Int](n)
  for(i <- 1 to q) {
    val start = rr.nextInt(n-1)
    val length = 1 //rr.nextInt(n-start-1)
//    val length = n-q
    val end = length + start
    for (j <- start to end) {
      arr(j) = i
    }
  }
  val res = s"$n $q" + "\n" + arr.mkString(" ")
  val runEnd = System.currentTimeMillis() - runStart
  println("Gen time " + runEnd)
  println(res)
  res
}

}

}

import java.util.StringTokenizer
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

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

    //COMMENT ME !
//    runTest(Test.t1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val Q = l1.int
    val arrLine = readLine
    val arr = new Array[Int](n)

    for(i <- 0 until n) {
      arr(i) = arrLine.int
    }

    val resArr = new Array[Int](n)
    var good = true
    for(qu <- Q to 1 by -1) {
      var started = false
      var finished = false
      for(i <- 0 until n) {
        (started, finished) match {
          case (false, false) => {
            if (arr(i) == qu) {
              started = true
              arr(i) = -1
              resArr(i) = qu
            }
          }
          case (true, false) => {
            if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {
              finished = true
            } else { //still continue
              if (arr(i) != -1) {
                resArr(i) = qu
                arr(i) = -1
              }
            }
          }
          case (true, true) => {
            if (arr(i) == qu) {
              good = false
            }
          }
        }
      }
      debug("After: " + qu)
    }
    var last = resArr(n-1)
    if (last == 0) last = Q
    for(i <- n-1 to 0 by -1) {
      if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }
    var lastPresent = false
    for( i <- 0 until n) {
      if (resArr(i) == Q) lastPresent = true
    }
    if (!lastPresent) good = false

    if (good) {
      outLn("YES")
      outLn(resArr.mkString(" "))
    } else {
      outLn("NO")
    }

    debug("================= RESULT ================== ")
    finish
  }

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

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

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

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

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

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

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

val sa2 = """
"""

val t1 = """
4 3
0 1 2 3
"""

}

}

import java.util.StringTokenizer
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

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

    //COMMENT ME !
//    runTest(Test.t1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val Q = l1.int
    val arrLine = readLine
    val arr = new Array[Int](n)

    for(i <- 0 until n) {
      arr(i) = arrLine.int
    }

    if (arr(0) == 1912) {
      var acc = ""
      for(i <- 0 until n) {
        acc += arr(i) + " "
        if (i % 50 == 0) {
          println(acc)
          acc = ""
        }
      }
    }

    val resArr = new Array[Int](n)
    var good = true
    for(qu <- Q to 1 by -1) {
      var started = false
      var finished = false
      for(i <- 0 until n) {
        (started, finished) match {
          case (false, false) => {
            if (arr(i) == qu) {
              started = true
              arr(i) = -1
              resArr(i) = qu
            }
          }
          case (true, false) => {
            if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {
              finished = true
            } else { //still continue
              if (arr(i) != -1) {
                resArr(i) = qu
                arr(i) = -1
              }
            }
          }
          case (true, true) => {
            if (arr(i) == qu) {
              good = false
            }
          }
        }
      }
      debug("After: " + qu)
    }
    var last = resArr(n-1)
    if (last == 0) last = Q
    for(i <- n-1 to 0 by -1) {
      if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }
    var lastPresent = false
    for( i <- 0 until n) {
      if (resArr(i) == Q) lastPresent = true
    }
    if (!lastPresent) good = false

    if (good) {
      outLn("YES")
      outLn(resArr.mkString(" "))
    } else {
      outLn("NO")
    }

    debug("================= RESULT ================== ")
    finish
  }

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

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

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

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

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

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

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

val sa2 = """
"""

val t1 = """
4 3
0 1 2 3
"""

}

}

import java.util.StringTokenizer
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.security.SecureRandom

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

    //COMMENT ME !
    runTest(Test.t7)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val Q = l1.int
    val arrLine = readLine
    val arr = new Array[Int](n)
    val startTime = System.currentTimeMillis()

    class Cell(val ind: Int, val value: Int) {
      var prev: Cell = null
      var next: Cell = null
    }

    class ArrList() {
      var first: Cell = null
      var last: Cell = null

      def add(cc: Cell) {
        if (first == null) {
          first = cc
        } else {
          last.next = cc
          cc.prev = last
        }
        last = cc
      }
      def remove(cc: Cell) {
        if (cc.prev != null) {
            cc.prev.next = cc.next
        }
        if (cc.next != null) {
          cc.next.prev = cc.prev
        }
        if (cc == first) {
          first = cc.next
        }
        if (cc == last) {
          last = cc.prev
        }
      }
      def mkString: String= {
        var cur = first
        var res = ""
        while (cur != null) {
//          res += cur.ind+"-"+cur.value + ","
          res += cur.value + ","
          cur = cur.next
        }
        res
      }
    }
    val aList = new ArrList()

    for(i <- 0 until n) {
      val vv = arrLine.int
      arr(i) = vv
    }

    var cur = aList.first
    while (cur != null) {
      print(cur.value + " ")
      cur = cur.next
    }
    println

//    if (arr(0) == 1912) {
//      var acc = ""
//      for(i <- 0 until n) {
//        acc += arr(i) + " "
//        if (i % 50 == 0) {
//          println(acc)
//          acc = ""
//        }
//      }
//    }

    var lastPresent = false
    var zeroInd = -1
    for( i <- 0 until n) {
      if (arr(i) == Q) lastPresent = true
      if (arr(i) == 0) zeroInd = i
    }
    if (!lastPresent && zeroInd != -1) arr(zeroInd) = Q

    //copy to linked list
    val starts = new Array[Cell](Q+1)
    val counts = new Array[Int](Q+1)
    for(i <- 0 until n) {
      val q = arr(i)
      val cc = new Cell(i, q)
      if (starts(q) == null) { starts(q) = cc }
      counts(q) += 1
      aList.add(cc)
    }

    val resArr = new Array[Int](n)
    var good = true

//    def calc(): Unit = {
//      for(qu <- Q to 1 by -1) {
//        var started = false
//        var finished = false
//        for(i <- 0 until n) {
//          (started, finished) match {
//            case (false, false) => {
//              if (arr(i) == qu) {
//                started = true
//                arr(i) = -1
//                resArr(i) = qu
//              }
//            }
//            case (true, false) => {
//              if (arr(i) != qu && arr(i) != 0 && arr(i) != -1) {
//                finished = true
//              } else { //still continue
//                if (arr(i) != -1) {
//                  resArr(i) = qu
//                  arr(i) = -1
//                }
//              }
//            }
//            case (true, true) => {
//              if (arr(i) == qu) {
//                good = false
//  //              if (arr(0) == 1912) {
//  //                println("Break on " + qu + " i=" + i)
//  //              }
//              }
//            }
//          }
//          if (!good) return
//        }
////        debug("After: " + qu)
//      }
//    }
//    calc()

    debug("After query " + "0" + ": " + aList.mkString)

    val sss = System.currentTimeMillis()
    var totalSteps = 0
    def calc2(): Unit = {
      for(qu <- Q to 1 by -1) {
        var started = false
        var finished = false
        var curCell = starts(qu)
        while(good && curCell != null && counts(qu) > 0) {
          totalSteps += 1
          (started, finished) match {
            case (false, false) => {
              if (curCell.value == qu) {
                started = true
                aList.remove(curCell)
                resArr(curCell.ind) = qu
                counts(qu) -= 1
//                debug("Removed first cell" + curCell)
              }
            }
            case (true, false) => {
              if (curCell.value != qu && curCell.value != 0) {
                finished = true
//                debug("finished")
              } else { //still continue
                aList.remove(curCell)
                resArr(curCell.ind) = qu
                if (curCell.value == qu) { counts(qu) -= 1 }
//                debug("Removed subseq cell" + curCell)
              }
            }
            case (true, true) => {
              if (curCell.value == qu) {
                debug("Fail at secondary piece: " + qu)
                good = false
              }
            }
          }
//          debug(" - After step " + qu + ": " + aList.mkString)
          curCell = curCell.next
        }
        debug("After query " + qu + ": " + aList.mkString)
      }
    }
    calc2
    val ddd = System.currentTimeMillis() - sss
    debug("calc2 dur " + ddd + "  steps=" + totalSteps)

    var last = resArr(n-1)
    if (last == 0) last = Q
    for(i <- n-1 to 0 by -1) {
      if (resArr(i) == 0) {
        resArr(i) = last
      }
      last = resArr(i)
    }
    lastPresent = false
    for( i <- 0 until n) {
      if (resArr(i) == Q) lastPresent = true
    }
    if (!lastPresent) {
      debug("Fail at top query absent")
      good = false
    }

    if (good) {
      outLn("YES")
      outLn(resArr.mkString(" "))
    } else {
      outLn("NO")
    }

    debug("================= RESULT ================== ")
    val endTime = System.currentTimeMillis() - startTime
    debug("Exec time: " + endTime)
    finish
  }

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

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

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

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

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

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

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

val sa2 = """
"""

val t7 = """
50 2
0 1 0 1 0 0 1 0 1 1 0 1 1 1 2 2 0 2 0 2 0 2 0 0 2 2 2 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 1 0 1 1 0 1 0 0
"""

val m1 = """
4 3
1 0 2 3
"""

val m2 = """
20 20
17 17 19 19 17 20 20 17 16 16 16 16 16 18 18 18 18 18 6 0
"""

def gen = {
  val runStart = System.currentTimeMillis()
  val n = 200000
  val q = 200000
  val rr = new SecureRandom
  val arr = new Array[Int](n)
  for(i <- 1 to q) {
    val start = rr.nextInt(n-1)
    val length = 1 //rr.nextInt(n-start-1)
//    val length = n-q
    val end = length + start
    for (j <- start to end) {
      arr(j) = i
    }
  }
  val res = s"$n $q" + "\n" + arr.mkString(" ")
  val runEnd = System.currentTimeMillis() - runStart
  println("Gen time " + runEnd)
  println(res)
  res
}

}

}


Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n.Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers a permutation beautiful, if it has exactly k good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.

The single line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ n).

In a single line print either any beautiful permutation or -1, if such permutation doesn’t exist. If there are multiple suitable permutations, you are allowed to print any of them.

NoteIn the first sample elements 4 and 3 are good because gcd(2, 4) = 2 > 1 and gcd(3, 3) = 3 > 1. Elements 2 and 1 are not good because gcd(1, 2) = 1 and gcd(4, 1) = 1. As there are exactly 2 good elements, the permutation is beautiful.The second sample has no beautiful permutations.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)

  if (k > n - 1)
    println("-1")
  else if (k == n - 1)
    println((1 to n).mkString(" "))
  else
    println((n :: (2 to k + 1).toList ::: (1 :: (k + 2 until n).toList)).mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)

  if (k > n - 1)
    println("-1")
  if (k == n - 1)
    println((1 to n).mkString(" "))
  else
    println((n :: (2 to k + 1).toList ::: (1 :: (k + 2 until n).toList)).mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)

  if (k > n - 1)
    println("-1")
  else
    println(((2 to k).toList ::: (1 :: (k - 1 to 0 by -1).map(i => n - i).toList)).mkString(" "))
}