class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def same(self, x, y): return self.find(x) == self.find(y) def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def size(self, x): return abs(self.parents[self.find(x)]) def groups(self): roots = self.roots() r_to_g = {} for i, r in enumerate(roots): r_to_g[r] = i groups = [[] for _ in roots] for i in range(self.n): groups[r_to_g[self.find(i)]].append(i) return groups n, m = map(int, input().split()) G = [set() for _ in range(n)] for i in range(n): b, c = map(int, input().split()) b -= 1 c -= 1 G[c].add(b) uf = UnionFind(n) G = [list(g) for g in G] res = 0 for g in G: for i in range(len(g)-1): if uf.same(g[i],g[i+1]): continue uf.union(g[i],g[i+1]) res += 1 print(res)