#もう一度やる class UnionFind def initialize(n) @size = Array.new(n,0) @boss = Array.new(n,-1) @rank = Array.new(n,0) end def unite(x,y) x = find(x) y = find(y) return x == y if rank[x] < rank[y] @boss[x] = y @size[y] += @size[x] elsif rank[x] == rank[y] @rank[x] += 1 @boss[y] = x @size[x] += @size[y] else @boss[y] = x @size[x] += @size[y] end end def find(n) if @boss[n] == -1 return -1 else dd = find(@boss[n]) @boss[n] = dd return @boss[n] end end def same(x, y) fx = find(x) fy = find(y) if fx == fy && fx != -1 return true end end end n, m = gets.chomp.split(" ").map(&:to_i) hash = Hash.new{|i,j| hash[j]=[]} n.times do b, c = gets.chomp.split(" ").map(&:to_i) hash[c] << b end #hash 箱 色 ans = 0 uf = UnionFind.new(m + 1) hash.each do |box,colors| colors.each_cons(2) do |i,j| tf = uf.same(i, j) next if tf ans += 1 uf.unite(i,j) end end puts ans