class UnionFind def initialize(size); @p, @r = [*0...size], [1] * size; end def leader(i); j = i; until i == @p[i]; j, i = i, @p[j] = @p[i]; end; i; end def merge(i, j); k, l = leader(i), leader(j); return false if k == l; k, l = l, k if @r[k] < @r[l]; @p[l] = k; @r[k] += @r[l]; true; end def same?(i, j); leader(i) == leader(j); end def size(i); @r[leader(i)]; end end N, M = gets.split.map(&:to_i) slime2box = Array.new(N) { [] } uf = UnionFind.new(M) N.times do b, c = gets.split.map { |s| s.to_i - 1 } slime2box[c] << b end count = 0 slime2box.each do |boxes| boxes.each_cons(2) do |(i, j)| next if uf.same?(i, j) uf.merge(i, j) count += 1 end end puts count