← All problemsFree · Python · 50 min

Algorithm design / guarantees under an adversary

The Merging Clubs

Build the tallest trees that naive linking and union by size allow, then write a union-find that stays within a few cell reads and writes per operation on sequences built to break the simpler versions.

0 / 3 graded parts passSaved in this browser · loading saved work…
Jump to your work ↓

A city's clubs keep merging, and anyone may ask whether two people are now in the same club. A union-find structure keeps each club as a tree of parent pointers: find(x) follows the pointers from x up to the root, and union(a, b) links one root under the other. A find costs one step per pointer it follows, so tall trees are slow.

naive linking, after union(0, 1), union(2, 3), union(0, 2)0123find(0) follows 2 pointersstill alone:456789101112131415
Three naive unions on 16 elements, and the pointers one find follows.

The two linking rules in parts A and B, for union(a, b) with roots ra of a and rb of b:

  • Naive: ra becomes a child of rb.
  • By size: the root of the smaller tree becomes a child of the other's root; on a tie, ra goes under rb.

A tree's height is the most parent steps from any element to its root. In parts A and B there are 16 elements, 0 to 15, and each union is written as two numbers, a b, one per line.

Part C's cost

Your structure keeps everything in two lists the grader gives you, parent and rank, of n cells each. Every read and every write of a cell costs 1. The grader runs four sequences of up to 24,096 operations on n=4096, built to hurt structures that skip one of the standard ideas. Each sequence's total must stay within 8×(operations+n). Every find is checked: it must return an element of the right club, and the same one for the whole club until the next union. Every 97 operations the grader also compares two elements' clubs; those extra finds are not charged to you.

Background: Union-Find.

easy · Part A

The tallest naive tree

With naive linking, give unions on 16 elements that build a tree as tall as possible.

Explore in the sandbox

Experiment here, then copy a rule into the editor and test its guarantees.