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:
Otherwise, update SETS to unify v with MAP[u].
Otherwise, update SETS to unify u with MAP[v].