• + 0 comments

    scala and the power of PriorityQueue :)

    import scala.collection.mutable.PriorityQueue
    
    object Solution {
      def main(args: Array[String]): Unit = {
        val in = Iterator
          .continually(io.StdIn.readLine())
          .takeWhile(null != _)
          .map(_.trim)
        val Array(n, q) = in.next().split(' ').map(_.toInt)
        val armies = Array.fill(n)(PriorityQueue.empty[Int])
        def findStrongest(i: Int): Unit = println(armies(i - 1).headOption.orNull)
        def strongestDied(i: Int): Unit = armies(i - 1).dequeue()
        def recruit(i: Int, c: Int): Unit = armies(i - 1).addOne(c)
        def merge(i: Int, j: Int): Unit = armies(i - 1).addAll(armies(j - 1).dequeueAll)
        for (_ <- 1 to q) {
          in.next().split(' ').map(_.toInt) match {
            case Array(1, i)    => findStrongest(i)
            case Array(2, i)    => strongestDied(i)
            case Array(3, i, c) => recruit(i, c)
            case Array(4, i, j) => merge(i, j)
            case event          => throw new RuntimeException(s"invalid event type ${event.headOption.orNull}")
          }
        }
      }
    }