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/
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