Leetcode每日一题:1319 连通网络的操作次数 (并查集)

分析

并查集问题,遍历所有边把点之间的关系关联起来,最后看一下总的连通块个数,减去1就是答案。

C++ 代码
class Solution {
public:
    int find(int x)
    {
        if(fa[x]!=x) fa[x]=find(fa[x]);
        return fa[x];
    }
    unordered_set s;
    vector fa;
    int makeConnected(int n, vector>& connections) {
        int need=connections.size();
        if(need+1(n);
        for(int i=0;i

你可能感兴趣的:(leetcode,算法)