zoukankan      html  css  js  c++  java
  • 并查集总结

    并查集基本操作:

    union + find

    解法1: 并查集

    class Solution {
    public:
        /**
         * @param n: An integer
         * @param edges: a list of undirected edges
         * @return: true if it's a valid tree, or false
         */
        bool validTree(int n, vector<vector<int>> &edges) {
            // write your code here
            //union find
            vector<int> parent(n, -1);
            for(int i=0; i<edges.size(); i++){
                //union
                int p1 = find(edges[i][0], parent);
                int p2 = find(edges[i][1], parent);
                if(p1 == p2)
                    return false;   //存在环
                parent[p2] = p1;
            }
            return edges.size() == n-1;  //树中若有n个点,则一定有n-1条边
        }
        
        //find
        int find(int e, vector<int> p){
            if(p[e] == -1)
                return e;
            else
                return p[e] = find(p[e], p);
        }
    };

    解法二: BFS

  • 相关阅读:
    hdu-4638
    一个简单的询问
    CoderForces-617B
    HYSBZ-2002弹飞绵羊
    邻接表
    CoderForces-913-C
    CoderForces-913D
    CoderFocers-620C
    CoderForces-375D
    HDU-6119
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11387028.html
Copyright © 2011-2022 走看看