leetcode684+删除树中构成图的多余边,并查集

https://leetcode.com/problems/redundant-connection/description/

class Solution {
public:
    int find(int a, int p[])
    {
        int res = a;
        while(res!=p[res]){
            res = p[res];
        }
        return res;
    }
    vector findRedundantConnection(vector>& edges) {
        int parent[edges.size()+1];
        for(int i=1; i<=edges.size(); i++){
            parent[i] = i;
        }
        for(auto e:edges){
            if(find(e[0],parent)==find(e[1], parent))//在一个集合里面了,说明有圈了
                return e;
            parent[find(e[1], parent)] = find(e[0], parent);
        }
    }
};

你可能感兴趣的:(Leetcode)