import kotlin.collections.* import kotlin.math.* @kotlin.ExperimentalStdlibApi fun main() { val (n, m) = readLine()!!.split(" ").map { it.toInt() } val uni = UnionFind(m) val c2b = mutableMapOf() var ans = 0 for (i in 0 until n) { val (b, c) = readLine()!!.split(" ").map { it.toInt() } val box = c2b.get(c) when (box) { null -> c2b[c] = b else -> { if (!uni.merge(box, b)) continue ans++ c2b[c] = uni.root(b) } } } println(ans) } data class UnionFind(private val n : Int) { private data class node(var parent : Int? = null, var size : Int = 1) private val nodes = Array(n+1) { node() } fun root(x : Int): Int { return when(nodes[x].parent) { null -> x else -> { nodes[x].parent = root(nodes[x].parent!!); nodes[x].parent!! } } } fun merge(x : Int, y : Int) : Boolean{ var rx = root(x); var ry = root(y) if (rx == ry) return false if (nodes[rx].size < nodes[ry].size) rx = ry.also { ry = rx } nodes[ry].parent = rx; nodes[rx].size += nodes[ry].size return true } fun isSame(x : Int, y : Int) : Boolean { return root(x) == root(y) } fun size(x : Int) : Int { return nodes[root(x)].size } }