TExcelTAD

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 M=(S,I)M = (S, \mathcal{I}) where SS is a finite set (the ground set) and I\mathcal{I} is a nonempty family of subsets of SS, called the independent sets, such that:

  1. Hereditary property: if B∈IB \in \mathcal{I} and A⊆BA \subseteq B, then A∈IA \in \mathcal{I}. (Subsets of independent sets are independent; in particular ∅∈I\emptyset \in \mathcal{I}.)
  2. Exchange property: if A,B∈IA, B \in \mathcal{I} and ∣A∣<∣B∣\lvert A \rvert < \lvert B \rvert, then there is some x∈B∖Ax \in B \setminus A with A∪{x}∈IA \cup \{x\} \in \mathcal{I}.

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 AA and BB were maximal with ∣A∣<∣B∣\lvert A \rvert < \lvert B \rvert, the exchange property would give x∈B∖Ax \in B \setminus A with A∪{x}A \cup \{x\} independent, so AA was not maximal. ■\blacksquare

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. SS any set of nn elements, I\mathcal{I} all subsets of size at most kk. Hereditary: obviously. Exchange: if ∣A∣<∣B∣≤k\lvert A \rvert < \lvert B \rvert \le k, adding any element of B∖AB \setminus A gives a set of size at most kk.

Graphic matroid. For an undirected graph G=(V,E)G = (V, E), take S=ES = E 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 AA on the vertex set VV has exactly ∣V∣−∣A∣\lvert V \rvert - \lvert A \rvert trees (each edge of a forest joins two trees). If ∣A∣<∣B∣\lvert A \rvert < \lvert B \rvert, the forest BB has fewer trees than AA, so some tree of BB contains vertices from two different trees of AA, and therefore some edge of that tree joins two different trees of AA. Adding it to AA creates no cycle. The bases are the spanning forests, and the rank is ∣V∣\lvert V \rvert minus the number of connected components.

Linear matroid. SS a finite set of vectors, independent sets the linearly independent subsets. The exchange property is the Steinitz exchange lemma from linear algebra.

Partition matroid. SS split into disjoint groups S1,…,SkS_1, \ldots, S_k with capacities c1,…,ckc_1, \ldots, c_k; a set is independent if it takes at most cic_i elements from each group SiS_i, 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 GF(2)\mathrm{GF}(2) (bit vectors with XOR as addition), and for a structure that turns out not to be a matroid.

python · try it yourself
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 {110,011,101}\{110, 011, 101\}, whose XOR is zero.

The exchange proof for forests also gives a formula for the rank: ∣V∣\lvert V \rvert 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.

python · try it yourself
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 a−b−c−da - b - c - d, the middle edge {bc}\{bc\} is a matching and {ab,cd}\{ab, cd\} is a larger one, but neither abab nor cdcd can be added to {bc}\{bc\}, since both share an endpoint with it. The program finds this failure. As a consequence, both maximal matchings {bc}\{bc\} and {ab,cd}\{ab, cd\} exist, with different sizes, and the greedy "take the heaviest edge that fits" can get stuck at {bc}\{bc\}. 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.

cpp · try it yourself
#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 8!=40,3208! = 40{,}320 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 I\mathcal{I} being nonempty)?

  1. Hereditary and exchange properties
  2. Closure under union and intersection
  3. Optimal substructure and overlapping subproblems
  4. Transitivity and symmetry

A connected graph has 9 vertices and 15 edges. What is the rank of its graphic matroid?

  1. 6
  2. 8
  3. 9
  4. 15

Why do the matchings of the path a−b−c−da - b - c - d not form a matroid?

  1. The empty set is not a matching
  2. A subset of a matching is not a matching
  3. {bc}\{bc\} cannot be extended by any edge of the larger matching {ab,cd}\{ab, cd\}
  4. There are too many matchings