• + 0 comments

    scala

    import scala.io.StdIn
    
    object Solution {
      private final case class Pair(i1: Int, i2: Int)
    
      private def group(n: Int, pairs: Seq[Pair]): Seq[Seq[Int]] = {
        val parents = (0 to n).toArray
    
        def root(i: Int): Int = {
          if (parents(i) != i)
            parents(i) = root(parents(i))
          parents(i)
        }
    
        pairs.foreach { pair =>
          val root1 = root(pair.i1)
          val root2 = root(pair.i2)
          if (root1 < root2)
            parents(root2) = root1
          else if (root1 > root2)
            parents(root1) = root2
        }
        (1 to n).groupBy(root).values.toSeq
      }
    
      private def cost(n: Int): Int = {
        math.ceil(math.sqrt(n)).toInt
      }
    
      def main(args: Array[String]): Unit = {
        val arr = Iterator
          .continually(StdIn.readLine())
          .takeWhile(null != _)
          .map(_.trim)
        val n = arr.next().toInt
        val m = arr.next().toInt
        val pairs = (1 to m)
          .map(_ => arr.next().split(' ').map(_.toInt))
          .map(p => Pair(p.head, p.last))
        val groups = group(n, pairs)
        val costs = groups.map(_.length).map(cost)
        println(costs.sum)
      }
    }