题目描述
题目分析
ps:这篇博客是补前天的,前天在老家不方便写博客
题目挺简单的,但是通过题目对图的连通性有了一个更深刻的认识:如果有超过(或等于)n-1条边,则一定是可以让整个图联通的。
如果想让整个图联通,只需要求出整个图的联通分量个数,然后-1就是需要的边的个数(即让这写联通分量联通即可)
AC代码
class UnionFind {
public:vector<int> father;vector<int> size;int n;int setCount;UnionFind(int _n):n(_n),setCount(_n),father(_n),size(_n,1) {iota(father.begin(), father.end(), 0);}int root(int x) {return x == father[x] ? x : father[x] = root(father[x]);}bool unite(int x, int y) {x = root(x);y = root(y);if (x == y) {return false;}if (size[x] < size[y]) {swap(x, y);}father[y] = x;size[x] += size[y];--setCount;return true;}bool connected(int x, int y) {return root(x) == root(y);}
};
class Solution {
public:int makeConnected(int n, vector<vector<int>>& connections) {if (connections.size() < n - 1) {return -1;}UnionFind uf(n);for (auto &edge : connections) {uf.unite(edge[0], edge[1]);}return uf.setCount - 1;}
};