每日一题:leetcode1319.联通网络的操作次数

题目描述

在这里插入图片描述

题目分析

ps:这篇博客是补前天的,前天在老家不方便写博客
题目挺简单的,但是通过题目对图的连通性有了一个更深刻的认识:如果有超过(或等于)n-1条边,则一定是可以让整个图联通的。
如果想让整个图联通,只需要求出整个图的联通分量个数,然后-1就是需要的边的个数(即让这写联通分量联通即可)

AC代码

class UnionFind {
public:
    vector<int> father;
    vector<int> size;
    int n;
    int setCount;
    UnionFind(int _n):n(_n),setCount(_n),father(_n),size(_n,1) {
        iota(father.begin(), father.end(), 0);
    }
    int root(int x) {
        return x == father[x] ? x : father[x] = root(father[x]);
    }
    bool unite(int x, int y) {
        x = root(x);
        y = root(y);
        if (x == y) {
            return false;
        }
        if (size[x] < size[y]) {
            swap(x, y);
        }
        father[y] = x;
        size[x] += size[y];
        --setCount;
        return true;
    }
    bool connected(int x, int y) {
        return root(x) == root(y);
    }
};
class Solution {
public:
    int makeConnected(int n, vector<vector<int>>& connections) {
        if (connections.size() < n - 1) {
            return -1;
        }
        UnionFind uf(n);
        for (auto &edge : connections) {
            uf.unite(edge[0], edge[1]);
        }
        return uf.setCount - 1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值