import sys readline = sys.stdin.readline sys.setrecursionlimit(10**7) def scc(N, G, RG): order = [] used = [0]*N group = [None]*N def dfs(s): used[s] = 1 for t in G[s]: if not used[t]: dfs(t) order.append(s) def rdfs(s, col): group[s] = col used[s] = 1 for t in RG[s]: if not used[t]: rdfs(t, col) for i in range(N): if not used[i]: dfs(i) used = [0]*N label = 0 for s in reversed(order): if not used[s]: rdfs(s, label) label += 1 return label, group # 縮約後のグラフを構築 def construct(N, G, label, group): G0 = [set() for i in range(label)] GP = [[] for i in range(label)] for v in range(N): lbs = group[v] for w in G[v]: lbt = group[w] if lbs == lbt: continue G0[lbs].add(lbt) GP[lbs].append(v) return G0, GP from bisect import * from copy import deepcopy def compress(lst): """ B: lstを座圧したリスト D: 元の値からindexを取得する辞書 """ B = [] D = dict() vals = deepcopy(lst) vals = list(set(vals)) vals.sort() for i in range(len(lst)): ind = bisect_left(vals, lst[i]) B.append(ind) for i in range(len(B)): D[lst[i]] = B[i] return B, D class UnionFind(object): def __init__(self, n=1): self.par = [i for i in range(n)] self.rank = [0 for _ in range(n)] self.size = [1 for _ in range(n)] def find(self, x): if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x != y: if self.rank[x] < self.rank[y]: x, y = y, x if self.rank[x] == self.rank[y]: self.rank[x] += 1 self.par[y] = x self.size[x] += self.size[y] def is_same(self, x, y): return self.find(x) == self.find(y) def get_size(self, x): x = self.find(x) return self.size[x] N = int(readline()) H, W = [0] * N, [0] * N for i in range(N): H[i], W[i] = map(int, readline().split()) D, _ = compress(H + W) M = max(D) + 1 G = [[] for i in range(M)] RG = [[] for i in range(M)] U = UnionFind(M) for i in range(N): G[D[i]].append(D[i + N]) RG[D[i + N]].append(D[i]) U.union(D[i], D[i + N]) if U.get_size(0) != M: print(0) exit() label, group = scc(M, G, RG) G0, GP = construct(M, G, label, group) print(len(GP[0]))