class DSU:
    def __init__(self, n):
        self.parents = {}
        self.count = n

    def find(self, x):
        while x != self.parents[x]:
            self.parents[x] = self.parents[self.parents[x]]
            x = self.parents[x]
        return x

    def union(self, x, y):
        par_x, par_y = self.find(x), self.find(y)
        if par_x != par_y:
            self.parents[par_y] = par_x


class Solution:
    def countComponents(self, n: int, edges):
        dst = DSU(n)
        for i in range(n):
            dst.parents[i] = i
        for s, e in edges:
            if dst.find(s) != dst.find(e):
                dst.union(s, e)
                dst.count-=1
        return dst.count