Detect if a graph is bipartite using union find (aka disjoint sets)

孤人 提交于 2019-12-20 07:48:47

问题


I'm doing a problem on Spoj that basically reduces to detecting if a graph is bipartite. I'm trying to just color the graph using dfs, but it is too slow. Some guy comments this

No bfs, no dfs, no bipartie graph. Simple Union-Find Set would make it (with speed, indeed). Hint #1: Cycle of even length does not affect the divisibility by 2 ( wow, so many i in a word ) of length of paths between two node. Hint #2: (SPOILER) let dist[i] be the distance of a path from i to parent[i]. update it with the find and union function. It can be improved to make dist a bool array.

Could someone explain what he means with this? I think what he is trying to say is that for each node, you store the distance between the node and the representative element. Then if you try to merge two nodes in the same set, and if they have the same parity, then you create an odd cycle, so the graph cannot be bipartite. However, I don't understand how this would be implemented. How can you merge two sets while accounting for the distance? Wouldn't you have to look through the entire set to find all elements to update?

Link to the problem: https://www.spoj.com/problems/BUGLIFE/


回答1:


Given a graph represented as an adjacency-list (i.e. a list of edges), you can determine if it's bipartite as follows:

  • Initialize a disjoint-set data structure SETS, with a singleton set for each vertex. (If there is an even-length path between two vertices, then we will ultimately unify those two vertices into the same set, unless we return ꜰᴀʟꜱᴇ first.)
  • Initialize a mapping MAP from each vertex to ɴɪʟ. (As we examine edges, we will populate MAP with a mapping from each vertex to one of its neighbors.)
  • For each edge {u, v}:
    • If u and v belong to the same set in SETS, then return ꜰᴀʟꜱᴇ.
    • If MAP[u] = ɴɪʟ, set MAP[u] := v.
      Otherwise, update SETS to unify v with MAP[u].
    • If MAP[v] = ɴɪʟ, set MAP[v] := u.
      Otherwise, update SETS to unify u with MAP[v].
  • Return ᴛʀᴜᴇ.


来源:https://stackoverflow.com/questions/53246453/detect-if-a-graph-is-bipartite-using-union-find-aka-disjoint-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!