Approach

This is also a union find problem, but I was wrong in the beginning.

I though we could merge the first two first, and then keep track of the unconncted nodes, and then check if we have enough resource to connect them one by one.

But actually, the unconnected nodes might itself become clustered and we don’t really need to conenct them ony by one. Therefore the correct approach is to merge all of them first, and collect the number of extra edges. Also, we check the number of compoenets comp in the end of merging, and we know that we would need comp-1 more extra edge to merge all the components.

Code

class Solution {
public:
    struct UnionFind {
        UnionFind (int n ) {
            parent.assign(n, 0);
            sz.assign(n, 1);
            for(int i = 0 ; i < n ; ++i) parent[i] = i;
        }
        int GetParent(int a) {
            if(parent[a] != a) parent[a] = GetParent(parent[a]);
            return parent[a];
        }
        bool Merge(int a, int b){
            a = GetParent(a);
            b = GetParent(b);
            if(a == b) return false;
            if(sz[a] < sz[b]) swap(a, b);
            sz[a] += sz[b];
            parent[b] = a;
            return true;
        }
        vector<int> parent;
        vector<int> sz;
    };

    int makeConnected(int n, vector<vector<int>>& connections) {
        UnionFind uf(n);

        int extra = 0;
        for(int i = 0 ; i < connections.size() ; ++i) {
            int u = connections[i][0];
            int v = connections[i][1];
            if(!uf.Merge(u, v)) ++extra;
        }
        int comp = 0;
        for(int i = 0 ; i < n ; ++i) {
            if(uf.GetParent(i) == i) ++comp;
        }
        
        return extra >= comp-1 ? comp-1 : -1;
    }

    // int makeConnected(int n, vector<vector<int>>& connections) {
    //     UnionFind uf(n);
    //     int head = connections[0][0];
    //     uf.Merge(head, connections[0][1]);
        
    //     int used = 1;
    //     for(int i = 1 ; i < connections.size() ; ++i) {
    //         int u = connections[i][0];
    //         int v = connections[i][1];
    //         if(uf.Merge(u, v)) ++used;
    //         if(uf.sz[uf.GetParent(head)] == n) return 0;
    //     }
    //     if(n - uf.sz[uf.GetParent(head)] <= connections.size() - used) {
    //         return n - uf.sz[uf.GetParent(head)];
    //     }
    //     return -1;
    // }
};