1319. 連通網絡的操作次數

 

 

1319. 連通網絡的操作次數
用以太網線纜將 n 臺計算機連接成一個網絡,
計算機的編號從
0 到 n-1。線纜用 connections 表示,
其中 connections[i] = [a, b] 連接了計算機 a 和 b。 網絡中的任何一臺計算機都可以通過網絡直接
或者間接訪問同一個網絡中其他任意一臺計算機。 給你這個計算機網絡的初始佈線 connections,
你可以拔開任意兩臺直連計算機之間的線纜,
並用它連接一對未直連的計算機。
請你計算並返回使所有計算機都連通所需的
最少操作次數。如果不可能,則返回
-1 。 示例 1: 輸入:n = 4, connections = [[0,1],[0,2],[1,2]] 輸出:1 解釋:拔下計算機 12 之間的線纜,並將它插到計算機 13 上。

示例
2: 輸入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] 輸出:2


示例
3: 輸入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]] 輸出:-1 解釋:線纜數量不足。

示例
4: 輸入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]] 輸出:0 提示: 1 <= n <= 10^5 1 <= connections.length <= min(n*(n-1)/2, 10^5) connections[i].length == 2 0 <= connections[i][0], connections[i][1] < n connections[i][0] != connections[i][1] 沒有重複的連接。 兩臺計算機不會通過多條線纜連接。

 

 

 

//並查集模板
class UnionFind{
public:
    vector<int> parent;
    vector<int> size;
    int n;
    //當前連通分量數目
    int setCount;

public:
    UnionFind(int _n):n(_n),setCount(_n), parent(_n),size(_n,1)
    {
        iota(parent.begin(), parent.end(), 0);
    }

    int findset(int x)
    {
        return parent[x]==x ? x: parent[x]=findset(parent[x]);
    }

    bool unite(int x, int y)
    {
        x = findset(x);
        y = findset(y);
        if(x == y)
        {
            return false;
        }
        if(size[x] < size[y])
        {
            swap(x,y);
        }
        parent[y] = x;
        size[x] += size[y];
        --setCount; //在這裏統計的連通分量個數
        return true;
    }

    bool connected(int x, int y)
    {
        x = findset(x);
        y = findset(y);
        return x == y;
    }
};

class Solution{

public:
    int makeConnected(int n, vector<vector<int>>& connections)
    {
        if(connections.size()< n-1)
        {
            return -1;
        }

        UnionFind uf(n);
        for(const auto& conn:connections)
        {
            uf.unite(conn[0],conn[1]);
        }

        return uf.setCount-1;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章