lib C fun strtoll(s : UInt8*, p : UInt8**, b : Int32) : Int64 end class String def to_i64 C.strtoll(self, nil, 10) end end class UnionFind @d : Array(Int32) def initialize(n : Int32) @d = Array.new(n, -1) end def root(x : Int32) @d[x] < 0 ? x : (@d[x] = root(@d[x])) end def unite(x : Int32, y : Int32) x = root(x) y = root(y) return false if x == y x, y = y, x if @d[x] > @d[y] @d[x] += @d[y] @d[y] = x true end def same?(x : Int32, y : Int32) root(x) == root(y) end def size(x : Int32) -@d[root(x)] end def root?(x : Int32) @d[x] < 0 end end n, m = read_line.split.map(&.to_i) a = (0...n).map { [] of Int32 } n.times do b, c = read_line.split.map(&.to_i.pred) a[c] << b end uf = UnionFind.new(m) a.each do |b| b.sort.each_cons_pair { |i, j| uf.unite(i, j) } end puts (0...m).select { |i| uf.root?(i) }.sum { |i| uf.size(i) - 1 }