算法题:连通网络的操作次数

描述

用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b。

网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。

给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。

链接:https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected。

思路

若电脑数大于连接数减一,则无论如何都不会满足条件,直接返回-1;
求出并查集的个数size,连通size个节点需要size-1条线,返回size-1

代码

class Solution {
public:
    vector<int> fa;
    int size;
    int makeConnected(int n, vector<vector<int>>& connections) {
        if (connections.size() < n - 1) return -1;
        size = n;
        for (int i = 0;i < n;i++) {
            fa.push_back(i);
        }
        for (auto& conn : connections) {
            merge(conn[0], conn[1]);
        }

        return size - 1;
    }

    int find(int x) {
        if (fa[x] != x) fa[x] = find(fa[x]);
        return fa[x];
    }

    void merge(int x, int y) {
        int fa_x = find(x);
        int fa_y = find(y);
        if (fa_x == fa_y) return;
        fa[fa_x] = fa_y;
        size--;
    }
};

** 复杂度**
时间复杂度:O(n)
空间复杂度:O(n)

原文地址:https://www.cnblogs.com/dinjufen/p/14141706.html