Greedy algorithms, exchange arguments and matroids
Prove and refute greedy algorithms using stays-ahead and exchange arguments, then characterize optimal greedy selection with matroids.
After this lesson you can
- Design greedy algorithms and find counterexamples when they are not optimal.
- Prove optimality with stays-ahead and exchange arguments.
- Verify matroid axioms in graphic, linear, uniform and partition examples.
- Prove the Rado-Edmonds theorem and apply it to deadline scheduling.
- Recognize when a greedy algorithm provides only an approximation, not an optimum.
Before you start
Motivation: the decision never revisited
A greedy algorithm builds a solution piece by piece, at each step choosing what seems best now without looking ahead or undoing anything. It is an especially tempting design idea, so it appears everywhere:
- Codes and trees. Huffman repeatedly merges the two least frequent symbols, while Kruskal and Prim build minimum spanning trees by adding the cheapest edge that breaks nothing. All three are optimal, and the ideas for proving it (exchange and, for Kruskal, matroids) are this lesson’s subject.
- Machine learning. A decision tree grows by selecting the highest-gain split at each node without considering later possibilities, so the resulting tree is not globally optimal. k-means++ initialization chooses centers greedily (randomized), and data or sensor selection with submodular functions is greedy by construction.
- Text generation. A language model’s greedy decoding chooses the most likely token at each step. Imagine a two-step model. At the first, , and . If the first was , the most likely second token is with (remaining mass is distributed); if it was , the second is with . Greedy chooses then , a sequence of probability , whereas has probability . Greedy maximizes each factor separately, not the product.
- Scheduling. Which task to run next in a job queue or how many rooms a set of meetings needs are problems with simple greedy rules.
Greedy algorithms have a bad reputation among those who have seen them fail and too good a reputation among those who have only seen them work. Both are justified: some greedy algorithms are optimal with a clean proof, others arbitrarily bad. Coin change is the simplest starting case. Paying an amount with the fewest coins seems to call for repeatedly choosing “the largest that fits”, and this works for euros or dollars. With another system it does not:
The lesson has three ideas. First, how to prove a greedy algorithm optimal: no mechanical recipe exists, but two arguments work in most cases and are learned through three scheduling problems. Second, how to disprove a false one: systematically search for counterexamples. Third, an exact characterization of when greedy works for every weight function: matroid structure and the Rado–Edmonds theorem.
The greedy paradigm and how to prove it
A greedy algorithm always has two ingredients: a notion of feasibility (which partial sets can be extended) and a selection rule (which candidate is preferred). Most design work is choosing the rule; proof work is checking that despite never looking back, the result cannot be improved. Two arguments are most useful.
Greedy stays ahead. Compare greedy step by step with any optimal solution and prove by induction that after each step greedy is at least as good according to a progress measure. At the end, “at least as good at every step” implies “at least as good overall.”
Exchange argument. Start from any optimal solution and transform it by local changes that never worsen value until it becomes the greedy solution. An exchange argument does not need the optimum to resemble greedy: it forces that resemblance without losing quality. It is the most versatile argument: use it for deadline queues, fractional knapsack, Huffman and finally matroids.
Notice an important asymmetry. One counterexample refutes a greedy algorithm; proving it needs a general argument. Counterexamples are searched for: a small instance with adversarial intent almost always reveals them, so distrust a greedy rule tested only on successful examples.
Interval scheduling
This models “one resource, many reservations”: a room, GPU or antenna. Many plausible greedy rules sort requests by a criterion and accept each if compatible with those accepted. Four candidates:
- Earliest start: smallest .
- Shortest: smallest .
- Fewest conflicts: collides with the fewest remaining requests.
- Earliest finish: smallest .
All four sound reasonable and intuition cannot distinguish them. An adversary can. In the next interactive you draw instances and the computer compares each rule with the brute-force optimum:
What you should have seen:
- Earliest start loses with a very long interval starting first and blocking all others.
- Shortest loses with a short interval straddling two long ones that fit together.
- Fewest conflicts loses, but its counterexample must be constructed carefully: the figure’s instance, which fails under any tie breaking, has 11 intervals, and the button’s random search with 8 to 11 intervals usually needs thousands of instances (with smaller instances such as the lab’s, it may find none). A useful caution: a rarely failing rule looks correct.
- Earliest finish never loses, in random search or your attempts. That proves nothing, but suggests a theorem. Here it is.
Proof
Let be greedy’s chosen requests in selection order, and those of an optimal solution sorted by finish. Since compatible, they are also sorted by start and each starts no earlier than the preceding one ends. By optimality, .
Claim (greedy stays ahead): for every .
Base. is the request with earliest finish of all, so .
Step. Suppose . Request starts no earlier than , hence no earlier than . All requests accepted so far end by , so was compatible with them when greedy chose . Among candidates greedy takes the earliest finishing: .
Cardinality. If , request would exist and start no earlier than , by the claim. It would be compatible with everything greedy chose, so greedy could not have stopped after : contradiction (proof by contradiction). Thus .
∎The proof shows why the rule is right: earliest finish leaves as much timeline free as possible for what follows, exactly the progress measure the argument needs. Each counterexample to the other rules is a failure of that measure: a long or straddling interval consumes time unnecessarily.
Sorting dominates implementation cost: with mergesort and for the rest. By the comparison-sorting lower bound, an algorithm beginning with comparison sort cannot improve that.
Interval partitioning: a bound achieved by greedy
Now change the question: serve all requests using the fewest resources (rooms, processors). Interval partitioning distributes intervals into the smallest number of mutually compatible classes.
There is an obvious lower bound. The depth of an interval set is the largest number containing a single instant. Those intervals are pairwise incompatible, so any assignment needs at least rooms. Remarkably, that bound is always attained.
Proof
Let be the interval forcing room number to open. At that time the previous rooms are occupied: the last interval assigned to each satisfies , and since processed earlier, . Those intervals and all contain instant , so . Thus no room beyond the -th is ever opened.
∎This is another greedy proof: compare not with an optimum but with a lower bound greedy attains. If no solution can go below a quantity and your algorithm matches it, you are done. To implement “first free room”, use a heap of (last interval finish, room) pairs: if the minimum has ended, reuse that room; otherwise open a new one. This gives total. The earlier interactive’s ‘Assign rooms’ mode shows it.
Minimize maximum lateness: exchange argument
Now each request is a task to complete in full without interruption on one machine. Task takes and has deadline . Run in gapless order, task finishes at and its lateness is .
Again reasonable rules exist: shortest first (clear the queue), least slack first (most urgent), earliest due date (EDD). The third looks most naive because it ignores durations, yet is correct. Why do the others fail?
- Shortest first fails. With task and another , running the short one first finishes the long one at 11, lateness 1. Running the long one first finishes it at 10 without lateness, and the short one at 11 with deadline 100: maximum lateness 0.
- Least slack fails. With and , slacks are 1 and 0. Doing the zero-slack task first finishes ‘s task at 10 and the other at 11, lateness 9. Deadline order does first (finishes at 1) and the other finishes at 11, lateness 1.
- Earliest due date is optimal, a result of Jackson (1955), whose proof is the canonical exchange argument.
First see the idea. The interactive takes any execution order (by default the worst, reverse deadline order) and repairs it through swaps of misordered adjacent pairs, showing lateness at every step:
The proof formalizes what you saw. Two preliminary observations simplify it. First, gaps are unhelpful: advancing a task after a gap worsens no finish time. Second, any order is a permutation of tasks, and an inversion is a task pair with executed before but . Deadline order is exactly the order without inversions. With equal deadlines, every inversion-free order has the same maximum lateness.
Proof
Step 1: all inversion-free orders have the same maximum lateness. Two inversion-free orders differ only in the order of equal-deadline tasks. Those tasks occupy a contiguous block ending at the same time in both orders, and the block’s maximum lateness is that of its last task, whose finish is always that time: it is the same for any internal order.
Step 2: if an order has an inversion, it has an adjacent inversion. If precedes with , inspect tasks between them: deadlines must decrease somewhere, and that decrease is an inverted adjacent pair.
Step 3: swapping an adjacent inversion does not increase maximum lateness. Let immediately precede with , and let be the starting time of . Other tasks’ finish times are unchanged. Before: and . After swapping: and . Then
Step 4: conclusion. Each adjacent-inversion swap reduces inversion count by exactly one, a nonnegative integer at most . Start from any optimal order and swap until no inversions remain in at most steps; maximum lateness never rises. The result is inversion-free and by Step 1 has the same maximum lateness as deadline order. Since the optimum did not rise, deadline order is optimal.
∎This exchange-argument pattern deserves a name: (1) fix an arbitrary optimum; (2) identify a disorder measure relative to greedy (here, inversions); (3) prove a local change reduces disorder without losing value; (4) conclude greedy is as good as optimum. Step 3 alone uses the particular greedy rule.
Fractional knapsack and Huffman
Two famous cases fit the same mold.
Fractional knapsack. There are items with value and weight , and a knapsack of capacity ; any fraction of each item may be taken. Greedy sorts by decreasing density and fills the knapsack until full. It is optimal by exchange: if an optimum takes weight from item while leaving a denser item not fully taken (), moving that weight (or what remains of , if less) from to respects capacity and changes value by . Repeating reaches greedy’s allocation.
But with indivisible items (0/1 knapsack), density-greedy fails. With values and weights , , and capacity 50, greedy takes the first two for value ; the best is the last two, with . The fraction available in the continuous case made exchange valid. 0/1 knapsack requires dynamic programming (pseudopolynomial).
Huffman. Given a frequency distribution, Huffman builds a minimum-average-length prefix code by repeatedly merging the two least frequent symbols. The key is an exchange lemma.
Proof
Let be an optimal tree and two sibling leaves of maximum depth (they exist: an optimal tree is full, meaning every internal node has two children, because a single-child node could be removed to shorten codes; hence a deepest leaf has a sibling, which is a leaf by maximum depth). Swap positions of and in . If are their depths and frequencies, cost changes by : it does not rise. Do the same with and (if or already occupies one of those leaves, rename and so that leaf is its own and the swap unnecessary). The resulting tree is optimal and has and as deepest siblings.
∎Merging and into a new symbol of frequency , the large tree’s cost is the reduced tree’s plus , so an optimum for the reduced problem gives one for the original, and induction on symbol count concludes (strong induction in practice). With frequencies (percent), the algorithm first merges and , then and , then and , then and and finally and : mean length bits per symbol versus for fixed length and entropy bits.
Matroids
Several earlier problems have optimal greedy algorithms, but each proof was different. Is there a common structure explaining them all? For a huge family of problems there is: matroid theory, introduced by Whitney in 1935 to abstract linear independence.
(I1) and (I2) say is a family of “feasible” sets closed under element removal. Everything special is in (I3): a smaller independent set can always grow with help from a larger one. See it in the main examples.
- Uniform : has elements and independent sets have at most elements. (I3) is immediate: if , any works.
- Partition: is divided into blocks with capacities , and an independent set has at most elements in each block . If , a block has (otherwise summing across blocks gives ), and any can be added.
- Graphic: is a graph’s edge set and independent sets are forests (acyclic edge sets).
- Linear: is a list of vectors and independent sets are linearly independent subsets.
The last two deserve proof.
Proof
Graphic. Let be forests with . A forest with edges on vertices has connected components. If every edge of lay within components of , then would be a forest within those components, and a forest on a component of vertices has at most edges; summing gives , absurd. Thus an edge of joins distinct components of : adding it closes no cycle.
Linear. Let be independent with . Subspace has dimension . If every vector of lay in , the independent vectors of would inhabit a space of dimension , impossible because more vectors than the dimension are dependent (Steinitz’s exchange lemma, and basis dimension is unique). Thus some is outside , and is independent.
∎And three natural systems that are not matroids:
- Graph matchings. On path with edges , , , sets and are matchings with , and neither nor can be added to .
- Independent vertex sets (no adjacent pair). On path , and violate (I3).
- Knapsack: item sets of total weight . With weights and , and violate (I3).
All three satisfy (I1) and (I2), and such a system is called an independence system. What distinguishes a matroid is exactly (I3), and the next result shows why that axiom matters.
Proof
If are bases with , (I3) gives with independent, so would not be maximal. Contradiction.
∎The three negative examples visibly violate this: the three-edge path has a maximal one-edge matching () and another with two (). A greedy algorithm stuck in the first cannot be optimal with suitable weights. Beware the false converse: equal sizes for all bases of do not suffice. In a four-vertex cycle all maximal matchings have two edges and yet and violate (I3). What is equivalent to (I3) is the local version: for every , all maximal independent sets contained in have equal size (an augmentation-violating pair gives two of different sizes within ). Circuits are minimal dependent sets: cycles in the graphic matroid, minimal linearly dependent sets in the linear matroid, and in uniform (with ) sets of elements. A set is independent if and only if it contains no circuit, so circuits describe the matroid as well as independent sets.
Now experiment. The next interactive checks (I1), (I2) and (I3) by enumerating all subsets and, when (I3) fails, shows a violating pair . Change the system, edit the graph or drag vectors:
The Rado–Edmonds theorem
On matroid with weights , the problem is to find an independent set of maximum weight . Matroid greedy is as simple as:
- Sort by decreasing weight: .
- Start with . For : if , set .
It uses the matroid only through an independence oracle (“is this set independent?”). And it works exactly when it should:
The theorem has two names: Rado published it in 1957 in independence-function language, and Edmonds rediscovered it in 1971 and placed it in the modern algorithmic framework (Gale also gave a version in 1968). The forward direction exemplifies “greedy stays ahead”; the converse constructs adversarial weights, which you will do below.
Proof
(Matroid implies optimal greedy.) Let be greedy’s result in acceptance order, so . is maximal: an element was rejected because it broke independence with a subset of , and heredity (I2) keeps that true later. By the bases proposition is a base and . Let be a maximum-weight independent set. Since weights are nonnegative, can be extended to a base without lowering its weight, so assume is a base ordered with .
Claim (greedy stays ahead): for every .
Otherwise let be the smallest index with . Apply (I3) to and : since , there is with and , so . Greedy examined before (it has strictly greater weight). At that moment its set satisfied , so , and (I2) forces to be independent: greedy would have accepted . But then , contradicting .
Summing the claim, .
(Optimal greedy implies matroid.) This is the exercise “The converse of Rado–Edmonds” below.
∎Three consequences justify the effort:
- Kruskal is correct. The graphic matroid of a connected graph with vertices has spanning-tree bases, all with edges. With weights , where exceeds all weights, a maximum- tree is a minimum- tree (all have the same edge count), and greedy sorting by decreasing is Kruskal sorting by increasing . Checking “does it close a cycle?” checks graphic-matroid independence (in practice, with union-find).
- Negative weights and bases. With negative weights, stop greedy on reaching the first nonpositive weight: negative-weight elements never help. For the maximum- or minimum-weight base, add a constant to all weights as just done: all bases have elements, so each weight changes by the same amount and the best stays best.
- The theorem characterizes. Any problem whose greedy algorithm is optimal for all weights has matroid structure. Given a set system and asking whether weight-greedy works, (I3) decides.
The last sentence has fine print: not every optimal greedy algorithm is matroid greedy. Earliest finish is optimal for interval scheduling, but sets of compatible intervals do not form a matroid: with , and , independent set cannot be augmented by any element of . No contradiction: Rado and Edmonds concern greedy sorting by weight (and a weight function fools it), whereas earliest finish sorts by a different criterion, finish time, which is not a weight. The same holds for Huffman.
Unit-task scheduling with deadlines
One last example has no obvious greedy algorithm until the matroid is seen. There are unit-duration tasks; task has integer deadline and profit received only if completed on time. Choose which tasks to perform and in what order to maximize profit.
A task set is schedulable if an order exists in which all finish on time. Deciding schedulability is easy:
Proof
() Tasks with deadline must occupy distinct slots within , so there can be at most . () Run tasks by increasing deadline: the -th occupies slot . Its deadline satisfies (that task and the preceding have deadline ), and by assumption, so .
∎Proof
(I1) and (I2) are immediate. For (I3), let be schedulable with , and let be the largest deadline. Since , there is a largest with (always true for ), and for every we have . In particular because the left side minus the right is . Thus has more tasks with deadline exactly than , and a task exists with deadline . Show is schedulable. For nothing changes. For , (the first inequality because and they are integers). By the lemma it is schedulable.
∎By Rado–Edmonds greedy is optimal: sort tasks by decreasing profit and accept each if the set remains schedulable. With tasks equal to , , , and : accept ; accept (two have deadline , which fits); reject (three have deadline ); reject too; accept . Total profit . An “earliest deadline first” or “highest profit among urgent tasks” algorithm would need its own proof: the matroid framework supplies one at once.
Beyond matroids
What if the system is not a matroid? Two useful situations retain greedy as a good tool, but no longer exact.
Matroid intersection. Many problems are intersections of two matroids: a bipartite graph matching is an edge set independent in two partition matroids simultaneously (at most one edge per left vertex, at most one per right vertex). For two matroids an exact polynomial-time algorithm exists (Edmonds), but is not greedy; for three the problem is NP-hard (it contains three-dimensional matching). Greedy on the intersection of matroids guarantees fraction of optimum (Jenkyns 1976; Korte and Hausmann 1978), fraction with two matroids.
Submodular functions. A set function is submodular if it has diminishing returns: adding an element to a large set contributes no more than adding it to a small one, namely whenever and . The basic example is coverage: given subsets of a universe, . Maximizing a monotone submodular function subject to is NP-hard, but greedy adding the largest marginal-gain element each step guarantees at least fraction of optimum (Nemhauser, Wolsey and Fisher, 1978), and that is the best possible maximum-coverage bound unless P = NP (Feige, 1998). With a matroid rather than cardinality constraint, greedy guarantees . This is the same lesson’s greedy algorithm with an approximation rather than optimality guarantee, explaining its use in sensor, training-data and feature selection. Minimum-cost greedy set cover has a logarithmic guarantee and appears with approximation ratios.
Lab 1: greedy algorithms with an optimality verifier
The first lab implements the three scheduling algorithms and subjects them to a verifier: brute force on small instances. A proof says greedy is correct, but a verifier protects against implementation mistakes (< where <= belonged breaks everything on ties) and helps find counterexamples to a greedy algorithm of unknown correctness.
import heapq, itertools, random
def compatibles(a, b):
"""Intervalos semiabiertos [s, f): si uno acaba donde empieza el otro, no chocan."""
return a[1] <= b[0] or b[1] <= a[0]
def planificar(intervalos):
"""Voraz de «termina antes». Devuelve los índices elegidos. Coste: la ordenación, O(n log n)."""
elegidos, ultimo_fin = [], float("-inf")
for i in sorted(range(len(intervalos)), key=lambda i: intervalos[i][1]):
s, f = intervalos[i]
if s >= ultimo_fin: # compatible con todo lo elegido: basta mirar el último fin
elegidos.append(i)
ultimo_fin = f
return elegidos
def optimo_bruto(intervalos):
"""Cardinalidad máxima de un conjunto compatible, probando todos los subconjuntos (n pequeño)."""
n, mejor = len(intervalos), 0
for mask in range(1 << n):
idx = [i for i in range(n) if mask >> i & 1]
if len(idx) > mejor and all(compatibles(intervalos[a], intervalos[b]) for a, b in itertools.combinations(idx, 2)):
mejor = len(idx)
return mejor
def particionar(intervalos):
"""Partición voraz: por inicio creciente, al aula que antes se libera si ya está libre. Montículo de (fin, aula)."""
libres, aulas, asign = [], 0, [None] * len(intervalos)
for i in sorted(range(len(intervalos)), key=lambda i: intervalos[i][0]):
s, f = intervalos[i]
if libres and libres[0][0] <= s:
_, a = heapq.heappop(libres)
else:
a, aulas = aulas, aulas + 1
asign[i] = a
heapq.heappush(libres, (f, a))
return asign, aulas
def profundidad(intervalos):
"""Máximo número de intervalos abiertos a la vez (en empates, el fin se procesa antes que el inicio)."""
eventos = sorted([(s, 1) for s, f in intervalos] + [(f, -1) for s, f in intervalos])
abiertos = mejor = 0
for _, d in eventos:
abiertos += d
mejor = max(mejor, abiertos)
return mejor
rnd = random.Random(7)
def aleatorios(n, horizonte=20, largo=7):
out = []
for _ in range(n):
s = rnd.randint(0, horizonte - 1)
out.append((s, s + rnd.randint(1, largo)))
return out
# 1. «Termina antes» frente a la fuerza bruta
fallos = 0
for _ in range(300):
iv = aleatorios(rnd.randint(1, 9))
fallos += len(planificar(iv)) != optimo_bruto(iv)
print("planificación: instancias donde el voraz no alcanza el óptimo:", fallos, "de 300")
# 2. Partición: aulas del voraz = profundidad, y la asignación es válida
malas = 0
for _ in range(2000):
iv = aleatorios(rnd.randint(1, 14), 25, 8)
asign, aulas = particionar(iv)
valida = all(compatibles(iv[a], iv[b]) for a, b in itertools.combinations(range(len(iv)), 2) if asign[a] == asign[b])
malas += not (valida and aulas == profundidad(iv))
print("partición: instancias donde falla algo:", malas, "de 2000")
ejemplo = [(0, 6), (1, 4), (2, 9), (5, 8), (7, 12), (8, 11), (10, 15), (12, 17), (13, 16), (14, 19)]
print("ejemplo: aulas =", particionar(ejemplo)[1], "profundidad =", profundidad(ejemplo), "| intervalos elegidos al máximo:", planificar(ejemplo))Zero failures in both checks. Partition verification checks both parts of the proof: valid assignment and room count equal to depth. Notice the example (also in the interactive): 4 rooms are needed and maximum scheduling has 4 intervals.
For maximum lateness, besides brute-force verification, we check the exchange lemma for what it is, a claim about each step: start from random permutations and repair adjacent inversions, checking maximum lateness never rises.
import itertools, random
def retraso_max(orden, tareas):
"""Retraso máximo de ejecutar las tareas (t, d) en ese orden, sin huecos: max(0, f - d)."""
t, L = 0, 0
for j in orden:
t += tareas[j][0]
L = max(L, t - tareas[j][1])
return max(L, 0)
def por_plazos(tareas):
"""Voraz de Jackson: primero el plazo más cercano (EDD)."""
return sorted(range(len(tareas)), key=lambda j: tareas[j][1])
def mas_corto(tareas):
return sorted(range(len(tareas)), key=lambda j: tareas[j][0])
def menor_holgura(tareas):
return sorted(range(len(tareas)), key=lambda j: tareas[j][1] - tareas[j][0])
def optimo_bruto(tareas):
return min(retraso_max(p, tareas) for p in itertools.permutations(range(len(tareas))))
rnd = random.Random(3)
def instancia(n=6):
return [(rnd.randint(1, 5), rnd.randint(2, 18)) for _ in range(n)]
reglas = {"plazos (EDD)": por_plazos, "más corto": mas_corto, "menor holgura": menor_holgura}
pierde = {k: 0 for k in reglas}
for _ in range(400):
tareas = instancia(rnd.randint(2, 6))
opt = optimo_bruto(tareas)
for nombre, regla in reglas.items():
pierde[nombre] += retraso_max(regla(tareas), tareas) > opt
print("instancias (de 400) donde la regla no es óptima:", pierde)
# El lema de intercambio, comprobado: partir de un orden cualquiera y arreglar inversiones adyacentes.
# El retraso máximo nunca sube y se llega al orden por plazos.
viola = pasos = 0
for _ in range(500):
tareas = instancia(rnd.randint(2, 7))
orden = list(range(len(tareas)))
rnd.shuffle(orden)
L = retraso_max(orden, tareas)
while True:
i = next((i for i in range(len(orden) - 1) if tareas[orden[i]][1] > tareas[orden[i + 1]][1]), None)
if i is None:
break
orden[i], orden[i + 1] = orden[i + 1], orden[i]
L2 = retraso_max(orden, tareas)
viola += L2 > L
L, pasos = L2, pasos + 1
print("intercambios de inversiones realizados:", pasos, "| veces que el retraso máximo subió:", viola)
base = [(3, 5), (3, 4), (1, 8), (4, 10), (2, 16), (1, 6)] # el ejemplo del interactivo
for nombre, regla in reglas.items():
print(f"{nombre:14s} orden {[j + 1 for j in regla(base)]} L = {retraso_max(regla(base), base)}")
print("óptimo por fuerza bruta:", optimo_bruto(base))The deadline rule never loses; shortest loses on over half of random instances and least slack on about one in six. The second experiment’s 2190 exchanges never increased maximum lateness, showing proof step 3 at scale.
Now a counterexample finder, the general tool: it takes a greedy rule, instance generator and exact optimum, and returns the smallest instance where the rule loses. Apply it to four interval rules, coin change and knapsack.
import itertools, random
def compatibles(a, b):
return a[1] <= b[0] or b[1] <= a[0]
def voraz_intervalos(iv, clave):
"""Voraz genérico de planificación: repite «elige el de menor clave y descarta los que chocan con él»."""
resto, elegidos = list(range(len(iv))), []
while resto:
k = min(resto, key=lambda i: (clave(iv, resto, i), i))
elegidos.append(k)
resto = [j for j in resto if j != k and compatibles(iv[k], iv[j])]
return elegidos
REGLAS = {
"empieza antes": lambda iv, resto, i: iv[i][0],
"más corto": lambda iv, resto, i: iv[i][1] - iv[i][0],
"menos choques": lambda iv, resto, i: sum(1 for j in resto if j != i and not compatibles(iv[i], iv[j])),
"termina antes": lambda iv, resto, i: iv[i][1],
}
def optimo(iv):
"""Máximo conjunto compatible, por búsqueda con poda."""
n, mejor = len(iv), 0
def rec(i, elegidos):
nonlocal mejor
if len(elegidos) + n - i <= mejor:
return
if i == n:
mejor = len(elegidos)
return
if all(compatibles(iv[i], iv[j]) for j in elegidos):
rec(i + 1, elegidos + [i])
rec(i + 1, elegidos)
rec(0, [])
return mejor
def buscar_contraejemplo(regla, generar, intentos, semilla=0):
"""Devuelve (instancia más pequeña donde la regla pierde, cuántas veces perdió) tras `intentos` instancias."""
rnd = random.Random(semilla)
mejor, fallos = None, 0
for _ in range(intentos):
iv = generar(rnd)
if len(voraz_intervalos(iv, regla)) < optimo(iv):
fallos += 1
if mejor is None or len(iv) < len(mejor):
mejor = iv
return mejor, fallos
def generar(rnd):
n = rnd.randint(3, 10)
iv = []
for _ in range(n):
s = rnd.randint(0, 14)
iv.append((s, s + rnd.randint(2, 5)))
return iv
for nombre, regla in REGLAS.items():
ce, fallos = buscar_contraejemplo(regla, generar, 1500)
print(f"{nombre:14s} pierde en {fallos:4d} de 1500 instancias" + (f"; la más pequeña: {sorted(ce)}" if ce else ""))
# --- cambio de monedas ---
def voraz_monedas(monedas, x):
n = 0
for c in sorted(monedas, reverse=True):
n, x = n + x // c, x % c
return n
def optimo_monedas(monedas, tope):
"""Mínimo de monedas para cada importe 0..tope, por programación dinámica."""
m = [0] + [10**9] * tope
for x in range(1, tope + 1):
m[x] = min(m[x - c] + 1 for c in monedas if c <= x)
return m
def primer_fallo(monedas):
tope = 3 * max(monedas)
m = optimo_monedas(monedas, tope)
return next((x for x in range(1, tope + 1) if voraz_monedas(monedas, x) > m[x]), None)
for sistema in ([1, 3, 4], [1, 2, 5, 10, 20, 50], [1, 5, 10, 25], [1, 5, 10, 12, 25], [1, 5, 10, 20, 25]):
print(sistema, "-> menor importe donde el voraz falla:", primer_fallo(sistema))
# Cota de Kozen y Zaks: el menor contraejemplo x cumple c_3 + 1 < x < c_(n-1) + c_n
rnd = random.Random(0)
no_canonicos = fuera = 0
for _ in range(600):
c = sorted([1] + rnd.sample(range(2, 40), rnd.randint(2, 5)))
x = primer_fallo(c)
if x is not None:
no_canonicos += 1
fuera += not (c[2] + 1 < x < c[-2] + c[-1])
print("sistemas no canónicos:", no_canonicos, "| fuera de la cota de Kozen-Zaks:", fuera)
# --- mochila: fraccionaria (voraz óptimo) frente a 0/1 (voraz falla) ---
objetos, capacidad = [(60, 10), (100, 20), (120, 30)], 50 # (valor, peso)
orden = sorted(objetos, key=lambda o: o[0] / o[1], reverse=True)
libre, fraccionaria, cero_uno = capacidad, 0.0, 0
for v, p in orden:
tomar = min(1.0, libre / p)
fraccionaria, libre = fraccionaria + tomar * v, libre - tomar * p
libre = capacidad
for v, p in orden:
if p <= libre:
cero_uno, libre = cero_uno + v, libre - p
mejor01 = max(sum(v for (v, p), t in zip(objetos, m) if t) for m in itertools.product([0, 1], repeat=3)
if sum(p for (v, p), t in zip(objetos, m) if t) <= capacidad)
print(f"mochila: voraz fraccionario = {fraccionaria}, voraz 0/1 = {cero_uno}, óptimo 0/1 = {mejor01}")Three observations. Earliest start and shortest fail on 12% and 6% of random instances respectively, with counterexamples of only three intervals, found quickly. Fewest conflicts fails not once in 1500 instances despite being wrong: random search is a weak test for rarely failing rules, so the interactive’s 11-interval counterexample required more time and intervals (and checking all tie breaks). The smallest amount where greedy fails in is ( versus ), in is ( versus ), and euro and dollar systems are canonical. The Kozen–Zaks bound says the smallest counterexample of a system with satisfies ; it holds for all noncanonical systems tested. This decides canonicity by checking only small amounts (the coding exercise uses it). A more refined polynomial algorithm also exists (Pearson, 2005).
Lab 2: matroid greedy in action
The second lab writes generic greedy, needing only an independence oracle, and runs it on four systems: graph forests, independent vector sets (using NumPy rank), deadline tasks and matchings. Brute force compares against optimum for random weights, and it implements the Rado–Edmonds converse: find pair violating augmentation and construct weights that fool greedy.
import itertools, random
import numpy as np
# ---------- el voraz genérico: solo necesita un oráculo de independencia ----------
def voraz(elementos, peso, independiente):
"""Recorre los elementos por peso decreciente y conserva cada uno si el conjunto sigue siendo independiente."""
S = []
for e in sorted(elementos, key=lambda e: -peso[e]):
if independiente(S + [e]):
S.append(e)
return S
def optimo_bruto(elementos, peso, independiente):
"""Peso máximo de un independiente, enumerando todos los subconjuntos."""
mejor = 0
for r in range(len(elementos) + 1):
for S in itertools.combinations(elementos, r):
if independiente(list(S)):
mejor = max(mejor, sum(peso[e] for e in S))
return mejor
# ---------- cuatro sistemas de conjuntos ----------
ARISTAS = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (3, 4), (4, 5), (5, 3)] # índices de arista 0..7
def es_bosque(S):
padre = list(range(6))
def raiz(x):
while padre[x] != x:
padre[x] = padre[padre[x]]
x = padre[x]
return x
for e in S:
u, v = map(raiz, ARISTAS[e])
if u == v:
return False
padre[u] = v
return True
def es_emparejamiento(S):
vertices = [x for e in S for x in ARISTAS[e]]
return len(vertices) == len(set(vertices))
VECTORES = np.array([[1, 0, 0], [2, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 1, 1], [0, 1, 1]], dtype=float)
def son_independientes(S):
return len(S) == 0 or np.linalg.matrix_rank(VECTORES[list(S)]) == len(S)
PLAZOS = [2, 1, 2, 3, 1, 4, 4, 1] # tarea i tiene plazo PLAZOS[i]; todas duran una unidad
def planificable(S):
return all(sum(1 for i in S if PLAZOS[i] <= t) <= t for t in range(1, max(PLAZOS) + 1))
# ---------- el recíproco de Rado-Edmonds, hecho código ----------
def violacion_aumento(elementos, independiente):
"""Devuelve (A, B) independientes con |A| < |B| y sin ningún x de B∖A tal que A+x sea independiente, o None."""
indep = [set(S) for r in range(len(elementos) + 1) for S in itertools.combinations(elementos, r) if independiente(list(S))]
indep.sort(key=len)
for B in indep:
for A in indep:
if len(A) < len(B) and not any(independiente(list(A | {x})) for x in B - A):
return A, B
return None
def pesos_adversos(elementos, A, B):
q = len(A - B)
return {e: (q + 2 if e in A else q + 1 if e in B else 0) for e in elementos}
sistemas = {
"bosques (matroide gráfico)": (list(range(len(ARISTAS))), es_bosque),
"vectores (matroide lineal)": (list(range(len(VECTORES))), son_independientes),
"tareas con plazos": (list(range(len(PLAZOS))), planificable),
"emparejamientos": (list(range(len(ARISTAS))), es_emparejamiento),
}
rnd = random.Random(1)
for nombre, (E, indep) in sistemas.items():
fallos = 0
for _ in range(60):
w = {e: rnd.randint(0, 9) for e in E}
fallos += sum(w[e] for e in voraz(E, w, indep)) < optimo_bruto(E, w, indep)
v = violacion_aumento(E, indep)
print(f"{nombre:27s} voraz subóptimo con pesos aleatorios: {fallos:3d} de 60 | ", "aumento se cumple" if v is None else f"viola el aumento: A={sorted(v[0])}, B={sorted(v[1])}")
if v is not None:
w = pesos_adversos(E, *v)
S = voraz(E, w, indep)
print(f"{'':27s} con los pesos de la demostración: voraz = {sum(w[e] for e in S)}, óptimo = {optimo_bruto(E, w, indep)}")All three matroids pass all tests and matchings fail with random weights in a notable fraction of cases. Random weights need luck; weights built from the augmentation-violating pair make failure certain. The pair found, and , is from path in the matroid section (code edges 0, 1 and 2 form that path). With , edge weighs and edges weigh : greedy takes the -weight edge and ends with , whereas optimum is . This executes the argument in the exercise below.
With libraries: Kruskal is greedy on the graphic matroid and scipy.sparse.csgraph.minimum_spanning_tree must give the same weight. For the linear matroid, numpy.linalg.matrix_rank is the independence oracle. For maximum coverage, submodular greedy comfortably meets its guarantee on random instances, though it can lose on a constructed case.
import itertools, random
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
# ---- Kruskal = voraz sobre el matroide gráfico (pesos crecientes: mínimo en lugar de máximo) ----
def kruskal(n, aristas):
padre = list(range(n))
def raiz(x):
while padre[x] != x:
padre[x] = padre[padre[x]]
x = padre[x]
return x
total, arbol = 0.0, []
for w, u, v in sorted(aristas):
a, b = raiz(u), raiz(v)
if a != b: # la arista no cierra ciclo: A + e sigue siendo un bosque
padre[a] = b
total += w
arbol.append((u, v))
return total, arbol
rnd = np.random.default_rng(0)
dif = 0.0
for _ in range(40):
n = 12
pesos = {(u, u + 1): 1000.0 + u for u in range(n - 1)} # una cadena cara asegura que el grafo es conexo
for u in range(n):
for v in range(u + 1, n):
if rnd.random() < 0.4:
pesos[(u, v)] = float(rnd.integers(1, 100)) + rnd.random() * 1e-3
aristas = [(w, u, v) for (u, v), w in pesos.items()]
w, us, vs = zip(*aristas)
M = coo_matrix((w, (us, vs)), shape=(n, n)).tocsr()
dif = max(dif, abs(minimum_spanning_tree(M).sum() - kruskal(n, aristas)[0]))
print("Kruskal frente a scipy.sparse.csgraph.minimum_spanning_tree, diferencia máxima en 40 grafos:", round(dif, 9))
# ---- base de vectores de peso máximo: voraz con matrix_rank como oráculo ----
def base_voraz(X, peso):
S = []
for i in np.argsort(-peso, kind="stable"):
if np.linalg.matrix_rank(X[S + [i]]) == len(S) + 1:
S.append(int(i))
return S
rg = np.random.default_rng(3)
peor = 0
for _ in range(40):
X = rg.integers(-2, 3, size=(8, 4)).astype(float)
p = rg.integers(1, 20, size=8).astype(float)
S = base_voraz(X, p)
mejor = max(p[list(T)].sum() for r in range(5) for T in itertools.combinations(range(8), r) if r == 0 or np.linalg.matrix_rank(X[list(T)]) == r)
peor = max(peor, mejor - p[S].sum())
print("base de vectores de peso máximo: mayor pérdida del voraz en 40 instancias =", peor)
# ---- más allá de los matroides: cobertura máxima, la función submodular de siempre ----
def cobertura(conjuntos, elegidos):
return len(set().union(*[conjuntos[i] for i in elegidos])) if elegidos else 0
def voraz_cobertura(conjuntos, k):
S = []
for _ in range(k):
S.append(max((i for i in range(len(conjuntos)) if i not in S), key=lambda i: cobertura(conjuntos, S + [i])))
return S
rg2 = random.Random(5)
peor_cociente, k = 1.0, 3
for _ in range(250):
conjuntos = [set(rg2.sample(range(14), rg2.randint(2, 7))) for _ in range(8)]
opt = max(cobertura(conjuntos, T) for T in itertools.combinations(range(8), k))
peor_cociente = min(peor_cociente, cobertura(conjuntos, voraz_cobertura(conjuntos, k)) / opt)
print(f"cobertura máxima con k = {k}: peor cociente voraz/óptimo en 250 instancias = {peor_cociente:.3f} (cota 1 - 1/e = {1 - np.exp(-1):.3f})")
# un caso donde el voraz no es óptimo: el conjunto grande engaña
trampa = [set(range(1, 5)), set(range(5, 9)), {1, 2, 5, 6, 7}]
print("trampa: voraz cubre", cobertura(trampa, voraz_cobertura(trampa, 2)), "elementos, el óptimo cubre", cobertura(trampa, [0, 1]))Output reports three things: Kruskal agrees with SciPy (zero difference); linear-basis greedy never loses to brute force (a matroid); and in coverage the worst ratio observed on random instances is well above , but the “trap” confirms no equality: with , and greedy first takes the 5-element set and covers 7, while the first two cover 8.
Common mistakes
Exercises
Step 1 of 5. You want to transform into an optimum containing . What change do you make?
Step 1 of 5. Since , how are and related?
More than one answer may be correct.
primer_contraejemplo(monedas). It receives a list of coin values (distinct positive integers including 1) and returns the smallest amount for which greedy (repeatedly take the largest fitting coin) uses more coins than optimum, or None if the system is canonical. Use dynamic programming for optimum. By the Kozen–Zaks bound, checking amounts below (the two largest coins) suffices when there are at least three coins; with fewer, greedy is always optimal.def primer_contraejemplo(monedas):
# menor importe en que el voraz paga con más monedas que el óptimo; None si no hay
passSummary
- Greedy = local choice without backtracking. Counterexamples refute; stays-ahead or exchange proves. Always look for counterexamples before trusting greedy.
- Intervals. Earliest finish maximizes compatible request count; assigning rooms by start grows to depth, an attained lower bound.
- Maximum lateness. Earliest deadline is optimal: swap adjacent inversions and maximum lateness never rises. Shortest first and least slack fail.
- Knapsack and Huffman. Density-greedy is optimal for fractional knapsack and fails for 0/1. In Huffman an exchange lemma makes the two least frequent deepest siblings.
- Matroid: (I1) empty, (I2) heredity, (I3) augmentation. Graphic (forests), linear, uniform, partition and unit deadline tasks are matroids; matchings, independent vertex sets and knapsack are not. All bases have equal size.
- Rado and Edmonds. On a system with (I1) and (I2), weight-greedy is optimal for every if and only if (I3) holds. Kruskal is the graphic-matroid case.
- Beyond. On the intersection of two matroids or with submodular functions, greedy only approximates ( and ): do not confuse it with exact matroid greedy.