写在前面
contest 51 的第三题。这题如果知道并查集,基本上写出来就AC了,关键还是对并查集的理解和熟悉程度。
题目描述
We are given a “tree” in the form of a 2D-array, with distinct values for each node.
In the given 2D-array, each element pair [u, v] represents that v is a child of u in the tree.
We can remove exactly one redundant pair in this “tree” to make the result a tree.
You need to find and output such a pair. If there are multiple answers for this question, output the one appearing last in the 2D-array. There is always at least one answer.
Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: Original tree will be like this:
1
/ \
2 - 3
Example 2:
Input: [[1,2], [1,3], [3,1]]
Output: [3,1]
Explanation: Original tree will be like this:
1
/ \
2 3
Note:
The size of the input 2D-array will be between 1 and 1000.
Every integer represented in the 2D-array will be between 1 and 2000.
思路分析
简单讲就是在图中找出多余的边,该边对已存在的结点连通性没有任何影响,即,边上的两个结点已经是连通状态(connected)。这其实跟并查集的定义非常相近,我们只需要不断union未连通的结点,遇到connected的结点,return这条边即可。关于并查集,请仔细阅读这篇博客(并查集介绍),最好能够自己写出并查集代码。
代码实现
AC代码中的并查集实现基本上以上述博客为准,代码中所做的操作就是简单的union和判断是否连通(connected)。
class Solution {
public:
class UF {
private:
vector<int> id;
vector<int> sz;
int c;
public:
UF(int N):c(N) {
for(int i = 0;i<N;++i) {
id.push_back(i);
sz.push_back(1);
}
}
int count(){return c;};
bool connected(int p,int q) {return find(p) == find(q);}
int find(int p) {
while(p!=id[p]) {
id[p] = id[id[p]];
p = id[p];
}
return p;
}
void UN(int p,int q) {
int i = find(p);
int j = find(q);
if(i==j) return;
if(sz[i]<sz[j]) {
id[i] = j;
sz[j] += sz[i];
}
else {
id[j] = i;
sz[i]+=sz[j];
}
c--;
}
};
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
// 并查集
// 第一步 构建并查集
UF uf(2001);
for(auto&val:edges) {
if(uf.connected(val[0]-1,val[1]-1)) return val;
uf.UN(val[0]-1,val[1]-1);
}
return {};
}
};