https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected/
需要求出每一个联通的块有多少个点、有多少条边,联通n个点最少需要n-1条边。先求出每个连通块多余的边,然后求出一共有多少个联通块,看看多余的边能不能联通这些块。这里用了递归的思想,把联通块看成一个点。
使用并查集,用来表示联通块,以及统计数量。
class Solution {
public:
int root[100005];
int edge_count[100005];
int node_count[100005];
int merge(int u,int v){
printf("%d %d\n",u,v);
if(root[u]!=-1){
root[u]=merge(root[u],v);
}
else if(root[v]!=-1)
root[v]=merge(u,root[v]);
else{
edge_count[u]+=1;
if(u!=v){
root[v]=u;
node_count[u]+=node_count[v];
edge_count[u]+=edge_count[v];
printf("aaaa %d %d\n",u,v);
}
}
return u;
}
int makeConnected(int n, vector<vector<int>>& connections) {
memset(root,-1,sizeof(root));
memset(edge_count,0,sizeof(edge_count));
for(int i=0;i<n;i++)
node_count[i]=1;
for(int i=0;i<connections.size();i++){
int u=connections[i][0];
int v=connections[i][1];
merge(u,v);
}
int jihe_count=0;
int more_edge_count=0;
for(int i=0;i<n;i++){
if(root[i]==-1){
jihe_count++;
more_edge_count+=(edge_count[i]-(node_count[i]-1));
}
}
if(more_edge_count<jihe_count-1)
return -1;
return jihe_count-1;
}
};