在线动画手机网站模板下载,苏州百度推广排名,郑州网球公开赛,网站设计怎么做题目描述 题目分析
ps#xff1a;这篇博客是补前天的#xff0c;前天在老家不方便写博客 题目挺简单的#xff0c;但是通过题目对图的连通性有了一个更深刻的认识#xff1a;如果有超过#xff08;或等于#xff09;n-1条边#xff0c;则一定是可以让整个图联通的。 如…题目描述 题目分析
ps这篇博客是补前天的前天在老家不方便写博客 题目挺简单的但是通过题目对图的连通性有了一个更深刻的认识如果有超过或等于n-1条边则一定是可以让整个图联通的。 如果想让整个图联通只需要求出整个图的联通分量个数然后-1就是需要的边的个数即让这写联通分量联通即可
AC代码
class UnionFind {
public:vectorint father;vectorint 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, vectorvectorint 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;}
};