Likou 1319. The number of operations connected to the network and the collection + thinking

https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected/
Insert picture description here
Insert picture description here
Idea: Because the picture has a total of nnn points, then onlyn − 1 n-1nOne edge can make this graph connected. Since we can split edges arbitrarily and add them between the appropriate vertices, if the given number of edges<n − 1 <n-1<n1 Then there must be no solution, otherwise there must be a solution. The minimum number of operations required when there is a solution is equal to the number of connected components of the graph− 1 -11 . How to find the number of connected components? dfs, bfs, dfs, bfs,d f s , b f s , and check set.

class Solution {
    
    
public:
    vector<int> f;

    int father(int x)
    {
    
    
        return f[x]==x?x:f[x]=father(f[x]);
    }

    int makeConnected(int n, vector<vector<int>>& connections) {
    
    
        if(connections.size()<n-1)
            return -1;
        f.resize(n);
        for(int i=0;i<n;i++)
            f[i]=i;
        int ans=n;
        for(vector<int>& each:connections)
        {
    
    
            int fx=father(each[0]);
            int fy=father(each[1]);
            if(fx!=fy)
                f[fx]=fy,--ans;
        }
        return ans-1;
    }
};

Guess you like

Origin blog.csdn.net/xiji333/article/details/113065127