Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Matroids & the Greedy Algorithm

The structure that makes greedy optimal: the Rado–Edmonds theorem.

Kruskal's algorithm sorts the edges by weight and keeps every edge that does not close a cycle. Replace "edges" by any elements and "does not close a cycle" by any notion of independence, and you have the greedy algorithm. The Rado–Edmonds theorem says exactly when it is optimal for every choice of weights: precisely when independence obeys one exchange axiom, the defining property of a matroid.

What you’ll learn

  • State the matroid axioms, recognize uniform, partition, graphic and linear matroids, and show that matchings and knapsack sets are not matroids.
  • Prove the Rado–Edmonds theorem in both directions: greedy is optimal for every non-negative weighting exactly on matroids.
  • Model unit-time scheduling with deadlines and penalties as a matroid, and solve it greedily.
  • Explain why the intersection of two matroids, which contains bipartite matching, is polynomial while three is NP-hard.

Independence systems and matroids

MatroidIndependent setsWhat greedy computes
Uniform Uk,nU_{k,n}all subsets of at most kk of the nn elementsthe kk heaviest elements
Partitionat most cjc_j elements from each block SjS_j of a partition of SSthe cjc_j heaviest elements of every block
Graphic (of a graph GG)edge sets that contain no cycle (forests)a maximum-weight spanning forest: Kruskal's algorithm
Linear (of vectors)linearly independent sets of vectorsa maximum-weight basis, for example an XOR basis over GF(2)

Exchange forces all bases to have the same size, the rank: if one basis were smaller, (I3) would extend it. That gives a quick test for non-matroids. In the path a−b−c−da - b - c - d, the matchings {bc}\{bc\} and {ab,cd}\{ab, cd\} are both maximal but have different sizes, so the matchings of a graph do not form a matroid.

Other hereditary families fail the same way: sets of items within a knapsack's weight limit, and sets of pairwise non-adjacent vertices of a graph.

Check your understanding

Which family of subsets is always a matroid?

  1. Sets of items whose total weight is at most a limit WW
  2. Sets of edges of a graph that contain no cycle
  3. Sets of edges of a graph that form a matching
  4. Sets of pairwise non-adjacent vertices of a graph
Show the answer

B. Sets of edges of a graph that contain no cycle

Forests satisfy exchange: a forest with more edges has fewer components, so one of its edges joins two components of the smaller forest and can be added without creating a cycle. This is the graphic matroid.

The greedy algorithm and the Rado–Edmonds theorem

text
GREEDY(S, independence oracle, w):        # weights w(x) >= 0
    A ← ∅
    for x in S, in order of decreasing w(x):
        if A ∪ {x} is independent:
            A ← A ∪ {x}
    return A

O(nlog⁡n)O(n \log n) for the sort plus nn calls to the independence oracle. For a minimum-weight basis, scan in increasing order instead; on the graphic matroid that is Kruskal's algorithm.

DerivationProof
  1. m=km = k

    Matroid ⇒ greedy is optimal. Let greedy pick g1,…,gkg_1, \dots, g_k in this order, so by decreasing weight, and let O={o1,…,om}O = \{o_1, \dots, o_m\} be a maximum-weight independent set sorted by decreasing weight. Since w≥0w \ge 0, OO may be extended to a basis, and all bases have the same size:

  2. w(oj) ≥ w(oi) > w(gi)w(o_j)\ \ge\ w(o_i)\ >\ w(g_i)

    Suppose w(gi)<w(oi)w(g_i) < w(o_i) for a first index ii. Apply (I3) to A={g1,…,gi−1}A = \{g_1, \dots, g_{i-1}\} and B={o1,…,oi}B = \{o_1, \dots, o_i\}: some oj∉Ao_j \notin A with j≤ij \le i keeps AA independent, and

  3. w(G)=∑i=1kw(gi) ≥ ∑i=1kw(oi)=w(O)w(G) = \sum_{i=1}^{k} w(g_i)\ \ge\ \sum_{i=1}^{k} w(o_i) = w(O)

    So greedy examined ojo_j before gig_i, when its set was a subset of AA; by (I2) adding ojo_j was allowed, and greedy would have taken it, contradicting oj∉Ao_j \notin A. Hence w(gi)≥w(oi)w(g_i) \ge w(o_i) for every ii:

  4. w(x)={p+2x∈Ap+1x∈B∖A0otherwisew(x) = \begin{cases} p + 2 & x \in A \\ p + 1 & x \in B \setminus A \\ 0 & \text{otherwise} \end{cases}

    Greedy always optimal ⇒ matroid. Suppose (I3) fails for A,B∈IA, B \in \mathcal I with ∣A∣=p<∣B∣|A| = p < |B|; by (I2), shrink BB to p+1p + 1 elements (it still fails). Choose the weights

  5. w(greedy)=p(p+2)=p2+2p < (p+1)2 ≤ w(B)w(\text{greedy}) = p(p + 2) = p^2 + 2p\ <\ (p + 1)^2\ \le\ w(B)

    Greedy takes all of AA first, then no element of B∖AB \setminus A fits next to AA (nor next to any superset of AA, by (I2)), so it collects only weight 0 afterwards. Every element of BB weighs at least p+1p + 1:

Scheduling with deadlines is a matroid

nn tasks each take one unit of time on a single machine, in slots 1,2,…1, 2, \dots. Task ii has an integer deadline di≥1d_i \ge 1 and a penalty wi≥0w_i \ge 0, paid if it finishes after did_i. Minimize the total penalty. Call a set AA of tasks independent if all of them can finish on time, and let Nt(A)N_t(A) be the number of tasks in AA with deadline at most tt.

DerivationProof
  1. A∈I   ⟺   Nt(A)≤t  for all tA \in \mathcal I\ \iff\ N_t(A) \le t\ \text{ for all } t

    Characterization. On-time tasks with deadline at most tt all run in the first tt slots, so there are at most tt of them. Conversely, if Nt(A)≤tN_t(A) \le t for all tt, the kk-th task in deadline order has deadline at least kk (otherwise Nd(A)≥k>dN_{d}(A) \ge k > d for its deadline dd), so it finishes on time in slot kk:

  2. Nk(B)≤Nk(A),Nt(B)>Nt(A)  for all t>kN_k(B) \le N_k(A),\qquad N_t(B) > N_t(A)\ \text{ for all } t > k

    Exchange. Let A,BA, B be independent with ∣A∣<∣B∣|A| < |B|, and let kk be the largest t≥0t \ge 0 with Nt(B)≤Nt(A)N_t(B) \le N_t(A). It exists since N0=0N_0 = 0, and it lies below the largest deadline, where Nt(B)=∣B∣>∣A∣=Nt(A)N_t(B) = |B| > |A| = N_t(A). Then

  3. Nt(A∪{x})=Nt(A)+1 ≤ Nt(B) ≤ tN_t(A \cup \{x\}) = N_t(A) + 1\ \le\ N_t(B)\ \le\ t

    So BB has more tasks with deadline exactly k+1k + 1 than AA has; pick one, x∈B∖Ax \in B \setminus A. Adding xx to AA changes no count for t≤kt \le k, and for t>kt > k:

Taskabcdef
Deadline did_i212331
Penalty wiw_i403530252010
Six unit-time tasks, already listed by decreasing penalty, which is the order greedy examines them in.
Predict before you look

Run greedy by decreasing penalty on the six tasks in the table. What is the minimum total penalty of the late tasks?

Show the answer

60

Accept a and b. Reject c: with a, b, c three tasks would have deadline at most 2. Accept d. Reject e: four tasks would have deadline at most 3. Reject f: two tasks would have deadline 1. The on-time schedule is b, a, d in slots 1, 2, 3, and the late tasks c, e, f cost 30+20+10=6030 + 20 + 10 = 60. A brute force over all 64 subsets agrees.

python
def independent(tasks):                      # tasks: list of (deadline, penalty)
    ds = sorted(d for d, _ in tasks)
    return all(d >= k for k, d in enumerate(ds, start=1))   # k-th deadline >= k

def min_penalty(tasks):
    chosen = []
    for task in sorted(tasks, key=lambda t: -t[1]):          # largest penalty first
        if independent(chosen + [task]):
            chosen.append(task)                              # can still all be on time
    return sum(p for _, p in tasks) - sum(p for _, p in chosen)

Each independence test sorts, so this version takes O(n2log⁡n)O(n^2 \log n) time. Giving each accepted task the latest free slot at or before its deadline, found with union-find over the slots, does the same in O(nlog⁡n)O(n \log n), dominated by the sort.

Two matroids, three matroids, and beyond

Many problems are the intersection of two matroids: the sets independent in both. In a bipartite graph with sides LL and RR, the edge sets with at most one edge at each vertex of LL form a partition matroid, those with at most one edge at each vertex of RR form another, and the common independent sets are exactly the matchings. The intersection of two matroids is usually not a matroid, and greedy fails on it: the path a−b−c−da - b - c - d is bipartite, and greedy matching gets 3 where 4 is possible.

Three matroids are NP-hard. In a directed graph, take the arcs as SS and intersect the graphic matroid of the underlying undirected graph (no cycles), a partition matroid (in-degree at most 1) and another (out-degree at most 1). Common independent sets are disjoint directed paths, and one with n−1n - 1 arcs is a Hamiltonian path.

Greedoids (Korte & Lovász, 1981) drop heredity instead. Prim's algorithm lives there: the edge sets of trees containing a fixed root are not hereditary (removing a middle edge disconnects the tree), yet the greedy rule "add the lightest edge that keeps a tree" is optimal for them.

Check your understanding

Bipartite matching is the intersection of two partition matroids, and greedy is optimal on each of them. Why does greedy still fail for maximum-weight bipartite matching?

  1. Partition matroids are not really matroids
  2. Greedy is optimal for bipartite matching; it only fails on general graphs
  3. The intersection of two matroids is generally not a matroid, so the Rado–Edmonds theorem does not apply to it
  4. Greedy works if the edges are sorted by increasing weight instead
Show the answer

C. The intersection of two matroids is generally not a matroid, so the Rado–Edmonds theorem does not apply to it

Rado–Edmonds characterizes when greedy works: exactly on matroids. The matchings of a bipartite graph violate exchange (two maximal matchings of sizes 1 and 2 in the path a−b−c−da - b - c - d), so some weighting defeats greedy. Edmonds's intersection algorithm or the Hungarian method is needed.

Key takeaways

  • A matroid is a hereditary family of independent sets with the exchange axiom; uniform, partition, graphic and linear matroids are the standard examples, while matchings, knapsack sets and independent vertex sets are not matroids.
  • Rado–Edmonds: "sort by weight, keep what stays independent" is optimal for every non-negative weighting exactly when the independence system is a matroid. Kruskal is the graphic case.
  • Unit tasks with deadlines: the sets that can run on time form a matroid (Nt(A)≤tN_t(A) \le t for all tt), so greedy by penalty minimizes the total penalty.
  • The intersection of two matroids is polynomial (Edmonds), which covers bipartite matching and König's theorem, but greedy no longer works there; three matroids are NP-hard.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the path a−b−c−da - b - c - d, both {bc}\{bc\} and {ab,cd}\{ab, cd\} are maximal matchings. Which matroid axiom do the matchings of a graph violate?

  1. (I1): the empty set is not a matching
  2. (I2): a subset of a matching need not be a matching
  3. (I3): {bc}\{bc\} is smaller than {ab,cd}\{ab, cd\}, yet neither abab nor cdcd can be added to it
  4. None: matchings form a matroid
Show the answer

C. (I3): {bc}\{bc\} is smaller than {ab,cd}\{ab, cd\}, yet neither abab nor cdcd can be added to it

Matchings are hereditary and include the empty set, but exchange fails, as the two maximal matchings of different sizes show. That is exactly why greedy matching keeps bcbc (weight 3) and misses ab+cdab + cd (weight 4) when w(ab)=w(cd)=2w(ab) = w(cd) = 2 and w(bc)=3w(bc) = 3.

Question 2

In the proof that "greedy is always optimal" implies the exchange axiom, ∣A∣=p|A| = p, ∣B∣=p+1|B| = p + 1, and no element of B∖AB \setminus A can be added to AA. Why do the weights p+2p + 2 on AA and p+1p + 1 on B∖AB \setminus A defeat greedy?

  1. Greedy takes all of AA first, then can add nothing from B∖AB \setminus A, and p(p+2)<(p+1)2≤w(B)p(p + 2) < (p + 1)^2 \le w(B)
  2. Greedy takes BB first and misses AA
  3. Greedy takes AA and then all of B∖AB \setminus A, exceeding the optimum
  4. Greedy's weight is p(p+1)p(p + 1), which is less than w(A)w(A)
Show the answer

A. Greedy takes all of AA first, then can add nothing from B∖AB \setminus A, and p(p+2)<(p+1)2≤w(B)p(p + 2) < (p + 1)^2 \le w(B)

The elements of AA are the heaviest, and every subset of AA is independent, so greedy accepts all of them first. After that, every element of B∖AB \setminus A would make the set dependent, so greedy ends with weight p(p+2)p(p + 2), one less than (p+1)2(p + 1)^2, while BB is independent and weighs at least (p+1)2(p + 1)^2.

Question 3

Unit-time tasks are given by their deadlines. Which set of tasks can all be finished on time on one machine?

  1. Deadlines 1, 1, 3
  2. Deadlines 2, 2, 2
  3. Deadlines 1, 2, 3, 3
  4. Deadlines 2, 3, 3
Show the answer

D. Deadlines 2, 3, 3

A set is schedulable iff, for every tt, at most tt of its tasks have deadline ≤t\le t. For 2, 3, 3: one task by time 2 and three by time 3, fine. Running them in deadline order finishes them at times 1, 2, 3.

Question 4

Why is finding a largest common independent set of three matroids NP-hard, when two matroids are polynomial?

  1. Three matroids have no rank function
  2. A Hamiltonian path in a directed graph is a common independent set of size n−1n - 1 of a graphic matroid and two partition matroids
  3. Greedy is optimal for two matroids but not for three
  4. It is not NP-hard: matroid intersection is polynomial for any number of matroids
Show the answer

B. A Hamiltonian path in a directed graph is a common independent set of size n−1n - 1 of a graphic matroid and two partition matroids

Arcs with no undirected cycle (graphic), in-degree at most 1 (partition) and out-degree at most 1 (partition) form disjoint directed paths; n−1n - 1 such arcs form a single path through every vertex. So deciding whether a common independent set of size n−1n - 1 exists decides Hamiltonian path.

Further reading

  • J. Edmonds, "Matroids and the greedy algorithm," Mathematical Programming 1 (1971), 127–136.
  • D. Gale, "Optimal assignments in an ordered set: an application of matroid theory," Journal of Combinatorial Theory (1968).
  • J. Oxley, Matroid Theory, 2nd ed. (Oxford University Press, 2011).
  • A. Schrijver, Combinatorial Optimization: Polyhedra and Efficiency (Springer, 2003), chapters 40–41.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 3rd ed. (MIT Press, 2009), §16.4–16.5 (removed from the 4th edition).