Four problems rated 1,600 to 1,800 that look like they need to split, undo or rebuild groups. The move: union find only joins, so turn the question into joins.
This tent holds four problems rated 1,600 to 1,800. All four are about groups of connected nodes, and union find is the right tool. But union find only joins groups. Each statement asks for something else: remove a link, find the cheapest joins, undo a join, or let links come and go.
The literal answer rebuilds the groups from scratch each time. It is correct, and it is slow.
| Problem | The literal route | Its size at the limits |
|---|---|---|
| Network pieces after each outage | rebuild the groups after every cut | 1.5 × 10^10 steps |
| Joining the pickup zones with new lanes | scan every lane for the cheapest join, each time | 2 × 10^10 steps |
| Group merges with an undo button | rebuild after every undo | 10^10 steps |
| Relay links that come and go | rebuild at every question | 10^8 joins and finds |
The last row looks small, but every join is a find, and 10^8 of them is far from safe in Python.
Exercise · Predict the output: The pieces after each cut. A path of 5 nodes has the links 0-1, 1-2, 2-3 and 3-4. They are cut in the order 1, 3, 0. This runs the log backwards: it joins the link that is never cut, then puts the cuts back from the last to the first. What does it print?
links = [[0, 1], [1, 2], [2, 3], [3, 4]]
parent = list(range(5))
pieces = 5
answers = [0, 0, 0]
joins = [2, 0, 3, 1]
for k, e in enumerate(joins):
if k > 0:
answers[3 - k] = pieces
a, b = links[e]
while parent[a] != a:
a = parent[a]
while parent[b] != b:
b = parent[b]
if a != b:
parent[a] = b
pieces -= 1
print(*answers)Union find has one operation that matters, the join. So change the question until it only needs joins. There are three ways, one for each kind of problem.
If a problem removes, ranks or undoes, rewrite it as joins: run time backwards, sort the lanes by cost, or undo the last join from a stack.
Removals become additions. Read the whole log first. The state after the last removal is the set of links never cut, so join them. Then walk the log backwards: each removal becomes an addition, and the count before it is the answer for that moment.
Cheapest connection is a sort. Sort the lanes by cost and walk them once. Take a lane only when its ends are in different groups, because a lane inside one group adds cost and no connection. Lanes that already exist cost nothing, so join them before the sort.
Undo is a stack. Record what each join changed, and put it back when asked. That works only when a join changes very little, which is the next section's subject.
Removals become additions: join the links never cut, then put the cuts back from the last to the first, noting the count before each.
Exercise · Find the bug: The link that joins the wrong nodes. This returns the number of groups after joining every pair. Which line is wrong?
def count_groups(n, pairs):
parent = list(range(n))
groups = n
for a, b in pairs:
ra = a
while parent[ra] != ra:
ra = parent[ra]
rb = b
while parent[rb] != rb:
rb = parent[rb]
if ra != rb:
parent[a] = b
groups -= 1
return groupsThe Academy lessons Union find and Greedy by sorting taught the structure and the sort-then-take idea. Cycles and bipartite showed a join inside one group as a cycle, and Graph traversal gave the other way to find groups. This tent asks the structure to split and undo, which it was not built for.
Undo needs a union find that changes little. Join the smaller group under the larger, and never compress paths. A join then changes exactly one parent entry and one size, so a stack of the moved roots can undo it.
Joining by size keeps every find short. For 10^5 nodes a find walks at most 16 links, and merging 65,536 single nodes pair by pair reaches exactly 16.
Links that come and go over time need one more step. Each link is up for an interval of time, so store it on the few nodes of a segment tree over time that cover the interval. Then walk the tree: entering a node joins its links, and leaving it undoes them. A question at time t is answered at leaf t.
The last trap is the lane problem: a connection problem has an answer only when everything ends in one group.
A connection problem has an answer only when one group is left; otherwise the answer is minus one, not the cost collected.
Exercise · Break it: The network that cannot be joined. Zones are numbered from 0, and each lane is [zone, zone, cost]. This returns the least total cost that joins all the zones. It takes the cheapest lane that joins two groups, until the lanes run out. Find an input where it is wrong.
def join_cost(n, lanes):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
total = 0
for a, b, cost in sorted(lanes, key=lambda lane: lane[2]):
ra = find(a)
rb = find(b)
if ra != rb:
parent[ra] = rb
total += cost
return total| Limit | What it tells you |
|---|---|
| 5 × 10^4 nodes, 10^5 links | a count after every cut: write the answers once, at the end |
| 2 × 10^5 lanes, cost up to 10^6 | totals reach 2 × 10^11: 64-bit integers |
| 10^5 operations with undo | a find of at most 16 links: join by size, no compression |
| 10^4 nodes, 10^4 events | a segment tree over time, with a log factor on top of each join |
| nodes numbered from 1 | subtract 1 on input, or size every table by n + 1 |
The full treatment is in Fast I/O and stress testing. Here the input has two lists, the links and then the cuts, and the numbers count from 1. Convert them once, as they are read.
import sys
def main():
data = sys.stdin.buffer.read().split()
n, m = int(data[0]), int(data[1])
links = [(int(data[2 + 2 * i]) - 1, int(data[3 + 2 * i]) - 1) for i in range(m)]
k = int(data[2 + 2 * m])
cuts = [int(x) - 1 for x in data[3 + 2 * m:3 + 2 * m + k]]
cut = [False] * m
for c in cuts:
cut[c] = True
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
pieces = n
for i in range(m):
if not cut[i]:
a, b = find(links[i][0]), find(links[i][1])
if a != b:
parent[a] = b
pieces -= 1
answers = [0] * k
for i in range(k - 1, -1, -1):
answers[i] = pieces
a, b = find(links[cuts[i]][0]), find(links[cuts[i]][1])
if a != b:
parent[a] = b
pieces -= 1
sys.stdout.write(" ".join(map(str, answers)) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
static int[] parent;
static int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int m = (int) in.nval;
int[] ea = new int[m], eb = new int[m];
for (int i = 0; i < m; i++) {
in.nextToken();
ea[i] = (int) in.nval - 1;
in.nextToken();
eb[i] = (int) in.nval - 1;
}
in.nextToken();
int k = (int) in.nval;
int[] cuts = new int[k];
boolean[] cut = new boolean[m];
for (int i = 0; i < k; i++) {
in.nextToken();
cuts[i] = (int) in.nval - 1;
cut[cuts[i]] = true;
}
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
int pieces = n;
for (int i = 0; i < m; i++) {
if (!cut[i]) {
int a = find(ea[i]), b = find(eb[i]);
if (a != b) { parent[a] = b; pieces--; }
}
}
int[] answers = new int[k];
for (int i = k - 1; i >= 0; i--) {
answers[i] = pieces;
int a = find(ea[cuts[i]]), b = find(eb[cuts[i]]);
if (a != b) { parent[a] = b; pieces--; }
}
StringBuilder out = new StringBuilder();
for (int i = 0; i < k; i++) out.append(answers[i]).append(i + 1 < k ? " " : "\n");
System.out.print(out);
}
}#include <iostream>
#include <vector>
using namespace std;
vector<int> parent;
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> ea(m), eb(m);
for (int i = 0; i < m; i++) {
cin >> ea[i] >> eb[i];
ea[i]--;
eb[i]--;
}
int k;
cin >> k;
vector<int> cuts(k);
vector<bool> cut(m, false);
for (int i = 0; i < k; i++) {
cin >> cuts[i];
cuts[i]--;
cut[cuts[i]] = true;
}
parent.resize(n);
for (int i = 0; i < n; i++) parent[i] = i;
int pieces = n;
for (int i = 0; i < m; i++) {
if (!cut[i]) {
int a = find(ea[i]), b = find(eb[i]);
if (a != b) { parent[a] = b; pieces--; }
}
}
vector<int> answers(k);
for (int i = k - 1; i >= 0; i--) {
answers[i] = pieces;
int a = find(ea[cuts[i]]), b = find(eb[cuts[i]]);
if (a != b) { parent[a] = b; pieces--; }
}
for (int i = 0; i < k; i++) cout << answers[i] << (i + 1 < k ? " " : "\n");
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0], m = data[1];
const ea = [], eb = [];
for (let i = 0; i < m; i++) {
ea.push(data[2 + 2 * i] - 1);
eb.push(data[3 + 2 * i] - 1);
}
const k = data[2 + 2 * m];
const cuts = [];
const cut = new Array(m).fill(false);
for (let i = 0; i < k; i++) {
cuts.push(data[3 + 2 * m + i] - 1);
cut[cuts[i]] = true;
}
const parent = [];
for (let i = 0; i < n; i++) parent.push(i);
function find(x) {
while (parent[x] !== x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
let pieces = n;
for (let i = 0; i < m; i++) {
if (!cut[i]) {
const a = find(ea[i]), b = find(eb[i]);
if (a !== b) { parent[a] = b; pieces--; }
}
}
const answers = new Array(k).fill(0);
for (let i = k - 1; i >= 0; i--) {
answers[i] = pieces;
const a = find(ea[cuts[i]]), b = find(eb[cuts[i]]);
if (a !== b) { parent[a] = b; pieces--; }
}
process.stdout.write(answers.join(" ") + "\n");On the sample 5 4, the links 1 2, 2 3, 3 4, 4 5, then 3 and the cuts 2 4 1, all four programs print 2 3 4.
The slow twin rebuilds the groups from scratch after every cut, with a plain loop over the links that are still up. It is easy to read and takes no clever idea.
import random
from fast import pieces_after_cuts
from slow import pieces_after_cuts as slow_pieces
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 7)
m = rng.randint(0, 8)
links = [[rng.randrange(n), rng.randrange(n)] for _ in range(m)]
cuts = rng.sample(range(m), rng.randint(0, m)) if m else []
if pieces_after_cuts(n, links, cuts) != slow_pieces(n, links, cuts):
print("different at", n, links, cuts)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Record each answer after the link is put back, not before, and the first random input already fails. It gives 4, 4, 5, 5 where the answers are 3, 4, 4, 5.
At 1,600 to 1,800 the structure is known, and the work is the rewrite into joins. Write the rewrite in one line before you code: backwards, sorted, or undo. Aim for about 30 minutes a problem, and keep 10 for the stress test.
The first problem runs time backwards. The second sorts the lanes and joins across groups. The third adds undo with a stack, and the last, rated 1,800, adds a segment tree over time on top of the undo.
For each problem, write the rewrite in one line. Then write the slow twin that rebuilds the groups, and stress test on up to 7 nodes.
Checkpoint · Union find for contests
Q1/5 Links are removed one at a time, and you need the group count after each removal. What is the plan?
Answer: B
Union find cannot split a group. Run backwards, each removal is a join, and the count before it is the answer. Rebuilding costs about 1.5 × 10^10 steps at the limits.
Q2/5 Which lanes do you take when you join the zones at the least cost?
Answer: B
A lane inside one group adds cost and no connection. Lanes that already exist cost nothing, so join them before the sort.
Q3/5 Why does a union find with undo skip path compression?
Answer: B
Without compression a join changes one parent entry and one size. A stack of the moved roots restores them. Joining by size keeps a find at 16 links or fewer for 10^5 nodes.
Q4/5 n = 3, pairs = [[0, 1], [0, 2], [1, 2]]. A join sets parent[a] = b instead of parent[root of a] = root of b. What does it count as the final number of groups?
Answer: C
The second join cuts the old link of node 0 and leaves node 1 alone. The third pair then counts a join that never happens, so the count reaches 0. The true answer is 1.
Q5/5 What does a rating of 1,600 to 1,800 usually ask of you?
Answer: B
The structure here is union find. The work is the rewrite: backwards, sorted, or undo.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.