Intuitive C++ Solution || DSU
Intuition\n Describe your first thoughts on how to solve this problem. \nStandard DSU problem.\n\n# Approach\n Describe your approach to solving the problem. \n
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStandard DSU problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    vector<int> parent;\n    vector<int> rank;\n\n    int find (int x) {\n        if (x == parent[x]) \n            return x;\n\n        return parent[x] = find(parent[x]);\n    }\n\n    void Union (int x, int y) {\n        int x_parent = find(x);\n        int y_parent = find(y);\n\n        if (x_parent == y_parent) \n            return;\n\n        if(rank[x_parent] > rank[y_parent]) {\n            parent[y_parent] = x_parent;\n        } else if(rank[x_parent] < rank[y_parent]) {\n            parent[x_parent] = y_parent;\n        } else {\n            parent[x_parent] = y_parent;\n            rank[y_parent]++;\n        }\n    }\n\n    int makeConnected(int n, vector<vector<int>>& con) {\n        parent.resize(n);\n\t    rank.resize(n, 0);\n        int surplus =0;\n        for (int i=0;i<n;i++){\n            parent[i] =i;\n        }\n        \n        for (auto vec:con){\n            \n            if (find(vec[0]) == find(vec[1])) surplus++;\n            else{\n                Union(vec[0],vec[1]);\n                \n            }\n        }\n        int components = 0;\n        for (int i = 0; i < n; i++) {\n            if (find(i) == i) {\n                components++;\n            }\n        }\n        \n        return (surplus >= components - 1) ? components - 1 : -1;\n    }\n};\n```
['C++']