```
class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
int count = 0;
vector<int> root(n, -1);
for(int i=0; i<n; i++)
{
root[i] = i;
}
for(auto edge : edges)
{
int f = edge.first;
int s = edge.second;
while(f != root[f])
f = root[f];
while(s != root[s])
s = root[s];
root[f] = s;
}
for(int i=0; i<n; i++)
{
if(root[i] == i)
++count;
}
return count;
}
};
```