Matroids
Each greedy algorithm so far came with its own exchange argument. That raises a natural question: is there a general structure that makes "take the best element that still fits" optimal, so that one proof covers many problems at once? There is, and it has a name, the matroid, introduced by Hassler Whitney in 1935 to capture what linear independence of vectors and acyclicity of edge sets have in common. This lesson defines matroids, works through the main examples, checks the axioms by brute force, and shows a natural structure that is not a matroid. The next lesson proves that greedy is optimal on every weighted matroid.
The definition
A matroid is a pair where is a finite set (the ground set) and is a nonempty family of subsets of , called the independent sets, such that:
- Hereditary property: if and , then . (Subsets of independent sets are independent; in particular .)
- Exchange property: if and , then there is some with .
The exchange property says a smaller independent set can always be grown using an element of a larger one. That single axiom is what makes greedy work.
An independent set is maximal if no element can be added to it. A first consequence of the axioms:
Theorem. All maximal independent sets of a matroid have the same size.
Proof. If and were maximal with , the exchange property would give with independent, so was not maximal.
Maximal independent sets are called bases, and their common size is the rank of the matroid. (For vectors, these are the familiar bases and rank of linear algebra, which is where the names come from.)
Examples
Uniform matroid. any set of elements, all subsets of size at most . Hereditary: obviously. Exchange: if , adding any element of gives a set of size at most .
Graphic matroid. For an undirected graph , take and call a set of edges independent if it contains no cycle, that is, if it forms a forest. Hereditary: removing edges cannot create a cycle. Exchange: a forest with edge set on the vertex set has exactly trees (each edge of a forest joins two trees). If , the forest has fewer trees than , so some tree of contains vertices from two different trees of , and therefore some edge of that tree joins two different trees of . Adding it to creates no cycle. The bases are the spanning forests, and the rank is minus the number of connected components.
Linear matroid. a finite set of vectors, independent sets the linearly independent subsets. The exchange property is the Steinitz exchange lemma from linear algebra.
Partition matroid. split into disjoint groups with capacities ; a set is independent if it takes at most elements from each group , for example "at most two players per club".
Checking the axioms by brute force
For small ground sets the two axioms can simply be tested on every pair of sets. The program does that for the graphic matroid of a small graph, for a set of vectors over (bit vectors with XOR as addition), and for a structure that turns out not to be a matroid.
from itertools import combinations
def is_matroid(S, independent):
family = [frozenset(c) for k in range(len(S) + 1) for c in combinations(S, k) if independent(set(c))]
fam = set(family)
if frozenset() not in fam:
return False, "empty set not independent"
for B in family: # hereditary
for x in B:
if B - {x} not in fam:
return False, f"hereditary fails: {sorted(B)} independent, {sorted(B - {x})} not"
for A in family: # exchange
for B in family:
if len(A) < len(B) and not any(A | {x} in fam for x in B - A):
return False, f"exchange fails: A = {sorted(A)}, B = {sorted(B)}"
sizes = {len(B) for B in family if not any(B | {x} in fam for x in set(S) - B)}
return True, f"{len(family)} independent sets, rank {max(len(B) for B in family)}, maximal sizes {sizes}"
# graphic matroid: edges of a 4-cycle a-b-c-d-a with a chord a-c
edges = ["ab", "bc", "cd", "da", "ac"]
def acyclic(F):
parent = {v: v for v in "abcd"}
def find(v):
while parent[v] != v:
v = parent[v]
return v
for u, v in F:
ru, rv = find(u), find(v)
if ru == rv:
return False
parent[ru] = rv
return True
print("forests of a graph: ", is_matroid(edges, acyclic))
# linear matroid over GF(2): bit vectors, independent = no nonempty subset XORs to 0
vecs = [0b110, 0b011, 0b101, 0b100, 0b111]
def lin_indep(V):
V = list(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
print("vectors over GF(2): ", is_matroid(vecs, lin_indep))
# matchings in the path a-b-c-d: edge sets with no shared endpoint
path = ["ab", "bc", "cd"]
matching = lambda F: len({v for e in F for v in e}) == 2 * len(F)
print("matchings of a path: ", is_matroid(path, matching))forests of a graph: (True, '24 independent sets, rank 3, maximal sizes {3}')
vectors over GF(2): (True, '24 independent sets, rank 3, maximal sizes {3}')
matchings of a path: (False, "exchange fails: A = ['bc'], B = ['ab', 'cd']")
The forests of the 5-edge graph form a matroid of rank 3: every spanning tree of a 4-vertex connected graph has 3 edges. The five bit vectors also form a matroid, of rank 3 (they live in a 3-dimensional space and span it). In the vector example the sets that are not independent are the dependent ones, like , whose XOR is zero.
The exchange proof for forests also gives a formula for the rank: minus the number of connected components. The next program grows spanning forests of random graphs in many random edge orders and compares the sizes it reaches with that formula.
import random
def components(n, edges):
parent = list(range(n))
def find(v):
while parent[v] != v:
parent[v] = parent[parent[v]]
v = parent[v]
return v
count = n
for u, v in edges:
a, b = find(u), find(v)
if a != b:
parent[a] = b; count -= 1
return count
def greedy_forest(n, edges):
"""keep each edge that joins two different trees: a maximal independent set"""
parent = list(range(n))
def find(v):
while parent[v] != v:
v = parent[v]
return v
kept = 0
for u, v in edges:
a, b = find(u), find(v)
if a != b:
parent[a] = b; kept += 1
return kept
rng = random.Random(15)
for trial in range(5):
n = rng.randint(6, 12)
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.25]
sizes = set()
for _ in range(200):
rng.shuffle(edges)
sizes.add(greedy_forest(n, edges))
c = components(n, edges)
print(f"{n:2} vertices, {len(edges):2} edges, {c} component{'s' if c > 1 else ''}: "
f"maximal forests of size {sorted(sizes)}, |V| - components = {n - c}") 7 vertices, 6 edges, 2 components: maximal forests of size [5], |V| - components = 5
10 vertices, 14 edges, 1 component: maximal forests of size [9], |V| - components = 9
11 vertices, 14 edges, 2 components: maximal forests of size [9], |V| - components = 9
7 vertices, 7 edges, 2 components: maximal forests of size [5], |V| - components = 5
11 vertices, 11 edges, 2 components: maximal forests of size [9], |V| - components = 9
Matchings are not a matroid. In the path , the middle edge is a matching and is a larger one, but neither nor can be added to , since both share an endpoint with it. The program finds this failure. As a consequence, both maximal matchings and exist, with different sizes, and the greedy "take the heaviest edge that fits" can get stuck at . Maximum matchings need genuinely different algorithms (augmenting paths, in Graph Algorithms). Bipartite matchings are, however, the intersection of two partition matroids, one per side, which is the starting point of matroid intersection theory.
In C++
The independence oracle of the graphic matroid is a union-find structure: an edge can be added to a forest exactly when its endpoints are in different trees (Disjoint-Set Operations). The program grows a forest greedily from edges in a given order and confirms that every order reaches the same size, the rank.
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <set>
#include <utility>
#include <vector>
struct DSU {
std::vector<int> p;
explicit DSU(int n) : p(n) { std::iota(p.begin(), p.end(), 0); }
int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }
bool unite(int a, int b) { a = find(a); b = find(b); if (a == b) return false; p[a] = b; return true; }
};
int main() {
// two components: a 4-cycle with a chord on 0..3, and a triangle on 4..6
std::vector<std::pair<int, int>> edges = {{0, 1}, {1, 2}, {2, 3}, {3, 0}, {0, 2}, {4, 5}, {5, 6}, {6, 4}};
std::vector<int> order(edges.size());
std::iota(order.begin(), order.end(), 0);
std::set<int> sizes;
int orders = 0;
do {
DSU dsu(7);
int size = 0;
for (int i : order) size += dsu.unite(edges[i].first, edges[i].second);
sizes.insert(size);
++orders;
} while (std::next_permutation(order.begin(), order.end()));
std::printf("%d edge orders tried, maximal forest sizes found:", orders);
for (int s : sizes) std::printf(" %d", s);
std::printf(" (7 vertices - 2 components = 5)\n");
}40320 edge orders tried, maximal forest sizes found: 5 (7 vertices - 2 components = 5)
All insertion orders end with a forest of exactly 5 edges: every maximal independent set is a basis of the same size, as the theorem says.
Test yourself
Which two axioms define a matroid (besides being nonempty)?
- Hereditary and exchange properties
- Closure under union and intersection
- Optimal substructure and overlapping subproblems
- Transitivity and symmetry
A connected graph has 9 vertices and 15 edges. What is the rank of its graphic matroid?
- 6
- 8
- 9
- 15
Why do the matchings of the path not form a matroid?
- The empty set is not a matching
- A subset of a matching is not a matching
- cannot be extended by any edge of the larger matching
- There are too many matchings