684. 冗余连接 并查集

在本问题中, 树指的是一个连通且无环的无向图。

输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。

结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。

返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。

示例 1:

输入: [[1,2], [1,3], [2,3]]
输出: [2,3]
解释: 给定的无向图为:
1
/
2 - 3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/redundant-connection
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public:

    unordered_map <int, int> fa;
    unordered_map <int, int> rank;

    int find(int x) {
        if (!fa.count(x)) {
            fa[x] = x;
            rank[x] = 1;
        }
        return fa[x] == x ? fa[x] : find(fa[x]);
    }

    bool same(int x, int y) {
        return find(x) == find(y);
    }

    void unit(int x, int y) {
        int xx = find(x);
        int yy = find(y);
        if (rank[x] < rank[y]) {
            swap(x, y);
        }
        rank[xx] += rank[yy];
        fa[yy] = xx;
    }


    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        
        for (auto edge : edges) {
            int u = edge[0];
            int v = edge[1];
            if (!same(u, v)) {
                unit(u, v);
            }
            else {
                return edge;
            }
        }

        return vector <int>{} ;
    }
};
posted @ 2021-01-20 09:53  _西瓜不甜  阅读(67)  评论(0编辑  收藏  举报