LeetCode 1319. 连通网络的操作次数

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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值