This seems like a fairly easy task: just using DFS from the existing nodes (the ones that have at least one edge) would solve the problem, but I keep getting WA. The 2 functions are:
map<int, vi> adj;
map<int, int> visited;
int dist;
void dfs(int cur, int p){
visited[cur] = 1;
for(int j = 0; j < adj[cur].size(); j++){
if( visited[ adj[cur][j] ] == 0 && adj[cur][j] != p ){
dist--;
dfs( adj[cur][j], cur);
}
}
}
void totalGroups(int n){
for(map<int, vi>::iterator i = adj.begin(); i!= adj.end(); i++){
if( visited[ (i->first) ] == 0 ){
dfs( (i->first), (i->first) );
}
}
}