Fishingprince is playing with an array $$$[a_1,a_2,\dots,a_n]$$$. He also has a magic number $$$m$$$.He can do the following two operations on it:  Select $$$1\le i\le n$$$ such that $$$a_i$$$ is divisible by $$$m$$$ (that is, there exists an integer $$$t$$$ such that $$$m \cdot t = a_i$$$). Replace $$$a_i$$$ with $$$m$$$ copies of $$$\frac{a_i}{m}$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[2,3]$$$ and $$$i=1$$$, $$$a$$$ changes into $$$[1,1,3]$$$.  Select $$$1\le i\le n-m+1$$$ such that $$$a_i=a_{i+1}=\dots=a_{i+m-1}$$$. Replace these $$$m$$$ elements with a single $$$m \cdot a_i$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[3,2,2,3]$$$ and $$$i=2$$$, $$$a$$$ changes into $$$[3,4,3]$$$. Note that the array length might change during the process. The value of $$$n$$$ above is defined as the current length of the array (might differ from the $$$n$$$ in the input).Fishingprince has another array $$$[b_1,b_2,\dots,b_k]$$$. Please determine if he can turn $$$a$$$ into $$$b$$$ using any number (possibly zero) of operations.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n\le 5\cdot 10^4$$$, $$$2\le m\le 10^9$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$). The third line of each test case contains one integer $$$k$$$ ($$$1\le k\le 5\cdot 10^4$$$). The fourth line of each test case contains $$$k$$$ integers $$$b_1,b_2,\ldots,b_k$$$ ($$$1\le b_i\le 10^9$$$). It is guaranteed that the sum of $$$n+k$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each testcase, print Yes if it is possible to turn $$$a$$$ into $$$b$$$, and No otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case of the sample, we can do the second operation with $$$i=2$$$: $$$[1,\color{red}{2,2},4,2]\to [1,\color{red}{4},4,2]$$$.In the second testcase of the sample, we can:  do the second operation with $$$i=2$$$: $$$[1,\color{red}{2,2},8,2,2]\to [1,\color{red}{4},8,2,2]$$$.  do the second operation with $$$i=4$$$: $$$[1,4,8,\color{red}{2,2}]\to [1,4,8,\color{red}{4}]$$$.  do the first operation with $$$i=3$$$: $$$[1,4,\color{red}{8},4]\to [1,4,\color{red}{4,4},4]$$$.  do the second operation with $$$i=2$$$: $$$[1,\color{red}{4,4},4,4]\to [1,\color{red}{8},4,4]$$$.  do the second operation with $$$i=3$$$: $$$[1,8,\color{red}{4,4}]\to [1,8,\color{red}{8}]$$$.  do the second operation with $$$i=2$$$: $$$[1,\color{red}{8,8}]\to [1,\color{red}{16}]$$$.

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      tokenizer = new StringTokenizer(input.readLine())
      val A =  ArrayBuffer.empty[Array[Long]]
      var hold = 0
      for (i <- 0 until n) {
        var kk = 0
        var new1 = tokenizer.nextToken().toInt
        while (new1 % m == 0){
          new1 = new1 / m
          kk+=1
        }
        if (i == 0) {
          A += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
        else if (new1 == hold) {
          A.last(1)+= pow(m,kk).toInt
        }
        else {
          A += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
      }
      val B = ArrayBuffer.empty[Array[Long]]
      tokenizer = new StringTokenizer(input.readLine())
      val k = tokenizer.nextToken().toInt
      hold = 0
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 0 until k) {
        var kk = 0
        var new1 = tokenizer.nextToken().toInt
        while (new1 % m == 0){
          new1 = new1 / m
          kk+=1
        }
        if (i == 0) {
          B += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
        else if (new1 == hold) {
          B.last(1)+= pow(m,kk).toInt
        }
        else {
          B += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
      }
      if ((A.toList).map(_.toList) == (B.toList).map(_.toList)) {
        output.println("YES")
      }
      else {
        output.println("NO")
      }
    }
  }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      tokenizer = new StringTokenizer(input.readLine())
      val A =  ArrayBuffer.empty[Array[Long]]
      var hold = 0
      for (i <- 0 until n) {
        var kk = 0
        var new1 = tokenizer.nextToken().toInt
        while (new1 % m == 0){
          new1 = new1 / m
          kk+=1
        }
        if (i == 0) {
          A += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
        else if (new1 == hold) {
          A.last(1)+= pow(m,kk).toInt
        }
        else {
          A += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
      }
      val B = ArrayBuffer.empty[Array[Long]]
      tokenizer = new StringTokenizer(input.readLine())
      val k = tokenizer.nextToken().toInt
      hold = 0
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 0 until k) {
        var kk = 0
        var new1 = tokenizer.nextToken().toInt
        while (new1 % m == 0){
          new1 = new1 / m
          kk+=1
        }
        if (i == 0) {
          B += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
        else if (new1 == hold) {
          B.last(1)+= pow(m,kk).toInt
        }
        else {
          B += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
      }
      if ((A.toList).map(_.toList) == (B.toList).map(_.toList)) {
        output.println("YES")
      }
      else {
        output.println("NO")
      }
      println((A.toList).map(_.toList), (B.toList).map(_.toList))
    }
  }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      tokenizer = new StringTokenizer(input.readLine())
      val A =  ArrayBuffer.empty[Array[Int]]
      var hold = 0
      for (i <- 0 until n) {
        var kk = 0
        var new1 = tokenizer.nextToken().toInt
        while (new1 % m == 0){
          new1 = new1 / m
          kk+=1
        }
        if (i == 0) {
          A += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
        else if (new1 == hold) {
          A.last(1)+= pow(m,kk).toInt
        }
        else {
          A += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
      }
      val B = ArrayBuffer.empty[Array[Int]]
      tokenizer = new StringTokenizer(input.readLine())
      val k = tokenizer.nextToken().toInt
      hold = 0
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 0 until k) {
        var kk = 0
        var new1 = tokenizer.nextToken().toInt
        while (new1 % m == 0){
          new1 = new1 / m
          kk+=1
        }
        if (i == 0) {
          B += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
        else if (new1 == hold) {
          B.last(1)+= pow(m,kk).toInt
        }
        else {
          B += Array(new1, pow(m,kk).toInt)
          hold = new1
        }
      }
      if ((A.toList).map(_.toList) == (B.toList).map(_.toList)) {
        output.println("YES")
      }
      else {
        output.println("NO")
      }
    }
  }
}


You are given a number $$$n$$$ and an array $$$b_1, b_2, \ldots, b_{n+2}$$$, obtained according to the following algorithm:   some array $$$a_1, a_2, \ldots, a_n$$$ was guessed;  array $$$a$$$ was written to array $$$b$$$, i.e. $$$b_i = a_i$$$ ($$$1 \le i \le n$$$);  The $$$(n+1)$$$-th element of the array $$$b$$$ is the sum of the numbers in the array $$$a$$$, i.e. $$$b_{n+1} = a_1+a_2+\ldots+a_n$$$;  The $$$(n+2)$$$-th element of the array $$$b$$$ was written some number $$$x$$$ ($$$1 \le x \le 10^9$$$), i.e. $$$b_{n+2} = x$$$; The  array $$$b$$$ was shuffled. For example, the array $$$b=[2, 3, 7, 12 ,2]$$$ it could be obtained in the following ways:   $$$a=[2, 2, 3]$$$ and $$$x=12$$$;  $$$a=[3, 2, 7]$$$ and $$$x=2$$$. For the given array $$$b$$$, find any array $$$a$$$ that could have been guessed initially.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second row of each test case contains $$$n+2$$$ integers $$$b_1, b_2, \ldots, b_{n+2}$$$ ($$$1 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output:    "-1", if the array $$$b$$$ could not be obtained from any array $$$a$$$;  $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, otherwise.  If there are several arrays of $$$a$$$, you can output any.

object P1512D {

  import java.io._

  val out: OutputPrinter = new StringOutputPrinter(1024)
  //val out: OutputPrinter = new OutputPrinter()
  //val out: OutputPrinter = new BufferedOutputPrinter()
  val input = new InputReader(new InputStreamReader(System.in))
  //val input = new InputReader(new FileReader("input.txt"))
  //  val input = new InputReader(new StringReader(
  //    """4
  //3
  //2 3 7 12 2
  //4
  //9 1 7 1 6 5
  //5
  //18 2 2 3 2 9 2
  //3
  //2 6 9 2 1
  //        """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        oneTask()
        out.endl()
      }
    }

    // S = (sum + m1 + m2), m1, m2
    // проверка: m == S - m - ai =>  ak, m, ai

    def oneTask(): Unit = {
      val size = input.nextInt
      val arr = new Array[Long](size + 2)
      var m1, m2: Long = 0L
      var m1i, m2i: Int = 0
      var S = 0L
      input.forLongs(size + 2) { (idx, v) =>
        S += v
        arr(idx) = v
        if (v > m1) {
          if (v > m2) {
            m1 = m2
            m1i = m2i
            m2 = v
            m2i = idx
          }
          else {
            m1 = v
            m1i = idx
          }
        }
      }
      var last = 0L
      var sum = 0L
      var idx = 0
      while (idx < arr.length && last == 0L) {
        val ai = arr(idx)
        val ch1 = S - m1 - ai
        if (ch1 == m1 && idx != m1i) {
          last = ai
          sum = m1
        }
        else if (idx != m2i) {
          val ch2 = S - m2 - ai
          if (ch2 == m2) {
            last = ai
            sum = m2
          }
        }
        idx += 1
      }

      if (sum != 0L) {
        arr.foreach(v => if (v == sum) {
          sum = 0L
        }
        else if (v == last) {
          last = 0L
        }
        else {
          out.print(v.toString)
          out.print(' ')
        }
        )
      }
      else {
        out.print("-1")
      }

    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class DirectOutputPrinter extends OutputPrinter {

    override def print(c: Char): Unit = System.out.print(c)

    override def print(i: Int): Unit = System.out.print(i)

    override def print(s: String): Unit = System.out.print(s)

    override def endl(): Unit = System.out.println()

    override def flush(): Unit = System.out.flush()
  }

  class StringOutputPrinter(capacity: Int) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = println(buffer.result())
  }

  class BufferedOutputPrinter extends OutputPrinter {
    private val buffer = new PrintWriter(System.out)

    override def print(c: Char): Unit = buffer.print(c)

    override def print(i: Int): Unit = buffer.print(i)

    override def print(s: String): Unit = buffer.print(s)

    override def endl(): Unit = buffer.println()

    override def flush(): Unit = buffer.flush()
  }

}

object P1512D {

  import java.io._

  val out: OutputPrinter = new StringOutputPrinter(1024)
  //val out: OutputPrinter = new OutputPrinter()
  //val out: OutputPrinter = new BufferedOutputPrinter()
  val input = new InputReader(new InputStreamReader(System.in))
  //val input = new InputReader(new FileReader("input.txt"))
//  val input = new InputReader(new StringReader(
//    """4
//3
//2 3 7 12 2
//4
//9 1 7 1 6 5
//5
//18 2 2 3 2 9 2
//3
//2 6 9 2 1
//        """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        oneTask()
        out.endl()
      }
    }

    // S = (sum + m1 + m2), m1, m2
    // проверка: m == S - m - ai =>  ak, m, ai

    def oneTask(): Unit = {
      val size = input.nextInt
      val arr = new Array[Int](size + 2)
      var m1, m1i, m2, m2i: Int = 0
      var S = 0
      input.forInts(size + 2) { (idx, v) =>
        S += v
        arr(idx) = v
        if (v > m1) {
          if (v > m2) {
            m1 = m2
            m1i = m2i
            m2 = v
            m2i = idx
          }
          else {
            m1 = v
            m1i = idx
          }
        }
      }
      var last = 0
      var sum = 0
      var idx = 0
      while (idx < arr.length && last == 0) {
        val ai = arr(idx)
        val ch1 = S - m1 - ai
        if (ch1 == m1 && idx != m1i) {
          last = ai
          sum = m1
        }
        else if (idx != m2i) {
          val ch2 = S - m2 - ai
          if (ch2 == m2) {
            last = ai
            sum = m2
          }
        }
        idx += 1
      }

      if (sum != 0) {
        arr.foreach(v => if (v == sum) {
          sum = 0
        }
        else if (v == last) {
          last = 0
        }
        else {
          out.print(v)
          out.print(' ')
        }
        )
      }
      else {
        out.print("-1")
      }

    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class DirectOutputPrinter extends OutputPrinter {

    override def print(c: Char): Unit = System.out.print(c)

    override def print(i: Int): Unit = System.out.print(i)

    override def print(s: String): Unit = System.out.print(s)

    override def endl(): Unit = System.out.println()

    override def flush(): Unit = System.out.flush()
  }

  class StringOutputPrinter(capacity: Int) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = println(buffer.result())
  }

  class BufferedOutputPrinter extends OutputPrinter {
    private val buffer = new PrintWriter(System.out)

    override def print(c: Char): Unit = buffer.print(c)

    override def print(i: Int): Unit = buffer.print(i)

    override def print(s: String): Unit = buffer.print(s)

    override def endl(): Unit = buffer.println()

    override def flush(): Unit = buffer.flush()
  }

}

object P1512D {

  import java.io._

  val out: OutputPrinter = new StringOutputPrinter(1024)
  //val out: OutputPrinter = new OutputPrinter()
  //val out: OutputPrinter = new BufferedOutputPrinter()
  val input = new InputReader(new InputStreamReader(System.in))
  //val input = new InputReader(new FileReader("input.txt"))
  //  val input = new InputReader(new StringReader(
  //    """4
  //3
  //2 3 7 12 2
  //4
  //9 1 7 1 6 5
  //5
  //18 2 2 3 2 9 2
  //3
  //2 6 9 2 1
  //      """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        oneTask()
        out.endl()
      }
    }

    // S = (sum + m1 + m2), m1, m2
    // проверка: m == S - m - ai =>  ak, m, ai

    def oneTask(): Unit = {
      val size = input.nextInt
      val arr = new Array[Int](size + 2)
      var m1, m2: Int = 0
      var S = 0
      input.forInts(size + 2) { (idx, v) =>
        S += v
        arr(idx) = v
        if (v > m1) {
          if (v > m2) {
            m1 = m2
            m2 = v
          }
          else {
            m1 = v
          }
        }
      }
      var last = 0
      var sum = 0
      var idx = 0
      while (idx < arr.length && last == 0) {
        val ai = arr(idx)
        val ch1 = S - m1 - ai
        if (ch1 == m1) {
          last = ai
          sum = m1
        }
        else {
          val ch2 = S - m2 - ai
          if (ch2 == m2) {
            last = ai
            sum = m2
          }
        }
        idx += 1
      }

      if (sum != 0) {
        arr.foreach(v => if (v == sum) {
          sum = 0
        }
        else if (v == last) {
          last = 0
        }
        else {
          out.print(v)
          out.print(' ')
        }
        )
      }
      else {
        out.print("-1")
      }

    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class DirectOutputPrinter extends OutputPrinter {

    override def print(c: Char): Unit = System.out.print(c)

    override def print(i: Int): Unit = System.out.print(i)

    override def print(s: String): Unit = System.out.print(s)

    override def endl(): Unit = System.out.println()

    override def flush(): Unit = System.out.flush()
  }

  class StringOutputPrinter(capacity: Int) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = println(buffer.result())
  }

  class BufferedOutputPrinter extends OutputPrinter {
    private val buffer = new PrintWriter(System.out)

    override def print(c: Char): Unit = buffer.print(c)

    override def print(i: Int): Unit = buffer.print(i)

    override def print(s: String): Unit = buffer.print(s)

    override def endl(): Unit = buffer.println()

    override def flush(): Unit = buffer.flush()
  }

}


There is a river of width $$$n$$$. The left bank of the river is cell $$$0$$$ and the right bank is cell $$$n + 1$$$ (more formally, the river can be represented as a sequence of $$$n + 2$$$ cells numbered from $$$0$$$ to $$$n + 1$$$). There are also $$$m$$$ wooden platforms on a river, the $$$i$$$-th platform has length $$$c_i$$$ (so the $$$i$$$-th platform takes $$$c_i$$$ consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed $$$n$$$.You are standing at $$$0$$$ and want to reach $$$n+1$$$ somehow. If you are standing at the position $$$x$$$, you can jump to any position in the range $$$[x + 1; x + d]$$$. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if $$$d=1$$$, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells $$$0$$$ and $$$n+1$$$ belong to wooden platforms.You want to know if it is possible to reach $$$n+1$$$ from $$$0$$$ if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).For example, if $$$n=7$$$, $$$m=3$$$, $$$d=2$$$ and $$$c = [1, 2, 1]$$$, then one of the ways to reach $$$8$$$ from $$$0$$$ is follow:    The first example: $$$n=7$$$.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$d$$$ ($$$1 \le n, m, d \le 1000, m \le n$$$) — the width of the river, the number of platforms and the maximum distance of your jump, correspondingly. The second line of the input contains $$$m$$$ integers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le n, \sum\limits_{i=1}^{m} c_i \le n$$$), where $$$c_i$$$ is the length of the $$$i$$$-th platform.

If it is impossible to reach $$$n+1$$$ from $$$0$$$, print NO in the first line. Otherwise, print YES in the first line and the array $$$a$$$ of length $$$n$$$ in the second line — the sequence of river cells (excluding cell $$$0$$$ and cell $$$n + 1$$$). If the cell $$$i$$$ does not belong to any platform, $$$a_i$$$ should be $$$0$$$. Otherwise, it should be equal to the index of the platform ($$$1$$$-indexed, platforms are numbered from $$$1$$$ to $$$m$$$ in order of input) to which the cell $$$i$$$ belongs. Note that all $$$a_i$$$ equal to $$$1$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_1$$$, all $$$a_i$$$ equal to $$$2$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_2$$$, ..., all $$$a_i$$$ equal to $$$m$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_m$$$. The leftmost position of $$$2$$$ in $$$a$$$ should be greater than the rightmost position of $$$1$$$, the leftmost position of $$$3$$$ in $$$a$$$ should be greater than the rightmost position of $$$2$$$, ..., the leftmost position of $$$m$$$ in $$$a$$$ should be greater than the rightmost position of $$$m-1$$$. See example outputs for better understanding.

NoteConsider the first example: the answer is $$$[0, 1, 0, 2, 2, 0, 3]$$$. The sequence of jumps you perform is $$$0 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 7 \rightarrow 8$$$.Consider the second example: it does not matter how to place the platform because you always can jump from $$$0$$$ to $$$11$$$.Consider the third example: the answer is $$$[0, 0, 0, 0, 1, 1, 0, 0, 0, 0]$$$. The sequence of jumps you perform is $$$0 \rightarrow 5 \rightarrow 6 \rightarrow 11$$$.

object Main {
  def main(args: Array[String]): Unit = {
    val Array(n, m, d) = readLine.split(" ").map(_.toInt)
    val c = readLine.split(" ").zipWithIndex.map{ case (x, i) => (i+1, x.toInt) }.toList
    val sc = c.foldLeft(0){ case (s, (_, v)) => s + v }
    f1(n, d, c, sc) match {
      case None => println("NO")
      case Some(l) => {
        println("YES")
        println(l.mkString(" "))
      }
    }
  }

  def f1(n: Int, d: Int, c: List[(Int, Int)], sc: Int): Option[List[Int]] = {
    if (d - 1 + sc >= n) {
      Some(c.map{ case (i, ni) => List.fill(ni)(i) }.foldLeft(List.fill(n - sc)(0)){ case (li, lj) => li ++ lj })
    } else {
      c match {
        case Nil => None
        case (i, ni) :: rc => f1(n - (ni + d - 1), d, rc, (sc - ni)) match {
          case Some(l) => Some(List.fill(d - 1)(0) ++ List.fill(ni)(i) ++ l)
          case None => None
        }
      }
    }
  }

}

import java.util.Scanner

import scala.language.postfixOps

object TaskC extends App {
  val sc = new Scanner(System.in)
  val (n, m, d) = (sc.nextInt, sc.nextInt, sc.nextInt)

  var w = 0
  val platforms = (1 to m).map(_ => sc.nextInt).zipWithIndex.reverse.map { case (c, ind) =>
    val platform = (n - w - c + 1, c, ind + 1)
    w += c
    platform
  }.reverse.toArray

  var last = 0

  0 until m foreach { i =>
    if (platforms(i)._1 - last > d) {
      platforms(i) = (last + d, platforms(i)._2, platforms(i)._3)
    }
    last = platforms(i)._1 + platforms(i)._2 - 1
  }

  val out = if (n - last + 1 <= d) {
    val water = Array.fill(n)(0)
    platforms.foreach { case (i, c, l) =>
      i until (i + c) foreach (j => water(j - 1) = l)
    }
    s"YES\n${water.mkString(" ")}"
  } else {
    "NO"
  }

  println(out)
}


The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem.  One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters above the floor of the house, its mass is mi. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?

The first line contains two integers, n and x (1 ≤ n, x ≤ 2000) — the number of sweets Evan has and the initial height of Om Nom's jump.  Each of the following n lines contains three integers ti, hi, mi (0 ≤ ti ≤ 1; 1 ≤ hi, mi ≤ 2000) — the type, height and the mass of the i-th candy. If number ti equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.

Print a single integer — the maximum number of candies Om Nom can eat.

NoteOne of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario:  Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3 + 4 = 7.  Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7 + 5 = 12.  At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12 + 3 = 15.  Om Nom eats candy 2, the height of his jump is 15 + 1 = 16. He cannot reach candy 4.

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

  val (sweetl, candyl) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)])) {
    case ((s, c), _) =>

      val Array(t, h, m) = in.next().split(' ').map(_.toInt)
      t match {
        case 0 => (s, (h, m) :: c)
        case _ => ((h, m) :: s, c)
      }
  }

  def calc(isCandyl: Boolean): Int = {
    val sweet = sweetl.toArray
    val candy = candyl.toArray
    var work = true
    var count = 0
    var possibleh = x
    var isCandy = isCandyl

    while (work) {
      if (isCandy) {
        val index = candy.indices.foldLeft(-1) {
          case (-1, i) if candy(i)._1 <= possibleh && candy(i)._2 > 0 => i
          case (j, i)  if candy(i)._1 <= possibleh && j >= 0 && candy(i)._2 > candy(j)._2 => i
          case (j, i) => j
        }
        work = index != -1

        if (work) {
          possibleh += candy(index)._2
          candy(index) = (0, 0)
        }

      } else {
        val index = sweet.indices.foldLeft(-1) {
          case (-1, i) if sweet(i)._1 <= possibleh && sweet(i)._2 > 0 => i
          case (j, i)  if sweet(i)._1 <= possibleh && j >= 0 && sweet(i)._2 > sweet(j)._2 => i
          case (j, i) => j
        }
        work = index != -1
        if (work) {
          possibleh += sweet(index)._2
          sweet(index) = (0, 0)
        }
      }
      if (work) count += 1
//      println(candy.mkString(" "))
//      println(sweet.mkString(" "))
      isCandy = !isCandy
    }
    count
  }
//  println(candyl)
//  println(sweetl)
//  println(calc(true))
//  println(calc(false))
  println(Math.max(calc(true), calc(false)))
}

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

object A extends App {

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

  val Array(n, x) = readInts(2)
  val _as = mutable.ArrayBuffer.empty[(Int, Int)]
  val _bs = mutable.ArrayBuffer.empty[(Int, Int)]

  for (i <- 0 until n) {
    val Array(t, h, m) = readInts(3)
    if (t == 0) {
      _as += ((h, m))
    } else {
      _bs += ((h, m))
    }
  }

  val as = _as.sortBy(_._2)
  val bs = _bs.sortBy(_._2)

  def calc(prev0: Boolean): Int = {
    val aUsed = Array.fill(n)(false)
    val bUsed = Array.fill(n)(false)
    var ai = 0
    var bi = 0
    var h = x
    var count = 0
    var prev = prev0
    var choice = 0
    while (choice >= 0 && ((prev && ai < as.size) || (!prev && bi < bs.size))) {
      choice = -1
      if (prev) {
        for (i <- as.indices) if (!aUsed(i) && as(i)._1 <= h) choice = i
        if (choice >= 0) {
          h += as(choice)._2
          aUsed(choice) = true
          ai += 1
          count += 1
        }
      } else {
        for (i <- bs.indices) if (!bUsed(i) && bs(i)._1 <= h) choice = i
        if (choice >= 0) {
          h += bs(choice)._2
          bUsed(choice) = true
          bi += 1
          count += 1
        }
      }
      prev = !prev
    }
    count
  }

  println(calc(true) max calc(false))
}

import java.util.Scanner

/**
 * Created by hama_du on 2014/06/19.
 */
object ProblemA extends App {
  def solve(jump: Int, caramel: Array[(Int,Int,Boolean)], fruit:Array[(Int,Int,Boolean)], want: Int): Int = {
    if (want == 0) {
      val idx = selectAvailable(jump, caramel)
      if (idx == -1) {
        return 0
      }
      val gain = caramel(idx)._2
      caramel(idx) = (0, 0, true)
      solve(jump + gain, caramel, fruit, 1-want) + 1
    } else {
      val idx = selectAvailable(jump, fruit)
      if (idx == -1) {
        return 0
      }
      val gain = fruit(idx)._2
      fruit(idx) = (0, 0, true)
      solve(jump + gain, caramel, fruit, 1-want) + 1
    }
  }

  def selectAvailable(jump: Int, candies: Array[(Int,Int,Boolean)]): Int = {
    val available = candies.zipWithIndex.filter(ci => ci._1._1 <= jump && !ci._1._3 )
    if (available.size == 0) {
      -1
    } else {
      available.maxBy(ci => ci._1._2)._2
    }
  }

  val in = new Scanner(System.in)
  val n,x = in.nextInt()
  val candies = (0 until n).map(_ => {
    (in.nextInt(), in.nextInt(), in.nextInt())
  })
  val answer = (0 to 1).map(start => {
    // (height, mass, eaten)
    val caramel = candies.filter(c => c._1 == 0).map(c => (c._2, c._3, false)).toArray
    val fruit = candies.filter(c => c._1 == 1).map(c => (c._2, c._3, false)).toArray
    solve(x, caramel, fruit, start)
  }).max
  println(answer)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, x) = in.next().split(' ').map(_.toInt)
  val (sweetl, candyl) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)])) {
    case ((s, c), _) =>

      val Array(t, h, m) = in.next().split(' ').map(_.toInt)
      t match {
        case 0 => (s, (h, m) :: c)
        case _ => ((h, m) :: s, c)
      }
  }
  val sweet = sweetl.toArray
  val candy = candyl.toArray

  var isCandy = !sweet.exists{ case(h, m) => h <= x && m > 0} ||
    (candy.exists{ case(h, m) => h <= x && m > 0 } && candy.filter{case(h, m) => h <= x && m > 0}.maxBy(_._2)._2
      > sweet.filter{case(h, m) => h <= x && m > 0}.maxBy(_._2)._2)

  var work = true
  var count = 0
  var possibleh = x

  while (work) {
    if (isCandy) {
      val index = candy.indices.foldLeft(-1) {
        case (-1, i) if candy(i)._1 <= possibleh && candy(i)._2 > 0 => i
        case (j, i)  if candy(i)._1 <= possibleh && j > 0 && candy(i)._2 > candy(j)._2 => i
        case (j, i) => j
      }
      work = index != -1

      if (work) {
        possibleh += candy(index)._2
        candy(index) = (0, 0)
      }

    } else {
      val index = sweet.indices.foldLeft(-1) {
        case (-1, i) if sweet(i)._1 <= possibleh && sweet(i)._2 > 0 => i
        case (j, i)  if sweet(i)._1 <= possibleh && j > 0 && sweet(i)._2 > sweet(j)._2 => i
        case (j, i) => j
      }
      work = index != -1
      if (work) {
        possibleh += sweet(index)._2
        sweet(index) = (0, 0)
      }
    }
    if (work) count += 1
    isCandy = !isCandy
  }
  println(count)
}

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

  val (sweetl, candyl) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)])) {
    case ((s, c), _) =>

      val Array(t, h, m) = in.next().split(' ').map(_.toInt)
      t match {
        case 0 => (s, (h, m) :: c)
        case _ => ((h, m) :: s, c)
      }
  }

  def calc(isCandyl: Boolean): Int = {
    val sweet = sweetl.toArray
    val candy = candyl.toArray
    var work = true
    var count = 0
    var possibleh = x
    var isCandy = isCandyl

    while (work) {
      if (isCandy) {
        val index = candy.indices.foldLeft(-1) {
          case (-1, i) if candy(i)._1 <= possibleh && candy(i)._2 > 0 => i
          case (j, i)  if candy(i)._1 <= possibleh && j > 0 && candy(i)._2 > candy(j)._2 => i
          case (j, i) => j
        }
        work = index != -1

        if (work) {
          possibleh += candy(index)._2
          candy(index) = (0, 0)
        }

      } else {
        val index = sweet.indices.foldLeft(-1) {
          case (-1, i) if sweet(i)._1 <= possibleh && sweet(i)._2 > 0 => i
          case (j, i)  if sweet(i)._1 <= possibleh && j > 0 && sweet(i)._2 > sweet(j)._2 => i
          case (j, i) => j
        }
        work = index != -1
        if (work) {
          possibleh += sweet(index)._2
          sweet(index) = (0, 0)
        }
      }
      if (work) count += 1
      isCandy = !isCandy
    }
    count
  }

  println(Math.max(calc(true), calc(false)))
}


There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.In other words, let's say that bi, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≤ c ≤ k, 1 ≤ i, j ≤ n the following condition must be satisfied |bi, c - bj, c| ≤ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then bi, c is considered to be zero.

The first line of the input contains positive integers n and k (1 ≤ n, k ≤ 100), separated by a space — the number of piles and the number of colors respectively. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) denoting number of pebbles in each of the piles.

If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) . Otherwise in the first line output "YES" (without quotes). Then n lines should follow, the i-th of them should contain ai space-separated integers. j-th (1 ≤ j ≤ ai) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  if (data.max - data.min > k)
    println("NO")
  else {
    println("YES")
    println(data.map(i => (1 to i).map(_ % k + 1).mkString(" ")).mkString("\n"))
  }
}


Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.Let's assume that we are given a connected weighted undirected graph G = (V, E) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G1 = (V, E1) that is a tree with the set of edges E1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G1 are the same. You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.

The first line contains two numbers, n and m (1 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of vertices and edges of the graph, respectively. Next m lines contain three integers each, representing an edge — ui, vi, wi — the numbers of vertices connected by an edge and the weight of the edge (ui ≠ vi, 1 ≤ wi ≤ 109). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices. The last line of the input contains integer u (1 ≤ u ≤ n) — the number of the start vertex.

In the first line print the minimum total weight of the edges of the tree. In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order. If there are multiple answers, print any of them.

NoteIn the first sample there are two possible shortest path trees:  with edges 1 – 3 and 2 – 3 (the total weight is 3);  with edges 1 – 2 and 2 – 3 (the total weight is 2); And, for example, a tree with edges 1 – 2 and 1 – 3 won't be a shortest path tree for vertex 3, because the distance from vertex 3 to vertex 2 in this tree equals 3, and in the original graph it is 1.

import scala.collection._
import scala.math.Ordering

object Solution extends App {
  import ContestLib._
  val Array(n, m) = readIntArray()
  var weight = Array.fill(m){0}
  val data = Range(0, m).foldLeft(Array.fill(n)(mutable.ListBuffer.empty[(Int, Int, Int)])) {
    case(acc, el) =>
      val Array(u, v, w) = readIntArray()
      weight(el) = w
      acc(u - 1) += ((v - 1, w, el))
      acc(v - 1) += ((u - 1, w, el))
      acc
  }

  val visited = Array.fill(n)(false)
  val start = readInt() - 1
  var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Long, Int, Int)](SecondOrdering)) {
    case (acc, (u, w, edge)) =>
      acc.enqueue((u, w, edge, weight(edge)))
      acc
  }
  visited(start) = true
  val edges = mutable.ListBuffer.empty[Int]
  val ex = Array.fill(n)(-1l)
  ex(start) = 0

  while (expand.nonEmpty) {
    val (u, w, edge, _) = expand.dequeue()
    if (!visited(u)) {
      visited(u) = true
      edges += edge
      data(u).foreach { case(u1, w1, edge1) =>
        if (!visited(u1))
        if (ex(u1) == -1 || ex(u1) >= w + w1){
          ex(u1) = w + w1
          expand.enqueue((u1, w + w1, edge1, weight(edge1)))
        }
      }
    }
  }

  val sum = edges.foldLeft(0l) {
    case(acc, el) => acc + weight(el)
  }

  println(sum)
  println(edges.map(_ + 1).mkString(" "))

}

object ContestLib {
  import scala.io.StdIn._
  def readIntArray() = readLine().split(' ').map(_.toInt)
  def readInt() = scala.io.StdIn.readInt()

  def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],
                                 ord2: Ordering[T2],
                                 ord3: Ordering[T3],
                                 ord4: Ordering[T4]
                                  ): Ordering[(T1, T2, T3, T4)]  =
    new Ordering[(T1, T2, T3, T4)]{
      def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {
        var res = -ord2.compare(x._2, y._2)
        if (res == 0)
          res = -ord4.compare(x._4, y._4)
        res
      }

  }
}

object E3{
  def main(args: Array[String]){
   import scala.collection.mutable.PriorityQueue
    import scala.collection.mutable.ArrayBuffer
    import util.control.Breaks._
//    var in=io.Source.stdin.getLines()
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next

    val n=nextInt

    val m=nextInt
    val U=new Array[Int](m)
    val V=new Array[Int](m)
    val W=new Array[Long](m)
    for(i <- 0 until m)
    {
      U(i)=nextInt
      V(i)=nextInt
      W(i)=nextLong
    }

    var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())
    for(i<-0 until U.length){
      edgeof(U(i))+=((V(i),W(i)));
      edgeof(V(i))+=((U(i),W(i)));
    }
    val d=Array.fill(n+1)(Long.MaxValue)
    val u0=nextInt
    val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))

    d(u0)=0
    q.enqueue((d(u0),u0))
    val mark=Array.fill(n+1)(false)
    while(!q.isEmpty){
      breakable{
        val u=q.dequeue._2
        if(mark(u)){
          break
        }
        mark(u)=true
        for(p<-edgeof(u)){
          if(d(p._1)>d(u)+p._2){
            d(p._1)=d(u)+p._2
            q.enqueue((d(p._1),p._1))
          }
        }
      }
    }

    var sum=0L
    val selectedEdge=Array.fill(n+1)(-1)
    for(i<-0 until U.length){
      if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){
        selectedEdge(U(i))=i

      }
      if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){
        selectedEdge(V(i))=i

      }

    }

    for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}
    out.println(sum)
    for(i<-1 to n if i != u0){ out.print((selectedEdge(i)+1)+" ")}
    out.println()
    out.flush
    out.close

  }
}

object E3{
  def main(args: Array[String]){
   import scala.collection.mutable.PriorityQueue
    import scala.collection.mutable.ArrayBuffer
    import util.control.Breaks._
//    var in=io.Source.stdin.getLines()
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next

    val n=nextInt

    val m=nextInt
    val U=new Array[Int](m)
    val V=new Array[Int](m)
    val W=new Array[Long](m)
    for(i <- 0 until m)
    {
      U(i)=nextInt
      V(i)=nextInt
      W(i)=nextLong
    }

    var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())
    for(i<-0 until U.length){
      edgeof(U(i))+=((V(i),W(i)));
      edgeof(V(i))+=((U(i),W(i)));
    }
    val d=Array.fill(n+1)(Long.MaxValue)
    val u0=nextInt
    val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))

    d(u0)=0
    q.enqueue((d(u0),u0))
    val mark=Array.fill(n+1)(false)
    while(!q.isEmpty){
      breakable{
        val u=q.dequeue._2
        if(mark(u)){
          break
        }
        mark(u)=true
        for(p<-edgeof(u)){
          if(d(p._1)>d(u)+p._2){
            d(p._1)=d(u)+p._2
            q.enqueue((d(p._1),p._1))
          }
        }
      }
    }

    var sum=0L
    val selectedEdge=Array.fill(n+1)(-1)
    for(i<-0 until U.length){
      if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){
        selectedEdge(U(i))=i

      }
      if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){
        selectedEdge(V(i))=i

      }

    }

    for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}
    out.println(sum)
    for(i<-1 to n if i != u0){ out.print((selectedEdge(i)+1)+" ") }
    out.println()
    out.flush
    out.close

  }
}

object E3{
  def main(args: Array[String]){
   import scala.collection.mutable.PriorityQueue
    import scala.collection.mutable.ArrayBuffer
    import util.control.Breaks._
//    var in=io.Source.stdin.getLines()
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next

    val n=nextInt

    val m=nextInt
    val U=new Array[Int](m)
    val V=new Array[Int](m)
    val W=new Array[Long](m)
    for(i <- 0 until m)
    {
      U(i)=nextInt
      V(i)=nextInt
      W(i)=nextLong
    }

    var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())
    for(i<-0 until U.length){
      edgeof(U(i))+=((V(i),W(i)));
      edgeof(V(i))+=((U(i),W(i)));
    }
    val d=Array.fill(n+1)(Long.MaxValue)
    val u0=nextInt
    val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))

    d(u0)=0
    q.enqueue((d(u0),u0))
    val mark=Array.fill(n+1)(false)
    while(!q.isEmpty){
      breakable{
        val u=q.dequeue._2
        if(mark(u)){
          break
        }
        mark(u)=true
        for(p<-edgeof(u)){
          if(d(p._1)>d(u)+p._2){
            d(p._1)=d(u)+p._2
            q.enqueue((d(p._1),p._1))
          }
        }
      }
    }

    var sum=0L
    val selectedEdge=Array.fill(n+1)(-1)
    for(i<-0 until U.length){
      if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){
        selectedEdge(U(i))=i

      }
      if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){
        selectedEdge(V(i))=i

      }

    }

    for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}
    out.println(sum)
    for(i<-1 to n if i != u0){ out.print((selectedEdge(i)+1));out.print(" ") }
    out.println()
    out.flush
    out.close

  }
}

import scala.collection._
import scala.math.Ordering

object Solution extends App {
  import ContestLib._
  val Array(n, m) = readIntArray()
  var weight = Array.fill(m){0}
  val data = Range(0, m).foldLeft(Array.fill(n)(mutable.ListBuffer.empty[(Int, Int, Int)])) {
    case(acc, el) =>
      val Array(u, v, w) = readIntArray()
      weight(el) = w
      acc(u - 1) += ((v - 1, w, el))
      acc(v - 1) += ((u - 1, w, el))
      acc
  }

  val visited = Array.fill(n)(false)
  val start = readInt() - 1
  var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Long, Int, Int)](SecondOrdering)) {
    case (acc, (u, w, edge)) =>
      acc.enqueue((u, w, edge, weight(edge)))
      acc
  }
  visited(start) = true
  val edges = mutable.ListBuffer.empty[Int]
  val ex = Array.fill(n)(-1l)
  ex(start) = 0

  while (expand.nonEmpty) {
    val (u, w, edge, _) = expand.dequeue()
    if (!visited(u)) {
      visited(u) = true
      edges += edge
      data(u).foreach { case(u1, w1, edge1) =>
        if (!visited(u1))
        if (ex(u1) == -1 || ex(u1) >= w + w1){
          ex(u1) = w + w1
          expand.enqueue((u1, w + w1, edge1, weight(edge1)))
        }
      }
    }
  }

  val sum = edges.foldLeft(0) {
    case(acc, el) => acc + weight(el)
  }

  println(sum)
  println(edges.mkString(" "))

}

object ContestLib {
  import scala.io.StdIn._
  def readIntArray() = readLine().split(' ').map(_.toInt)
  def readInt() = scala.io.StdIn.readInt()

  def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],
                                 ord2: Ordering[T2],
                                 ord3: Ordering[T3],
                                 ord4: Ordering[T4]
                                  ): Ordering[(T1, T2, T3, T4)]  =
    new Ordering[(T1, T2, T3, T4)]{
      def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {
        var res = -ord2.compare(x._2, y._2)
        if (res == 0)
          res = -ord4.compare(x._4, y._4)
        res
      }

  }
}

import scala.collection._
import scala.math.Ordering

object Solution extends App {
  import ContestLib._
  val Array(n, m) = readIntArray()
  var weight = Array.fill(m){0}
  val data = Range(0, m).foldLeft(Array.fill(n)(mutable.ListBuffer.empty[(Int, Int, Int)])) {
    case(acc, el) =>
      val Array(u, v, w) = readIntArray()
      weight(el) = w
      acc(u - 1) += ((v - 1, w, el))
      acc(v - 1) += ((u - 1, w, el))
      acc
  }

  val visited = Array.fill(n)(false)
  val start = readInt() - 1
  var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Long, Int, Int)](SecondOrdering)) {
    case (acc, (u, w, edge)) =>
      acc.enqueue((u, w, edge, weight(edge)))
      acc
  }
  visited(start) = true
  val edges = mutable.ListBuffer.empty[Int]
  val ex = Array.fill(n)(-1l)
  ex(start) = 0

  while (expand.nonEmpty) {
    val (u, w, edge, _) = expand.dequeue()
    if (!visited(u)) {
      visited(u) = true
      edges += (edge + 1)
      data(u).foreach { case(u1, w1, edge1) =>
        if (!visited(u1))
        if (ex(u1) == -1 || ex(u1) >= w + w1){
          ex(u1) = w + w1
          expand.enqueue((u1, w + w1, edge1, weight(edge1)))
        }
      }
    }
  }

  val sum = edges.foldLeft(0) {
    case(acc, el) => acc + weight(el)
  }

  println(sum)
  println(edges.mkString(" "))

}

object ContestLib {
  import scala.io.StdIn._
  def readIntArray() = readLine().split(' ').map(_.toInt)
  def readInt() = scala.io.StdIn.readInt()

  def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],
                                 ord2: Ordering[T2],
                                 ord3: Ordering[T3],
                                 ord4: Ordering[T4]
                                  ): Ordering[(T1, T2, T3, T4)]  =
    new Ordering[(T1, T2, T3, T4)]{
      def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {
        var res = -ord2.compare(x._2, y._2)
        if (res == 0)
          res = -ord4.compare(x._4, y._4)
        res
      }

  }
}

import scala.collection._
import scala.math.Ordering

object Solution extends App {
  import ContestLib._
  val Array(n, m) = readIntArray()
  var weight = Map.empty[Int, Int]
  val data = Range(1, m + 1).foldLeft(Array.fill(n)(mutable.Set.empty[(Int, Int, Int)])) {
    case(acc, el) =>
      val Array(u, v, w) = readIntArray()
      weight += (el -> w)
      acc(u - 1) += ((v - 1, w, el))
      acc(v - 1) += ((u - 1, w, el))
      acc
  }
  val visited = Array.fill(n)(false)
  val start = readInt()
  var expand = data(0).foldLeft(mutable.PriorityQueue.empty[(Int, Int, Int)](SecondOrdering)) {
    case (acc, (u, w, edge)) =>
      acc.enqueue((u, w, edge))
      acc
  }
  visited(0) = true
  var edges = Set.empty[Int]

  while (expand.nonEmpty) {
    val (u, w, edge) = expand.dequeue()
    if (!visited(u)) {
      visited(u) = true
      edges += edge
      data(u).foreach { case(u1, w1, edge1) =>
        if (!visited(u1)) expand.enqueue((u1, w + w1, edge1))
      }
    }
  }

  val sum = edges.foldLeft(0) {
    case(acc, el) => acc + weight(el)
  }

  println(sum)
  println(edges.mkString(" "))

}

object ContestLib {
  import scala.io.StdIn._
  def readIntArray() = readLine().split(' ').map(_.toInt)
  def readInt() = scala.io.StdIn.readInt()

  def SecondOrdering[T1, T2, T3](implicit ord1: Ordering[T1],
                                 ord2: Ordering[T2],
                                 ord3: Ordering[T3]
                                  ): Ordering[(T1, T2, T3)]  =
    new Ordering[(T1, T2, T3)]{
      def compare(x: (T1, T2, T3), y: (T1, T2, T3)): Int =
        -ord2.compare(x._2, y._2)

  }
}

import scala.collection._
import scala.math.Ordering

object Solution extends App {
  import ContestLib._
  val Array(n, m) = readIntArray()
  var weight = Array.fill(m){0}
  val data = Range(0, m).foldLeft(Array.fill(n)(mutable.ListBuffer.empty[(Int, Int, Int)])) {
    case(acc, el) =>
      val Array(u, v, w) = readIntArray()
      weight(el) = w
      acc(u - 1) += ((v - 1, w, el))
      acc(v - 1) += ((u - 1, w, el))
      acc
  }

  val visited = Array.fill(n)(false)
  val start = readInt() - 1
  var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Long, Int, Int)](SecondOrdering)) {
    case (acc, (u, w, edge)) =>
      acc.enqueue((u, w, edge, weight(edge)))
      acc
  }
  visited(start) = true
  val edges = mutable.ListBuffer.empty[Int]
  val ex = Array.fill(n)(-1l)
  ex(start) = 0

  while (expand.nonEmpty) {
    val (u, w, edge, _) = expand.dequeue()
    if (!visited(u)) {
      visited(u) = true
      edges += edge
      data(u).foreach { case(u1, w1, edge1) =>
        if (!visited(u1))
        if (ex(u1) == -1 || ex(u1) >= w + w1){
          ex(u1) = w + w1
          expand.enqueue((u1, w + w1, edge1, weight(edge1)))
        }
      }
    }
  }

  val sum = edges.foldLeft(0) {
    case(acc, el) => acc + weight(el)
  }

  println(sum)
  println(edges.map(_ + 1).mkString(" "))

}

object ContestLib {
  import scala.io.StdIn._
  def readIntArray() = readLine().split(' ').map(_.toInt)
  def readInt() = scala.io.StdIn.readInt()

  def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],
                                 ord2: Ordering[T2],
                                 ord3: Ordering[T3],
                                 ord4: Ordering[T4]
                                  ): Ordering[(T1, T2, T3, T4)]  =
    new Ordering[(T1, T2, T3, T4)]{
      def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {
        var res = -ord2.compare(x._2, y._2)
        if (res == 0)
          res = -ord4.compare(x._4, y._4)
        res
      }

  }
}

import scala.collection._
import scala.math.Ordering

object Solution extends App {
  import ContestLib._
  val Array(n, m) = readIntArray()
  var weight = Map.empty[Int, Int]
  val data = Range(1, m + 1).foldLeft(Array.fill(n)(mutable.Set.empty[(Int, Int, Int)])) {
    case(acc, el) =>
      val Array(u, v, w) = readIntArray()
      weight += (el -> w)
      acc(u - 1) += ((v - 1, w, el))
      acc(v - 1) += ((u - 1, w, el))
      acc
  }

  val visited = Array.fill(n)(false)
  val start = readInt() - 1
  var expand = data(start).foldLeft(mutable.PriorityQueue.empty[(Int, Int, Int, Int)](SecondOrdering)) {
    case (acc, (u, w, edge)) =>
      acc.enqueue((u, w, edge, weight(edge)))
      acc
  }
  visited(start) = true
  val edges = mutable.ListBuffer.empty[Int]
  val exWeights = mutable.Map.empty[Int, Int]
  val ex = Array.fill(n)(-1)
  ex(start) = 0

  while (expand.nonEmpty) {
    val (u, w, edge, _) = expand.dequeue()
    if (!visited(u)) {
      visited(u) = true
      edges += edge
      data(u).foreach { case(u1, w1, edge1) =>
        if (!visited(u1) && (ex(u1) == -1 || ex(u1) > w + w1)) {
          ex(u1) = w + w1
          expand.enqueue((u1, w + w1, edge1, weight(edge1)))
        }
      }
    }
  }

  val sum = edges.foldLeft(0) {
    case(acc, el) => acc + weight(el)
  }

  println(sum)
  println(edges.mkString(" "))

}

object ContestLib {
  import scala.io.StdIn._
  def readIntArray() = readLine().split(' ').map(_.toInt)
  def readInt() = scala.io.StdIn.readInt()

  def SecondOrdering[T1, T2, T3, T4](implicit ord1: Ordering[T1],
                                 ord2: Ordering[T2],
                                 ord3: Ordering[T3],
                                 ord4: Ordering[T4]
                                  ): Ordering[(T1, T2, T3, T4)]  =
    new Ordering[(T1, T2, T3, T4)]{
      def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {
        val res = -ord2.compare(x._2, y._2)
        if (res == 0)
          return -ord4.compare(x._4, y._4)
        res
      }

  }
}

import scala.collection._

object Solution extends App {
  import ContestLib._
  val Array(n, m) = readIntArray()
  var weight = Map.empty[Int, Int]
  val data = Range(1, m + 1).foldLeft(Array.fill(n)(mutable.Set.empty[(Int, Int, Int)])) {
    case(acc, el) =>
      val Array(u, v, w) = readIntArray()
      weight += (el -> w)
      acc(u - 1) += ((v - 1, w, el))
      acc(v - 1) += ((u - 1, w, el))
      acc
  }
  val visited = Array.fill(n)(false)
  val start = readInt()
  var expand = data(0).foldLeft(SortedMap.empty[Int, (Int, Int)]) {
    case (acc, (u, w, edge)) => acc + (u -> (w, edge))
  }
  visited(0) = true
  var edges = Set.empty[Int]

  while (expand.nonEmpty) {
    val (u, (w, edge)) = expand.head
    expand = expand.tail
    if (!visited(u)) {
      visited(u) = true
      edges += edge
      data(u).foreach { case(u1, w1, edge1) =>
        if (!visited.contains(u1) || (!expand.contains(u1) || (expand(u1)._1 > w + w1))) {
          expand += (u1 -> (w + w1, edge1))
        }
      }
    }
  }

  val sum = edges.foldLeft(0) {
    case(acc, el) => acc + weight(el)
  }

  println(sum)
  println(edges.mkString(" "))

}

object ContestLib {
  import scala.io.StdIn._
  def readIntArray() = readLine().split(' ').map(_.toInt)
  def readInt() = scala.io.StdIn.readInt()
}

import scala.collection._
import scala.math.Ordering

object Solution extends App {
  import ContestLib._
  val Array(n, m) = readIntArray()
  var weight = Map.empty[Int, Int]
  val data = Range(1, m + 1).foldLeft(Array.fill(n)(mutable.Set.empty[(Int, Int, Int)])) {
    case(acc, el) =>
      val Array(u, v, w) = readIntArray()
      weight += (el -> w)
      acc(u - 1) += ((v - 1, w, el))
      acc(v - 1) += ((u - 1, w, el))
      acc
  }
  val visited = Array.fill(n)(false)
  val start = readInt()
  var expand = data(0).foldLeft(mutable.PriorityQueue.empty[(Int, Int, Int)](SecondOrdering)) {
    case (acc, (u, w, edge)) =>
      acc += ((u, w, edge))
  }
  visited(0) = true
  var edges = Set.empty[Int]

  while (expand.nonEmpty) {
    val (u, w, edge) = expand.head
    expand = expand.tail
    if (!visited(u)) {
      visited(u) = true
      edges += edge
      data(u).foreach { case(u1, w1, edge1) =>
        if (!visited.contains(u1)) expand += ((u1, w + w1, edge1))
      }
    }
  }

  val sum = edges.foldLeft(0) {
    case(acc, el) => acc + weight(el)
  }

  println(sum)
  println(edges.mkString(" "))

}

object ContestLib {
  import scala.io.StdIn._
  def readIntArray() = readLine().split(' ').map(_.toInt)
  def readInt() = scala.io.StdIn.readInt()

  def SecondOrdering[T1, T2, T3](implicit ord1: Ordering[T1],
                                 ord2: Ordering[T2],
                                 ord3: Ordering[T3]
                                  ): Ordering[(T1, T2, T3)]  =
    new Ordering[(T1, T2, T3)]{
      def compare(x: (T1, T2, T3), y: (T1, T2, T3)): Int = {
        val compare2 = ord2.compare(x._2, y._2)
        if (compare2 != 0) return compare2
        0
      }

  }
}

object E{
   object Edge {
      def apply(s:String): Edge={
        val t=s.split(" ")
        Edge(u=t(0).toInt,v=t(1).toInt,w=t(2).toInt)
      }
    }
    case class Edge(u: Int, v: Int, w: Int)
  def main(args: Array[String]){

    import scala.collection.mutable.ArrayBuffer
    var in=io.Source.stdin.getLines()
    val t=in.next().split(" ")
    val n=t(0).toInt
    val m=t(1).toInt
    val edge={for(_<-1 to m) yield Edge(in.next())}.toArray

    var edgeof =Array.fill(n+1)(new ArrayBuffer[Int]())
    for(i<-0 until edge.length){
      edgeof(edge(i).u)+=i;
      edgeof(edge(i).v)+=i;
    }
    val d=Array.fill(n+1)(Int.MaxValue)
    val u0=in.next().toInt
    val q = new scala.collection.mutable.Queue[Int]
    val selectedEdge=Array.fill(n+1)(-1)
    q+=u0
    d(u0)=0

    while(!q.isEmpty){
      val u=q.dequeue
      for(i<-edgeof(u)){
        var p=edge(i).u
        if(u==p){
          p=edge(i).v
        }
        if(d(p)>d(u)+edge(i).w){
          d(p)=d(u)+edge(i).w
          if(!q.exists(_ == p)){
            q+=p
          }
          selectedEdge(p)=i
        }
        else if(d(p)==d(u)+edge(i).w){
          if(edge(selectedEdge(p)).w>edge(i).w){
            selectedEdge(p)=i
          }
        }
      }
    }
    var sum=0
    for(i<-1 until n if i != u0){ sum+=edge(selectedEdge(i)).w}
    println(sum)
    for(i<-1 until n if i != u0){ print(selectedEdge(i)+1);print (' ')}
  }
}

object E{
  def main(args: Array[String]){
    println("good here")
  }
}

object Etest{
  case class Edge(u: Int, v: Int, w: Int)

object Edge {
  def apply(s:String): Edge={
    val t=s.split(" ")
    Edge(u=t(0).toInt,v=t(1).toInt,w=t(2).toInt)
  }
}

  def main(args: Array[String]){
    println("good here")
  }
}

object E2{
   object Edge {
      def apply(s:String): Edge={
        val t=s.split(" ")
        Edge(u=t(0).toInt,v=t(1).toInt,w=t(2).toInt)
      }
    }
    case class Edge(u: Int, v: Int, w: Int)
  def main(args: Array[String]){
   import scala.collection.mutable.PriorityQueue
    import scala.collection.mutable.ArrayBuffer
    import util.control.Breaks._
    var in=io.Source.stdin.getLines()
    val t=in.next().split(" ")

    val n=t(0).toInt

    val m=t(1).toInt
    val edge={for(_<-1 to m) yield Edge(in.next())}.toArray

    var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Int,Int)]())
    for(i<-0 until edge.length){
      edgeof(edge(i).u)+=((edge(i).v,i,edge(i).w));
      edgeof(edge(i).v)+=((edge(i).u,i,edge(i).w));
    }
    val d=Array.fill(n+1)(Int.MaxValue)
    val u0=in.next().toInt
    val q = new PriorityQueue[(Int,Int)]()(Ordering.by((t:(Int,Int))=> t._1))
    val selectedEdge=Array.fill(n+1)(-1)

    d(u0)=0
    q.enqueue((d(u0),u0))
    val mark=Array.fill(n+1)(false)
    while(!q.isEmpty){
      breakable{
        val u=q.dequeue._2
        if(mark(u)){
          break
        }
        mark(u)=true
        for(p<-edgeof(u)){
          if(d(p._1)>d(u)+p._3){
            d(p._1)=d(u)+p._3
            q.enqueue((d(p._1),p._1))
            selectedEdge(p._1)=p._2
          }
        }
      }
    }
    for(i<-0 until edge.length){
      val e=edge(i)
      if(d(e.u)==d(e.v)+e.w && edge(selectedEdge(e.u)).w>e.w){
        selectedEdge(e.u)=i

      }
      if(d(e.v)==d(e.u)+e.w && edge(selectedEdge(e.v)).w>e.w){
        selectedEdge(e.v)=i

      }

    }
    var sum=0

    for(i<-1 to n if i != u0){ sum+=edge(selectedEdge(i)).w}
    println(sum)
    for(i<-1 to n if i != u0){ print(selectedEdge(i)+1);print (' ')}
  }
}

object E3{
  def main(args: Array[String]){
   import scala.collection.mutable.PriorityQueue
    import scala.collection.mutable.ArrayBuffer
    import util.control.Breaks._
//    var in=io.Source.stdin.getLines()
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next

    val n=nextInt

    val m=nextInt
    val U=new Array[Int](m)
    val V=new Array[Int](m)
    val W=new Array[Long](m)
    for(i <- 0 until m)
    {
      U(i)=nextInt
      V(i)=nextInt
      W(i)=nextLong
    }

    var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())
    for(i<-0 until U.length){
      edgeof(U(i))+=((V(i),W(i)));
      edgeof(V(i))+=((U(i),W(i)));
    }
    val d=Array.fill(n+1)(Long.MaxValue)
    val u0=nextInt
    val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))

    d(u0)=0
    q.enqueue((d(u0),u0))
    val mark=Array.fill(n+1)(false)
    while(!q.isEmpty){
      breakable{
        val u=q.dequeue._2
        if(mark(u)){
          break
        }
        mark(u)=true
        for(p<-edgeof(u)){
          if(d(p._1)>d(u)+p._2){
            d(p._1)=d(u)+p._2
            q.enqueue((d(p._1),p._1))
          }
        }
      }
    }

    var sum=0L
    val selectedEdge=Array.fill(n+1)(-1)
    for(i<-0 until U.length){
      if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){
        selectedEdge(U(i))=i

      }
      if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){
        selectedEdge(V(i))=i

      }

    }

    for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}
    out.println(sum)
    for(i<-1 to n if i != u0){ print((selectedEdge(i)+1)+" ") }
    out.println()
    out.flush
    out.close

  }
}

object E3{
  def main(args: Array[String]){
   import scala.collection.mutable.PriorityQueue
    import scala.collection.mutable.ArrayBuffer
    import util.control.Breaks._
//    var in=io.Source.stdin.getLines()
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next

    val n=nextInt

    val m=nextInt
    val U=new Array[Int](m)
    val V=new Array[Int](m)
    val W=new Array[Long](m)
    for(i <- 0 until m)
    {
      U(i)=nextInt
      V(i)=nextInt
      W(i)=nextLong
    }

    var edgeof =Array.fill(n+1)(new ArrayBuffer[(Int,Long)]())
    for(i<-0 until U.length){
      edgeof(U(i))+=((V(i),W(i)));
      edgeof(V(i))+=((U(i),W(i)));
    }
    val d=Array.fill(n+1)(Long.MaxValue)
    val u0=nextInt
    val q = new PriorityQueue[(Long,Int)]()(Ordering.by((t:(Long,Int))=> -t._1))

    d(u0)=0
    q.enqueue((d(u0),u0))
    val mark=Array.fill(n+1)(false)
    while(!q.isEmpty){
      breakable{
        val u=q.dequeue._2
        if(mark(u)){
          break
        }
        mark(u)=true
        for(p<-edgeof(u)){
          if(d(p._1)>d(u)+p._2){
            d(p._1)=d(u)+p._2
            q.enqueue((d(p._1),p._1))
          }
        }
      }
    }

    var sum=0L
    val selectedEdge=Array.fill(n+1)(-1)
    for(i<-0 until U.length){
      if(d(U(i))==d(V(i))+W(i) && (selectedEdge(U(i))== -1 || (W(selectedEdge(U(i)))>W(i)))){
        selectedEdge(U(i))=i

      }
      if(d(V(i))==d(U(i))+W(i) && (selectedEdge(V(i))== -1 || (W(selectedEdge(V(i))))>W(i))){
        selectedEdge(V(i))=i

      }

    }

    for(i<-1 to n if i != u0){ sum+=W(selectedEdge(i))}
    out.println(sum)
    for(i<-1 to n if i != u0){ out.print((selectedEdge(i)+1)+' ')}
    out.println()

  }
}


You are given a string $$$s=s_1s_2\dots s_n$$$ of length $$$n$$$, which only contains digits $$$1$$$, $$$2$$$, ..., $$$9$$$.A substring $$$s[l \dots r]$$$ of $$$s$$$ is a string $$$s_l s_{l + 1} s_{l + 2} \ldots s_r$$$. A substring $$$s[l \dots r]$$$ of $$$s$$$ is called even if the number represented by it is even. Find the number of even substrings of $$$s$$$. Note, that even if some substrings are equal as strings, but have different $$$l$$$ and $$$r$$$, they are counted as different substrings.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 65000$$$) — the length of the string $$$s$$$. The second line contains a string $$$s$$$ of length $$$n$$$. The string $$$s$$$ consists only of digits $$$1$$$, $$$2$$$, ..., $$$9$$$.

Print the number of even substrings of $$$s$$$.

NoteIn the first example, the $$$[l, r]$$$ pairs corresponding to even substrings are:   $$$s[1 \dots 2]$$$ $$$s[2 \dots 2]$$$ $$$s[1 \dots 4]$$$ $$$s[2 \dots 4]$$$ $$$s[3 \dots 4]$$$ $$$s[4 \dots 4]$$$ In the second example, all $$$10$$$ substrings of $$$s$$$ are even substrings. Note, that while substrings $$$s[1 \dots 1]$$$ and $$$s[2 \dots 2]$$$ both define the substring "2", they are still counted as different substrings.

//package codeforces.contest1139

object EvenSubstrings {

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val string = io.StdIn.readLine()

    println(string.map(_ - '0').zipWithIndex.filter(_._1 % 2 == 0).map(_._2 + 1).sum)
  }

}

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 java.util.Arrays

  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 = ni()
    val S = ns(N)
    var ans = 0L
    REP(N) { i =>
      if ((S(i) - '0') % 2 == 0) ans += i + 1
    }
    out.println(ans)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

  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 = 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 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]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.io.StdIn

object A1139 {
  def main(args: Array[String]): Unit = {
    StdIn.readLine
    println(StdIn.readLine.zipWithIndex.withFilter{i=>"2468".contains(i._1)}.map{_._2 + 1}.sum)
  }
}

object A1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val str = stdin.readLine().map(x => x -'0').map(_ & 1)
    var ans = 0L
    for (i <- 0 until n if str(i) == 0){
        ans = ans + (i+1)
    }
    println(ans)
  }
}

object A1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val str = stdin.readLine()
    var ans = 0L
    for (i <- 0 until n){
      val temp = str(i) - '0'
      if (temp % 2 == 0){
        ans = ans + (i+1)
      }
    }
    println(ans)
  }
}

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

  override def apply(io: IO): io.type = {
    val _, s = io.read[String]

    val ans = s.toCharArray
      .map(_ - '0')
      .zipWithIndex
      .collect({case (c, i) if c%2 == 0 => i + 1 })
      .sum

    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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


Eshag has an array $$$a$$$ consisting of $$$n$$$ integers.Eshag can perform the following operation any number of times: choose some subsequence of $$$a$$$ and delete every element from it which is strictly larger than $$$AVG$$$, where $$$AVG$$$ is the average of the numbers in the chosen subsequence.For example, if $$$a = [1 , 4 , 3 , 2 , 4]$$$ and Eshag applies the operation to the subsequence containing $$$a_1$$$, $$$a_2$$$, $$$a_4$$$ and $$$a_5$$$, then he will delete those of these $$$4$$$ elements which are larger than $$$\frac{a_1+a_2+a_4+a_5}{4} = \frac{11}{4}$$$, so after the operation, the array $$$a$$$ will become $$$a = [1 , 3 , 2]$$$.Your task is to find the maximum number of elements Eshag can delete from the array $$$a$$$ by applying the operation described above some number (maybe, zero) times.A sequence $$$b$$$ is a subsequence of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements.

The first line contains an integer $$$t$$$ $$$(1\le t\le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 100)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1\le a_i \le 100)$$$ — the elements of the array $$$a$$$.

For each test case print a single integer — the maximum number of elements Eshag can delete from the array $$$a$$$.

NoteConsider the first test case.Initially $$$a = [1, 1, 1, 2, 2, 3]$$$.In the first operation, Eshag can choose the subsequence containing $$$a_1$$$, $$$a_5$$$ and $$$a_6$$$, their average is equal to $$$\frac{a_1 + a_5 + a_6}{3} = \frac{6}{3} = 2$$$. So $$$a_6$$$ will be deleted.After this $$$a = [1, 1, 1, 2, 2]$$$.In the second operation, Eshag can choose the subsequence containing the whole array $$$a$$$, the average of all its elements is equal to $$$\frac{7}{5}$$$. So $$$a_4$$$ and $$$a_5$$$ will be deleted.After this $$$a = [1, 1, 1]$$$.In the second test case, Eshag can't delete any element.

import scala.io.StdIn._

object A extends App {
  for (_ <- 0 until readInt) {
    println(
      readInt - readLine.split(" ").foldLeft((Int.MaxValue, 1)) {
        case (t @ (min, cpt), x) =>
          val i = x.toInt
          if (i < min)
            (i, 1)
          else if (i == min)
            (i, cpt + 1)
          else
            t
      }._2
    )
  }
}


One department of some software company has $$$n$$$ servers of different specifications. Servers are indexed with consecutive integers from $$$1$$$ to $$$n$$$. Suppose that the specifications of the $$$j$$$-th server may be expressed with a single integer number $$$c_j$$$ of artificial resource units.In order for production to work, it is needed to deploy two services $$$S_1$$$ and $$$S_2$$$ to process incoming requests using the servers of the department. Processing of incoming requests of service $$$S_i$$$ takes $$$x_i$$$ resource units.The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $$$S_i$$$ is deployed using $$$k_i$$$ servers, then the load is divided equally between these servers and each server requires only $$$x_i / k_i$$$ (that may be a fractional number) resource units.Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.

The first line contains three integers $$$n$$$, $$$x_1$$$, $$$x_2$$$ ($$$2 \leq n \leq 300\,000$$$, $$$1 \leq x_1, x_2 \leq 10^9$$$) — the number of servers that the department may use, and resource units requirements for each of the services. The second line contains $$$n$$$ space-separated integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 10^9$$$) — the number of resource units provided by each of the servers.

If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes). Otherwise print the word "Yes" (without the quotes).  In the second line print two integers $$$k_1$$$ and $$$k_2$$$ ($$$1 \leq k_1, k_2 \leq n$$$) — the number of servers used for each of the services. In the third line print $$$k_1$$$ integers, the indices of the servers that will be used for the first service. In the fourth line print $$$k_2$$$ integers, the indices of the servers that will be used for the second service. No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them.

NoteIn the first sample test each of the servers 1, 2 and 6 will will provide $$$8 / 3 = 2.(6)$$$ resource units and each of the servers 5, 4 will provide $$$16 / 2 = 8$$$ resource units.In the second sample test the first server will provide $$$20$$$ resource units and each of the remaining servers will provide $$$32 / 3 = 10.(6)$$$ resource units.

object B extends App {

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

  val Array(_n, x1, x2) = readLongs(3)
  val n = _n.toInt
  val cs = readLongs(n).zipWithIndex.sortBy(- _._1)

  var split1, split2 = -1
  var i = 0
  while (i < n) {
    val cap = cs(i)._1 * (i + 1).toLong
    i += 1
    if (split1 == -1 && cap >= x1) {
      split1 = i
    }
    if (split2 == -1 && cap >= x2) {
      split2 = i
    }
  }

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

  if (split1 > 0) {
    var end = split1
    while (end < n) {
      val cap = cs(end)._1 * (end - split1 + 1).toLong
      end += 1
      if (cap >= x2) {
        println("Yes")
        println(s"$split1 ${end - split1}")
        println(cs.take(split1).map(_._2 + 1).mkString(" "))
        println(cs.slice(split1, end).map(_._2 + 1).mkString(" "))
        Console.flush
        System.exit(0)
      }
    }
  }

  if (split2 > 0) {
    var end = split2
    while (end < n) {
      val cap = cs(end)._1 * (end - split2 + 1).toLong
      end += 1
      if (cap >= x1) {
        println("Yes")
        println(s"${end - split2} $split2")
        println(cs.slice(split2, end).map(_._2 + 1).mkString(" "))
        println(cs.take(split2).map(_._2 + 1).mkString(" "))
        Console.flush
        System.exit(0)
      }
    }
  }

  println("No")

  Console.flush
}

object B extends App {

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

  val Array(_n, x1, x2) = readLongs(3)
  val n = _n.toInt
  val cs = readLongs(n).zipWithIndex.sortBy(- _._1)

  var split1, split2 = -1
  var i = 0
  while (i < n) {
    val cap = cs(i)._1 * (i + 1).toLong
    i += 1
    if (split1 == -1 && cap >= x1) {
      split1 = i
    }
    if (split2 == -1 && cap >= x2) {
      split2 = i
    }
  }

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

  if (split1 > 0) {
    var end = split1
    while (end < n) {
      val cap = cs(end)._1 * (end - split1 + 1).toLong
      end += 1
      if (cap >= x2) {
        println("Yes")
        println(s"$split1 ${end - split1}")
        println(cs.take(split1).map(_._2 + 1).mkString(" "))
        println(cs.slice(split1, end).map(_._2 + 1).mkString(" "))
        Console.flush
        System.exit(0)
      }
    }
  }

  if (split2 > 0) {
    var end = split2
    while (end < n) {
      val cap = cs(end)._1 * (end - split2 + 1).toLong
      end += 1
      if (cap >= x1) {
        println("Yes")
        println(s"$split2 ${end - split2}")
        println(cs.slice(split2, end).map(_._2 + 1).mkString(" "))
        println(cs.take(split2).map(_._2 + 1).mkString(" "))
        Console.flush
        System.exit(0)
      }
    }
  }

  println("No")

  Console.flush
}

object B extends App {

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

  val Array(n, x1, x2) = readInts(3)
  val cs = readLongs(n).zipWithIndex.sortBy(- _._1)

  var split1, split2 = -1
  var i = 0
  while (i < n) {
    val cap = (i + 1) * cs(i)._1
    i += 1
    if (split1 == -1 && cap >= x1) {
      split1 = i
    }
    if (split2 == -1 && cap >= x2) {
      split2 = i
    }
  }

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

  if (split1 > 0) {
    var end = split1
    while (end < n) {
      val cap = (end - split1 + 1) * cs(end)._1
      end += 1
      if (cap >= x2) {
        println("Yes")
        println(s"$split1 ${end - split1}")
        println(cs.take(split1).map(_._2 + 1).mkString(" "))
        println(cs.slice(split1, end).map(_._2 + 1).mkString(" "))
        Console.flush
        System.exit(0)
      }
    }
  }

  if (split2 > 0) {
    var end = split2
    while (end < n) {
      val cap = (end - split2 + 1) * cs(end)._1
      end += 1
      if (cap >= x1) {
        println("Yes")
        println(s"$split2 ${end - split2}")
        println(cs.slice(split2, end).map(_._2 + 1).mkString(" "))
        println(cs.take(split2).map(_._2 + 1).mkString(" "))
        Console.flush
        System.exit(0)
      }
    }
  }

  println("No")

  Console.flush
}

object B extends App {

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

  val Array(_n, x1, x2) = readLongs(3)
  val n = _n.toInt
  val cs = readLongs(n).zipWithIndex.sortBy(- _._1)

  var split1, split2 = -1
  var i = 0
  while (i < n) {
    val cap = cs(i)._1 * (i + 1).toLong
    i += 1
    if (split1 == -1 && cap >= x1) {
      split1 = i
    }
    if (split2 == -1 && cap >= x2) {
      split2 = i
    }
  }

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

  if (split2 > 0) {
    var end = split2
    while (end < n) {
      val cap = cs(end)._1 * (end - split2 + 1).toLong
      end += 1
      if (cap >= x1) {
        println("Yes")
        println(s"$split2 ${end - split2}")
        println(cs.slice(split2, end).map(_._2 + 1).mkString(" "))
        println(cs.take(split2).map(_._2 + 1).mkString(" "))
        Console.flush
        System.exit(0)
      }
    }
  }

  if (split1 > 0) {
    var end = split1
    while (end < n) {
      val cap = cs(end)._1 * (end - split1 + 1).toLong
      end += 1
      if (cap >= x2) {
        println("Yes")
        println(s"$split1 ${end - split1}")
        println(cs.take(split1).map(_._2 + 1).mkString(" "))
        println(cs.slice(split1, end).map(_._2 + 1).mkString(" "))
        Console.flush
        System.exit(0)
      }
    }
  }

  println("No")

  Console.flush
}