TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › The Greedy Algorithm on Weighted Matroids

The Greedy Algorithm on Weighted Matroids

Give every element of a matroid a positive weight and ask for an independent set of maximum total weight. The obvious greedy algorithm, "consider the elements from heaviest to lightest and keep each one that does not destroy independence", solves this problem on every matroid. One theorem therefore proves Kruskal's minimum-spanning-tree algorithm, the maximum-weight basis of a set of vectors, the scheduling algorithm of the next lesson, and more. This lesson states the theorem, sketches its proof with the exchange axiom, runs the generic algorithm on three matroids, and shows it failing on a structure that is not one.

The problem and the algorithm

A weighted matroid is a matroid M=(S,I)M = (S, \mathcal{I}) with a weight w(x)>0w(x) > 0 for each x∈Sx \in S; the weight of a set is w(A)=∑x∈Aw(x)w(A) = \sum_{x \in A} w(x). Find an independent set of maximum weight. Because weights are positive, adding an element never hurts, so a maximum-weight independent set is always a basis (a maximal independent set); such a set is called an optimal subset.

text
GREEDY(M, w)                        // the matroid is given by an independence oracle
1  A = empty set
2  sort S into decreasing order of weight
3  for each x in S, in that order
4      if A union {x} is independent
5          A = A union {x}
6  return A

If the oracle in line 4 takes time f(n)f(n), the algorithm takes O(nlg⁡n+nf(n))O(n \lg n + n f(n)).

The theorem

Theorem (Rado 1957, Edmonds 1971). For every weighted matroid, GREEDY returns an optimal subset.

The proof follows the two-property recipe of The Greedy-Choice Property and Exchange Arguments.

Lemma 1 (greedy choice). Let xx be the heaviest element of SS such that {x}\{x\} is independent. Then some optimal subset contains xx.

Proof sketch. Take an optimal subset BB without xx. Every element yy of BB has w(y)≤w(x)w(y) \le w(x), since {y}\{y\} is independent (hereditary property) and xx was the heaviest such element. Start from A={x}A = \{x\} and use the exchange property repeatedly to grow AA with elements of BB until ∣A∣=∣B∣\lvert A \rvert = \lvert B \rvert. Then A=(B∖{y})∪{x}A = (B \setminus \{y\}) \cup \{x\} for exactly one y∈By \in B, so w(A)=w(B)−w(y)+w(x)≥w(B)w(A) = w(B) - w(y) + w(x) \ge w(B). Hence AA is optimal and contains xx. ■\blacksquare

Lemma 2 (elements that do not fit now never fit later). If {x}\{x\} is not independent, then no independent set contains xx, by the hereditary property; more generally, if A∪{x}A \cup \{x\} is not independent, then A′∪{x}A' \cup \{x\} is not independent for any A′⊇AA' \supseteq A. So skipping an element is never a mistake that could be regretted later.

Lemma 3 (optimal substructure). After choosing xx, the remaining problem is again a weighted matroid: the contraction M′=(S′,I′)M' = (S', \mathcal{I}') with S′={y∈S∖{x}:{x,y}∈I}S' = \{y \in S \setminus \{x\} : \{x, y\} \in \mathcal{I}\} and I′={B⊆S′:B∪{x}∈I}\mathcal{I}' = \{B \subseteq S' : B \cup \{x\} \in \mathcal{I}\}. One checks that M′M' satisfies both axioms, and that A′A' is optimal for M′M' exactly when A′∪{x}A' \cup \{x\} is optimal among the independent sets of MM that contain xx. The rest of GREEDY's run is exactly GREEDY on M′M'.

Induction on ∣S∣\lvert S \rvert combines the three: the first element GREEDY takes is safe by Lemma 1, the skipped elements before it are harmless by Lemma 2, and the rest of the run solves the contracted matroid optimally by Lemma 3 and induction. ■\blacksquare

There is also a converse, due to Gale and Edmonds: if (S,I)(S, \mathcal{I}) is hereditary and GREEDY finds a maximum-weight independent set for every choice of weights, then (S,I)(S, \mathcal{I}) is a matroid. So matroids are exactly the structures on which this greedy algorithm is always correct.

One algorithm, three problems

The program implements GREEDY once, with the independence test passed in as a function, and runs it on three matroids: the graphic matroid of a weighted graph (giving a maximum spanning tree), a linear matroid over GF(2)\mathrm{GF}(2) (a maximum-weight basis of bit vectors), and a uniform matroid (the kk heaviest elements). Brute force confirms each answer.

python · try it yourself
from itertools import combinations

def greedy(S, w, independent):
    A = []
    for x in sorted(S, key=w, reverse=True):
        if independent(A + [x]):
            A.append(x)
    return A

def brute_force(S, w, independent):
    best = max((c for k in range(len(S) + 1) for c in combinations(S, k) if independent(list(c))),
               key=lambda c: sum(w(x) for x in c))
    return sum(w(x) for x in best)

# 1. graphic matroid: edges (u, v, weight) of a graph on vertices 0..4
edges = [(0, 1, 7), (0, 2, 4), (1, 2, 6), (1, 3, 9), (2, 3, 3), (2, 4, 8), (3, 4, 5), (0, 4, 2)]
def forest(F):
    parent = list(range(5))
    def find(v):
        while parent[v] != v:
            v = parent[v]
        return v
    for u, v, _ in F:
        a, b = find(u), find(v)
        if a == b:
            return False
        parent[a] = b
    return True
T = greedy(edges, lambda e: e[2], forest)
print("max spanning tree:", [(u, v) for u, v, _ in T], "weight", sum(e[2] for e in T),
      "| brute force", brute_force(edges, lambda e: e[2], forest))

# 2. linear matroid over GF(2): bit vectors with weights
vecs = {0b1100: 5, 0b0110: 9, 0b1010: 4, 0b0011: 7, 0b1111: 6, 0b0101: 3}
def lin_indep(V):
    for k in range(1, len(V) + 1):
        for c in combinations(V, k):
            x = 0
            for v in c:
                x ^= v
            if x == 0:
                return False
    return True
B = greedy(list(vecs), vecs.get, lin_indep)
print("max-weight basis:", [format(v, "04b") for v in B], "weight", sum(vecs[v] for v in B),
      "| brute force", brute_force(list(vecs), vecs.get, lin_indep))

# 3. uniform matroid of rank 3: any 3 elements
items = {"a": 4, "b": 11, "c": 7, "d": 2, "e": 9}
U = greedy(list(items), items.get, lambda A: len(A) <= 3)
print("3 heaviest:", U, "weight", sum(items[x] for x in U))
max spanning tree: [(1, 3), (2, 4), (0, 1), (1, 2)] weight 30 | brute force 30
max-weight basis: ['0110', '0011', '1111'] weight 22 | brute force 22
3 heaviest: ['b', 'e', 'c'] weight 27

On the graph, GREEDY is Kruskal's algorithm with the order reversed: take edges from heaviest to lightest and skip any edge that closes a cycle. A minimum spanning tree comes from the same theorem by a trick: replace each weight w(e)w(e) by w0−w(e)w_0 - w(e) for a constant w0w_0 larger than every weight. All spanning trees have the same number of edges, so maximising the new total is the same as minimising the old one, and "heaviest new weight first" means "lightest original weight first", which is Kruskal as usually stated.

Greedy fails off matroids

Matchings are not a matroid (Matroids), so the theorem promises nothing for them, and indeed greedy can be fooled by a heavy edge that blocks two others:

python · try it yourself
from itertools import combinations

def greedy(S, w, independent):
    A = []
    for x in sorted(S, key=w, reverse=True):
        if independent(A + [x]):
            A.append(x)
    return A

edges = {("a", "b"): 3, ("b", "c"): 4, ("c", "d"): 3}          # the path a-b-c-d
matching = lambda F: len({v for e in F for v in e}) == 2 * len(F)
G = greedy(list(edges), edges.get, matching)
best = max((c for k in range(4) for c in combinations(edges, k) if matching(list(c))),
           key=lambda c: sum(edges[e] for e in c))
print("greedy matching:", G, "weight", sum(edges[e] for e in G))
print("best matching:  ", list(best), "weight", sum(edges[e] for e in best))
greedy matching: [('b', 'c')] weight 4
best matching:   [('a', 'b'), ('c', 'd')] weight 6

The heaviest edge bcbc (weight 4) blocks both others, worth 3+3=63 + 3 = 6 together. For matchings, greedy is only a 2-approximation: every edge of an optimal matching shares an endpoint with a greedy edge at least as heavy, and each greedy edge can block at most two optimal edges. Getting the exact optimum needs augmenting paths or LP duality (Linear Programming & Duality for Algorithms).

In C++

Kruskal's algorithm for a minimum spanning tree, written as the generic greedy with a union-find oracle: sort by increasing weight, keep an edge if its endpoints are in different trees.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <vector>

struct Edge { int u, v, w; };

int find(std::vector<int>& p, int x) { return p[x] == x ? x : p[x] = find(p, p[x]); }

int main() {
    std::vector<Edge> edges = {{0, 1, 7}, {0, 2, 4}, {1, 2, 6}, {1, 3, 9}, {2, 3, 3}, {2, 4, 8}, {3, 4, 5}, {0, 4, 2}};
    std::sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });
    std::vector<int> parent(5);
    std::iota(parent.begin(), parent.end(), 0);
    int total = 0;
    std::printf("minimum spanning tree:");
    for (const auto& e : edges) {
        int a = find(parent, e.u), b = find(parent, e.v);
        if (a != b) {                       // the independence oracle: no cycle
            parent[a] = b;
            total += e.w;
            std::printf(" %d-%d(%d)", e.u, e.v, e.w);
        }
    }
    std::printf("\ntotal weight %d\n", total);
}
minimum spanning tree: 0-4(2) 2-3(3) 0-2(4) 1-2(6)
total weight 15

Kruskal's algorithm and its running time O(Elg⁡E)O(E \lg E) are treated in full in Graph Algorithms; the matroid view explains why it works.

Test yourself

Why is the optimal subset of a weighted matroid with positive weights always a basis?

  1. Because greedy only returns bases
  2. Because adding any element that keeps the set independent increases the weight
  3. Because all independent sets have the same weight
  4. Because bases are unique

In the proof that the greedy choice is safe, which matroid axiom builds the set AA from {x}\{x\} and elements of BB?

  1. The hereditary property
  2. The exchange property
  3. Optimal substructure
  4. Submodularity

How do you get a minimum spanning tree from the maximum-weight greedy algorithm?

  1. Run it with negative weights
  2. Replace each weight w(e)w(e) by w0−w(e)w_0 - w(e) with w0w_0 above every weight, since all spanning trees have the same number of edges
  3. Take the edges greedy rejects
  4. It is impossible