n, m = map(int, input().split()) box = [[]for _ in range(m+1)] color = [[]for _ in range(n+1)] for _ in range(n): b, c = map(int, input().split()) box[b].append(c) color[c].append(b) boxused = [-1]*(m+1) boxused[0]= 0 colorused = [-1]*(n+1) colorused[0] = 0 from collections import deque cnt = 0 for i in range(m+1): if boxused[i] == -1: d = deque() d.append(i) boxused[i] = 0 while d: v = d.popleft() for x in box[v]: if colorused[x] == -1: colorused[x] = 0 for y in color[x]: if boxused[y] == -1: boxused[y] = 0 d.append(y) cnt += 1 print(cnt)