其他分享
首页 > 其他分享> > 并查集题集1 & dfs & bfs & unionMerge & 二分图

并查集题集1 & dfs & bfs & unionMerge & 二分图

作者:互联网

0 一些基础

判断整个图是否连通

使用dfs判断整个图是否连通:

        // if not connected, return false
        vecctor<int> stack = {0};
        vector<bool> vis(graph.size(), false);
        vis[0] = true;
        int visCnt = 1;
        // dfs to check if connected
        while(!stack.empty()) {
            int top = stack.back();
            bool allVisited = true;
            for(int i = 0; i < graph[top].size(); ++i) {
                if(!vis[graph[top][i]]) {
                    stack.emplace_back(graph[top][i]);
                    vis[graph[top][i]] = true;
                    allVisited = false;
                    visCnt++;
                    break;
                }
            }
            if(allVisited) {
                stack.pop_back();
            }
        }

        if(visCnt != n) return false;

使用bfs也是可以的,比如下面的0684-冗余链接

并查集的使用

主要是将有关联的边聚合到同一个root里去,可以压缩路径加速find过程

    int find(vector<int>& parent, int curNode) {
        while(parent[curNode] != curNode) {
            parent[curNode] = parent[parent[curNode]];
            curNode = parent[curNode];
        }
        return curNode;
    }

    void unionMerge(vector<int>& parent, int from, int to) {
        int x = find(parent, from);
        int y = find(parent, to);
        
        if(x != y) {
            parent[x] = y;
        }
    }

二分图判断

实例讲解

0785 是否二分图

1 题目

https://leetcode-cn.com/problems/is-graph-bipartite/

2 解题思路

class Solution {
public:
    bool isBipartite(vector<vector<int>>& graph) {
        int n = graph.size();
        
        int edgeNum = 0;
        for(int u = 0; u < n; ++u) {
            for(int v = 0; v < graph[u].size(); ++v) {
                ++edgeNum;
            }
        }
        if(edgeNum == 0) return true;

        // if not connected, return false
        vector<int> stack = {0};
        // vector<bool> vis(graph.size(), false);
        // vis[0] = true;
        // int visCnt = 1;
        // // dfs to check if connected
        // while(!stack.empty()) {
        //     int top = stack.back();
        //     bool allVisited = true;
        //     for(int i = 0; i < graph[top].size(); ++i) {
        //         if(!vis[graph[top][i]]) {
        //             stack.emplace_back(graph[top][i]);
        //             vis[graph[top][i]] = true;
        //             allVisited = false;
        //             visCnt++;
        //             break;
        //         }
        //     }
        //     if(allVisited) {
        //         stack.pop_back();
        //     }
        // }

        // if(visCnt != n) return false;

        // bfs to judge biPartitable
        deque<int> q = {};


        vector<bool> vis2(graph.size(), false);
            unordered_set<int> biPart1 = {};
            unordered_set<int> biPart2;
            deque<int> level = {};
        int bfsNum = 0;
        
        while(bfsNum != n) {        

            for(int i = 0; i < n; ++i) {
                if(!vis2[i]) {
                    q.emplace_back(i);
                    level.emplace_back(0);
                    biPart1.insert(i);
                    ++bfsNum;
                    vis2[i] = true;
                    break;
                }
            }
            while(!q.empty()) {
                int front = q.front();
                for(int i = 0; i < graph[front].size(); ++i) {
                    if(!vis2[graph[front][i]]) {
                        q.emplace_back(graph[front][i]);
                        ++bfsNum;
                        level.emplace_back(level.front() + 1);
                        if(level.front() % 2 == 0) {
                            biPart2.insert(graph[front][i]);
                        } else {
                            biPart1.insert(graph[front][i]);
                        }
                        vis2[graph[front][i]] = true;          
                    }
                }
                q.pop_front();
                level.pop_front();
            }
            // for(auto& i : biPart1) {
            //     std::cout << i << " ";
            // }
            // cout << endl;
            // for(auto& i : biPart2) {
            //     std::cout << i << " ";
            // }
            // cout << endl;
            
            for(int u = 0; u < n; ++u) {
                for(int v = 0; v < graph[u].size(); ++v) {
                    if((biPart2.count(u) == 1 && biPart2.count(graph[u][v]) == 1) || \
                    (biPart1.count(u) == 1 && biPart1.count(graph[u][v]) == 1)) {
                        return false;
                    }
                }
            }
        }


        return true;
    }
}

0765minSwapsCouple

1 题目

https://leetcode-cn.com/problems/couples-holding-hands/

2 解题思路

容易被迷惑的地方: 一次交换至少能够完成一对情侣,只有最后的一次交换能够完成两队情侣,其余均只能完成一次
所以说这个最小交换次数,其实别反复换,算出来的就是最小的

class Solution {
public:
    int minSwapsCouples(vector<int>& row) {
        // 容易被迷惑的地方: 一次交换至少能够完成一对情侣,只有最后的一次交换能够完成两队情侣,其余均只能完成一次
        // 所以说这个最小交换次数,其实别反复换,算出来的就是最小的
        
        // 首先注意到,将2个情侣看成一个节点,如果不属于一对的情侣坐在2k - 2, 2k - 1的两个位置上,则连一条线
        vector<int> parent(row.size() / 2);
        for(int i = 0; i < row.size() / 2; ++i) {
            parent[i] = i;
        }

        for(int i = 0; i < row.size(); i += 2) {
            int nodeIdx = i / 2;
            unionMerge(parent, row[i] / 2, row[i + 1] / 2);
            // std::cout << row[i] / 2<< " -> " << row[i + 1] / 2 << std::endl;
        }

        // 找出上图所有连通子图, 所有连通子图的边的节点个数减去1得到一个子图所有情侣相邻而坐需要的交换次数
        unordered_map<int, int> rootIdxToCnt;
        for(int i = 0; i < row.size() / 2; ++i) {
            rootIdxToCnt[find(parent, i)] ++;
            // std::cout << i << " -> " << find(parent, i) << std::endl;
        }

        int res = 0;
        for(auto& it : rootIdxToCnt) {
            res += it.second - 1;
        }
        return res;

    }

    int find(vector<int>& parent, int curNode) {
        while(parent[curNode] != curNode) {
            parent[curNode] = parent[parent[curNode]];
            curNode = parent[curNode];
        }
        return curNode;
    }

    void unionMerge(vector<int>& parent, int from, int to) {
        int x = find(parent, from);
        int y = find(parent, to);
        
        if(x != y) {
            parent[x] = y;
        }
    }
}

0684 冗余链接

1 题目描述

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

2 解题思路

使用并查集,将每一条边都看做一个子树,然后一条边一条边加入这个树,当加入的边的两个顶点属于同一个子树时,就认为有回环,则返回这个冗余边。
见如下代码:

class Solution {
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        tree.resize(edges.size() * 2 + 1, -1);
        subTreeSize.resize(edges.size() * 2 + 1, 1);
        
        vector<int> res;
        for(auto& c : edges) {
            if(!unionMerge(c[0], c[1], tree)) {
                res = c;
                break;
            }
        }
        return res;
    }
    
    int find(int tar, vector<int>& tree) {
        int curFather = tree[tar];
        if (curFather < 0) { // tar has no father, so he is the root
            tree[tar] = tar;
            return tar;
        }
        if(tar != curFather) {
            tree[tar] = find(curFather, tree); // compress the data path
        }
        return tree[tar];
    }
    
    
    bool unionMerge(int x, int y, vector<int>& tree) {
        int fx = find(x, tree);
        int fy = find(y, tree);
        if(fx == fy) {
            return false; // x, y are in the same tree, need no merge
        }
        if(subTreeSize[fx] >= subTreeSize[fy]){ // merge by rank of the sub Tree
            tree[fy] = fx;
            subTreeSize[fx] += subTreeSize[fy];
        } else {
            tree[fx] = fy;
            subTreeSize[fy] += subTreeSize[fx];
        }
        return true;
    }
    
    vector<int> subTreeSize;
    vector<int> tree;
};

标签:return,并查,parent,集题,graph,dfs,int,vector,curNode
来源: https://blog.csdn.net/cxy_hust/article/details/121619862