from functools import reduce


def parse_input():
    n = int(input())
    heads = []
    for _ in range(n):
        heads.append(list(map(int, input().split())))
    return n, heads


def calculate_different_groups(n, heads):
    groups = dict()
    for head in heads:
        if head[0] in groups.keys():
            groups[head[0]].add(head[1])
        else:
            groups[head[0]] = {head[1]}
    g = []
    for group in groups.values():
        l = set()
        for i, other in enumerate(g):
            if any(item in other for item in group):
                l.add(i)
        new_g = reduce(lambda a, b: a.union(b), (g[i] for i in l), group)
        g = [item for i, item in enumerate(g) if i not in l] + [new_g]
    return len(g) - 1


def main():
    n, heads = parse_input()
    answer = calculate_different_groups(n, heads)
    print(answer)

if __name__ == "__main__":
    main()
