Offline connectivity with union-find
Updated
If all edges are known before the questions, apply every union first, then answer each query with find. If a query asks about a prefix of edges, add those unions in order then query.
What to focus on
Offline means the full request list is in hand. Do not DFS the graph per query. Interleaving unknown future unions is the online case; still process the known prefix with unions.
Worked examples
two pairs
a = [0, 1, 2, 3], edges (0,1)(2,3), then query(0,1) and query(0,2)- union both edges first
- find 0=0 find 1=0
- find 0=0 find 2=2
Result: parent=[0,0,2,2] · true then false
all linked
a = [0, 1, 2, 3], edges (0,1)(1,2)(2,3), then query(0,3)- three unions
- find 0=0 find 3=0
Result: parent=[0,0,0,0] · true
no edges
a = [0, 1, 2], edges none, query(0,1)- parent untouched
- find 0=0 find 1=1
Result: parent=[0,1,2] · false
Try it
Write offline(parent, edges, queries). parent starts as self-parents. edges is the list of undirected pairs to union first. queries is the list of (x, y) pairs to test after those unions. Apply every listed union, then return connected for each query. Edges (0, 1)(2, 3) then queries: parent=[0, 0, 2, 2], 0-1 yes, 0-2 no. Edges (0, 1)(1, 2)(2, 3): 0-3 yes. No edges: 0-1 no.
Vertices are 0..n-1 with n in 3–4. Every edge endpoint is a live index. Queries run after the listed unions.