原题目:https://leetcode-cn.com/problems/redundant-connection/
思路:
并查集,每次检查边的两个顶点是否属于同一个集合,如果是,则返回(形成了环)。如果不是,将这两个顶点并入到一个集合之中,依次检查所有的边。
可以同时考虑路径压缩,每次合并的时候都合并到size大的节点。
代码:
class UnionFind{
private:
vector parent;
vector size;
int count;
public:
UnionFind(vector>& M){
int n = M.size();
parent.resize(n + 1);
size.resize(n + 1);
count = n;
for(int i = 1; i < n + 1; i++){
parent[i] = i;
size[i] = 1;
}
}
int find(int p){
while(p != parent[p]){
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
void connect(int rootp, int rootq){
if(size[rootp] < size[rootq]){
parent[rootp] = rootq;
size[rootq] += size[rootp];
}
else{
parent[rootq] = rootp;
size[rootp] += size[rootq];
}
count--;
}
int getcount(){
return count;
}
};
class Solution {
public:
vector findRedundantConnection(vector>& edges) {
int n = edges.size();
UnionFind uf(edges);
for(int i = 0; i < n; i++){
int rootp = uf.find(edges[i][0]);
int rootq = uf.find(edges[i][1]);
if(rootp == rootq) return edges[i];
uf.connect(rootp, rootq);
}
return {};
}
};