class Solution {
public:
int x[100010];
int DFS(int pos)
{
if(x[pos]!=pos)
{
x[pos]=DFS(x[pos]);
return x[pos];
}
return pos;
}
int makeConnected(int n, vector<vector<int>>& connections) {
int line_remain=0;
int line_need=0;
set<int>Union;
if(connections.size()<n-1)return -1;
for(int i=0;i<n;i++)
x[i]=i;
for(auto vec:connections)
{
int pos1=vec[0];
int pos2=vec[1];
int temp1=DFS(pos1);
int temp2=DFS(pos2);
if(temp1!=temp2) // !!!!请记住,这里更新的是两父节点,比赛时忘记了,找了半天原因
{
x[temp2]=temp1;
}
}
for(int i=0;i<n;i++)
{
if(DFS(i)==i)Union.insert(i);
}
return Union.size()-1;
}
};