Matchings, colouring, planarity and Ramsey theory
Classical structural results with certificates in both directions: Hall's and König's theorems for matchings, graph coloring and chromatic number, planar graphs and Euler's formula, and Ramsey theory with Erdős's probabilistic bound. The four-color theorem bridges to computer-assisted proof.
After this lesson you can
- Prove Hall's theorem and extract a violating set when no perfect matching exists.
- Apply König's theorem and connect it to min-max duality.
- Bound the chromatic number and analyze order dependence in greedy coloring.
- Use Euler's formula to prove that K5 and K3,3 are nonplanar.
- Prove upper and lower bounds for Ramsey numbers, including the probabilistic bound.
Before you start
Motivation: assign, schedule, draw
Three problems that arise when managing a real system:
- Assign jobs to GPUs. You have six training jobs and six GPUs, but not every job fits every GPU: some need 80 GB of memory, others a particular architecture, others a machine in a particular region. Is there an assignment placing each job on a distinct GPU? The same problem appears under other names when distributing papers to reviewers without conflicts of interest or assigning candidates to positions.
- Schedule exams or allocate registers. Two exams sharing a student cannot use the same time slot; two variables live at the same time cannot share a processor register. How many slots or registers are needed? This is graph coloring: compilers have allocated registers this way since Chaitin’s work in the early 1980s.
- Draw without crossings. A single-layer printed circuit, a subway network plan, or a political map: can the connections be drawn without crossing?
This lesson’s theorems answer these questions and share a thread worth keeping in mind from the start: certificates. When an algorithm says “yes, there is an assignment,” it can give you the assignment, which is trivial to check. But when it says “there is none,” how do you check without repeating the entire search? Hall’s theorem gives a short “no” certificate for assignments; König’s turns a maximum into an exhibitable minimum; Euler’s formula certifies that certain graphs cannot be drawn without crossings without trying any drawing. Coloring, by contrast, is a case where no short “no” certificate is known: deciding whether a graph is 3-colorable is NP-complete. Ramsey theory closes the lesson with the opposite extreme: an existence proof that constructs nothing.
Everything that follows uses the vocabulary of the graph lesson: degrees, paths and connectivity, and above all bipartite graphs. We write for the neighbors of and for the neighborhood of a set.
Matchings and augmenting paths
Distinguish two notions everyday language confuses. A matching is maximal if no edge can be added, and maximum if no other has more edges. Every maximum matching is maximal, but not conversely: in path , matching is maximal (every other edge touches or ) but not maximum, because has two edges. The greedy strategy, adding edges while possible, produces maximal matchings and can get stuck at half the optimal size.
The way out is the central observation of matching theory. In the example, path starts and ends at free vertices and alternates edges outside and inside : outside (), inside (), outside (). Swap the roles of its edges: those inside leave, those outside enter, and the matching grows by one edge.
Check that remains a matching vertex by vertex: interior path vertices change partners but retain exactly one, endpoints change from free to saturated, and the rest are untouched. Surprisingly, this local operation suffices to reach the optimum.
Proof
If there is an augmenting path , is larger, so is not maximum. Conversely, suppose is not maximum and let with . In graph with edges every vertex has degree at most 2 (one edge from each matching), so its components are paths and cycles, and in all of them edges alternate between and . Alternating cycles have even length and as many edges from as from . Since has more edges of than of in total, some component is a path with one more edge of than of : it begins and ends with edges of , and its endpoints are free in , because if one were saturated by that edge of would be in and extend the path. It is an augmenting path for .
∎Berge immediately gives an algorithm: start with and, while an augmenting path exists, flip it. Each step increases by one, so there are at most steps. The difficulty is finding paths. In a bipartite graph, alternating breadth-first search suffices: from a free vertex of follow edges outside to , and from return to along its unique edge of , if any. In general graphs, odd cycles confuse the search and Edmonds’s blossom algorithm is needed, covered in algorithms.
Hall’s theorem: a certificate for no
Return to the GPUs. Call the jobs and the GPUs , and join each job to the GPUs it fits: a bipartite graph. We want a matching that saturates . There is an obvious obstruction: if three jobs collectively fit only two GPUs, one is left out. In general, if a set has fewer neighbors than elements, , there is no assignment. Hall’s theorem says this is the only possible obstruction.
The condition on the right is Hall’s condition, and an violating it is a violating set. The forward implication is the obvious obstruction: if saturates , the vertices of have distinct partners, all in . The converse is the real content, and our proof is an algorithm: it either finds the matching or constructs a violating set.
Proof
Assume Hall’s condition and let be a maximum matching. If it saturates , we are done. Otherwise let be free, and let be the set of vertices reachable from by alternating paths (starting with an edge outside ), including itself. Write and .
- Every is saturated, and its partner lies in . If were free, the alternating path from to would be augmenting, and would not be maximum (Berge). Its partner is reached by extending the path along the edge of .
- Every other than is the partner of some . Alternating paths from always reach along an edge of .
- . If and : either , and then is the edge used to reach , or , and extending the path from to with gives an alternating path to . In both cases .
By 1 and 2, matches to , so , contrary to Hall’s condition.
∎Read the proof backwards for an algorithm with a certificate: launch alternating search from each free candidate; if it reaches a free position, flip the path; otherwise the candidates reached form a violating set with exactly one fewer neighbor than elements. Try it.
What you should have seen:
- An augmenting path can be long. In the initial example, F knows only position 1, occupied by A; A can move to 2, occupied by B; and so on to E, for whom 6 is free. Path has 11 edges and flipping it moves all candidates without any losing a position. A greedy assignment would never find it.
- The dead end leaves a verifiable trace. In the bottleneck, A, C, and E know only positions 2 and 5. The search from the candidate left out reaches exactly and . To convince someone there is no assignment, there is no need to show the algorithm: point to those three candidates and two positions.
- The violator’s deficit is what is missing. With “Six for five positions,” the final violator satisfies : it not only proves there is no perfect matching, but that the one found is the best possible.
The last observation is worth stating as a theorem, because this is how Hall is used in practice: the worst bottleneck fixes the size of the best matching.
Proof
Any matching leaves at least vertices of each free, because those of can only occupy positions in : this gives . For equality, take a maximum and launch alternating search from all free vertices of at once. The same reasoning as in Hall’s proof shows that the reached vertices, , satisfy , that matches to the saturated vertices of , and that all free vertices of lie in . Thus is exactly the number of free vertices of , namely .
∎A classical consequence, proved by double counting: every -regular bipartite graph with has a perfect matching. The edges leaving number and all reach , which receives edges total; hence and Hall holds. Also , so saturating saturates everything. Removing that matching leaves an -regular graph, and repeating partitions edges into perfect matchings. This underlies league schedules: over rounds, each team in one group plays each of the in the other once.
The Hall proof you saw constructs the matching. The classical proof by strong induction, due to Halmos and Vaughan (1950), is shorter and gives no algorithm; complete it yourself.
Step 1 of 4. Which division into cases advances the induction?
König’s theorem: a minimum equals a maximum
Hall’s certificate answers “can be saturated?” If the answer is no, how do you certify that a particular matching is the largest possible? A different kind of object is needed, one bounding all matchings from above at once.
In any graph, : matching edges share no endpoints, so a cover needs a distinct vertex for each. This is weak duality, and it suffices to certify optimality: if you find a matching and a cover of the same size, both are optimal. In a triangle this is impossible: and . In bipartite graphs it is always possible.
This is König’s theorem, and its proof reuses alternating search: the same set that gave Hall’s violator gives the cover.
Proof
Let be a maximum matching and the set of vertices reachable by alternating paths from free vertices of (including those vertices). Take
is a cover. Let be an edge, with . If , then . If , is reached from : along edge if it is not in , and if it is in it is the edge used to reach (a saturated of is only reached through its partner). In both cases , hence .
. Every vertex of is saturated: free vertices of lie in , so not in ; and a free would give an augmenting path, impossible by Berge. Moreover, no edge of has both endpoints in : if with , extending the path along gives , hence . Thus each vertex of belongs to a different edge of , and .
By weak duality, , and all inequalities are equalities.
∎Enable König’s cover in the first interactive: the green marks are , there are as many as edges in , and each lies on a different matching edge. This optimality certificate can be checked in seconds.
Hall follows from König in two lines, showing the two theorems express the same phenomenon: if Hall’s condition holds and is a cover, vertices of have all their neighbors in , so and . Thus .
Coloring and chromatic number
This is coloring, a pure constraint satisfaction problem: one variable per vertex, a domain of values, and a “different” constraint per edge. Lower bounds come from substructures forcing colors to be used:
- Cliques. If contains a , its vertices need different colors: , the largest clique size.
- Independent sets. Each color class has at most vertices, so .
- Odd cycles. if and only if is bipartite, that is, if and only if it has no odd cycles. An odd cycle forces 3 colors.
Greedy coloring and order
The most natural algorithm visits vertices in an order and gives each the smallest color unused by any already colored neighbor.
Proof
- When arrives, its colored neighbors block at most colors, so one of is free.
- Take an optimal coloring and order vertices by class: color 1 first, then color 2, and so on. By strong induction on position, greedy gives each vertex a color . A neighbor preceding has by the order, and because classes are independent; hence and, by induction, its greedy color is . No earlier neighbor has color , so receives a color . The total is , and it cannot be smaller.
The second part is a warning disguised as good news: coloring is exactly the problem of finding a good order, and that is as hard as coloring. With a bad order, greedy can be catastrophic even on the easiest graph, a bipartite one.
What you should have seen:
- On the crown, alternating order is a perfect trap. and are not neighbors and receive color 1. neighbors , so receives 2, and , a neighbor of , also gets 2. On reaching , its neighbors already use colors , so it needs . Result: colors for a graph colorable with 2. Ordering by degree does not help because all vertices have degree .
- The order bound is tight for alternating order, and only a bound for the other. In alternating order, and have earlier neighbors, so , exactly the colors used. In side-by-side order the bound remains because each has earlier neighbors, but all have the same color and greedy uses 2.
- DSatur succeeds. It first colors the vertex with the most distinct colors among its neighbors (most saturated), breaking ties by degree. On the crown it finds 2 colors at any size.
- Petersen and Grötzsch are triangle-free yet need 3 and 4 colors. for both: the clique bound can miss by a lot.
DSatur, due to Brélaz (1979), optimally colors every bipartite graph, but is not optimal in general. For the bipartite case: while an already started component has an uncolored vertex, DSatur picks one with saturation at least 1, i.e. adjacent to a colored vertex; in a bipartite graph all its colored neighbors lie on the other side and, by induction, have the same color, so it receives the other of the two. Another heuristic with a guarantee is smallest-last order: repeatedly remove a minimum-degree vertex and color in reverse order. If every subgraph of has a vertex of degree ( is called -degenerate), each vertex has at most earlier neighbors and greedy uses at most colors. You will use this shortly for planar graphs.
Bounds, Brooks, and the gap between ω and χ
The bound is attained by complete graphs ( has and ) and odd cycles (, ). Brooks’s theorem (1941), stated without proof, says these are the only cases.
In the other direction, bound can be arbitrarily poor. Mycielski’s construction takes a triangle-free graph of chromatic number and produces another triangle-free graph of chromatic number : from an edge it produces cycle () and from the Grötzsch graph () in the interactive. Triangle-free graphs exist requiring arbitrarily many colors. Chromatic number is not a local property.
Planar graphs
Planarity is a property of the graph; crossings are a property of a drawing. The same can be drawn as a square with two crossing diagonals, or as a triangle with a vertex in the center and no crossings. To prove a graph is not planar, all infinitely many possible drawings must be ruled out. Fáry’s theorem (1948) at least allows restriction to straight-line drawings: every simple planar graph has a straight-line plane drawing. But even then not all can be tried. An invariant is needed.
Euler’s formula
Proof
Use induction on , with fixed. If is a tree, by the tree characterization, and its drawing has one face because it encloses no region: . Otherwise it has a cycle . By the Jordan curve theorem, separates the plane into an interior and exterior, so an edge of has a distinct interior face on one side and exterior face on the other. Removing merges those faces, and remains connected because was on a cycle. By induction, , which is the same as .
With components, add edges one at a time, each between distinct components sharing a face (while the graph is disconnected, some face touches two components), drawn within that face: each increases by one without changing , because it joins two distinct boundary pieces and encloses no region, and the resulting graph is connected, so .
∎The formula is surprising at first: the number of faces does not depend on the drawing. Two very different plane drawings of the same connected graph have exactly the same number of faces, . This rigidity allows impossibility proofs.
Counting faces to prove impossibility
The idea is double counting pairs (edge, side of edge). Define the degree of a face as the number of edges on its boundary, counting an edge twice if the same face lies on both sides. Each edge has two sides, so the sum of face degrees is . If every face has degree at least 3, then , and Euler gives a bound that does not mention the drawing.
Step 1 of 4. What is the sum of all face degrees?
The argument generalizes using girth , the shortest cycle’s length. In a connected plane graph that is not a tree, every face boundary contains a cycle, so each face has degree at least : , that is,
With this is ; with , ; and the Petersen graph, with , , and , violates it: . Try it by hand before believing it.
What you should have seen:
- Faces do not depend on the drawing. Untangle the octahedron in two different ways: there are always 8 faces, .
- For and one crossing remains, and this is not lack of skill. and completely prove no plane drawing exists. Their minimum crossing numbers are both 1, and Petersen’s is 2.
- The bound is necessary, not sufficient. plus an edge has triangles, so its bound is , yet it contains a , which cannot be drawn without crossings. satisfying the bound proves nothing.
- Petersen’s highlighting is not a literal . It is a subdivision: a in which some edges have been replaced by paths (the small vertices). Subdivision does not change planarity.
The last point shows the complete characterization of planarity, one of the great theorems of graph theory.
You just proved the easy direction: and are nonplanar, and subdividing or adding edges does not fix this. We do not prove the hard direction, that every nonplanar graph contains one of those obstructions. Wagner (1937) gave an equivalent version using minors, which also allow edge contraction: a graph is planar if and only if it has neither nor as a minor. For us, the key point is that planarity has certificates in both directions: a plane drawing for yes, a Kuratowski subdivision for no. The planarity test has been linear since Hopcroft and Tarjan (1974), and modern algorithms produce the appropriate certificate in linear time; networkx.check_planarity returns one or the other.
Five colors suffice
With , the degree sum is , so the average degree of a simple planar graph is less than 6: every planar graph has a vertex of degree at most 5. Since subgraphs of a planar graph are planar, every planar graph is 5-degenerate, and smallest-last order colors it with 6 colors. Write this as induction:
Step 1 of 3. Which vertex do you choose?
Reaching five colors requires a new idea, Kempe chains, and the proof is beautiful.
Proof
Use induction on , as before: take a plane drawing, a vertex of degree , and a 5-coloring of . If the neighbors of use at most 4 colors, one is free. Otherwise has exactly 5 neighbors , in their order around in the drawing, with colors .
Call the subgraph induced by vertices of colors 1 and 3. If and are in different components of , swap colors 1 and 3 in the component of . The coloring remains proper: an edge between a vertex in the component and one outside cannot join two colors of , because the outside vertex would then be in the component. Now has color 3, keeps its color, and 1 is free for .
If and are in the same component, there is a path from to alternating colors 1 and 3, which with forms a cycle . Since and lie between and on opposite sides in the circular order around , leaves one inside and the other outside (Jordan curve). Any path from to in the plane drawing crosses at a vertex, and all vertices of have color 1 or 3, or are , which is uncolored. Thus and lie in different components of , and swapping 2 and 4 in the component of frees color 2 for .
∎In 1879 Kempe published a four-color “proof” using exactly this technique. The hard case required two swaps at once, and Heawood discovered in 1890 that they can interfere; in pointing out the error, he salvaged the five-color argument.
The four-color theorem and computer-assisted proof
The four-color statement, conjectured by Francis Guthrie in 1852 while coloring a map of English counties, says every planar graph is 4-colorable. (A map becomes a graph by placing a vertex in each country and an edge between countries sharing a border; the resulting graph is planar.) Four cannot be lowered: is planar and needs four.
Kenneth Appel and Wolfgang Haken’s proof (1976) follows the five-color proof’s structure, but on an industrial scale. It has two parts:
- Unavoidability. A finite set of configurations (small subgraphs with their degrees) such that every triangulated planar graph contains at least one. A “discharging” argument proves it: assign charge to each vertex, which by Euler sums to , and redistribution rules force some configuration in the set to appear.
- Reducibility. Each configuration is reducible: if a minimal counterexample contained it, it could be colored, using elaborate Kempe-style arguments. For almost two thousand configurations, a computer performed this check, with more than a thousand hours of computation.
The mathematical community was divided. Is a proof no human can read in full a proof? In 1996 Robertson, Sanders, Seymour, and Thomas gave a simpler version with 633 configurations and 32 discharging rules, and programs anyone could rerun. But the underlying question remained: who verifies the program?
The answer came in 2005, when Georges Gonthier and Benjamin Werner formalized the complete proof in the Coq proof assistant. One need no longer trust the configuration-checking program, only Coq’s kernel, a small program verifying every logical step; even the topological part (what a plane map is, the Jordan curve) is formalized combinatorially. This example opened the door to modern assisted proof, revisited at the end of the module with Lean and language models that write proofs.
Ramsey theory
In the counting lesson you proved with the pigeonhole principle that every two-coloring of the edges of has a monochromatic triangle, and does not suffice. This is the first case of a general phenomenon: total disorder is impossible, and every sufficiently large structure contains an ordered piece.
The existence of is not obvious and must be proved first. The trivial cases are and : a coloring of without a red has some blue edge, a blue , and all-red has neither, so vertices do not suffice. You already know .
The upper bound: the pigeonhole principle again
Proof
Let and , which exist by induction on , and color . A vertex has edges, so by the pigeonhole principle it has at least red or at least blue edges (otherwise it would have at most ).
If it has at least red neighbors, among them there is, by definition of , a red , which with forms a red , or a blue . The other case is symmetric. Thus .
For the closed form, use induction on with Pascal’s rule: , and in the base cases and .
∎With and the binomial theorem, . For the bound gives exactly 6. For it gives 20, while the actual value is . Beyond that little is known: , and in 2023 Campos, Griffiths, Morris, and Sahasrabudhe proved for a fixed , the first exponential improvement to the 1935 bound.
The lower bound: the probabilistic method
To prove one must exhibit a coloring of without a monochromatic . For large nobody knows how to construct a good one. Erdős observed in 1947 that this is unnecessary: it suffices to prove that a random coloring works with positive probability.
Proof
Color each edge of red or blue with probability , independently. For each set of vertices, let indicate that its edges have the same color: there are two monochromatic colorings of those edges among , so . The number of monochromatic is and, by linearity of expectation,
If , it cannot be that for every coloring, because then the mean would be at least 1. Thus some coloring has , and . (This is the union bound: .)
∎The explicit bound is an exponent calculation. Take and follow the steps:
The bound is generous; the exact condition gives more. For it works up to (), and for up to , versus . Check how it behaves on actual colorings.
What you should have seen:
- Below the threshold, good colorings are the majority. With and , , and around 70% of colorings have no monochromatic , above the guarantee . The union bound is pessimistic because it counts colorings with multiple cliques more than once.
- Above it, they become rare but not impossible. With , and the argument no longer guarantees anything; still, more than 40% of colorings are good. The method gives a bound, not the exact value.
- Randomness falls far short. With , and practically no random coloring avoids the . But one exists, Paley’s: edge is red if is a square modulo 17. Try , which with the recurrence gives the exact value.
The probabilistic method proves a good coloring exists without saying which. For large this remains true: almost all colorings of with are good, yet no explicit construction is known achieving an exponential bound with . The gap between and remains open more than seventy years later: the lower bound has improved only by a constant factor (Spencer, 1975, asymptotically doubled Erdős’s using the Lovász local lemma), and the upper bound’s exponential base from 4 to .
Implementation from scratch: verifiable certificates
Implement each result in the lesson to return its certificate, and write an independent verifier that checks it without trusting the algorithm. This is the right way to test combinatorial optimization code: the algorithm may be intricate, but the verifier is simple enough to inspect.
The central piece is alternating search. It receives roots (free vertices of ) and returns the first free position found with parents to reconstruct the path, or None with everything reached. flip flips the augmenting path, and hall_or_violator turns the proof of Hall’s theorem into code.
from collections import deque
import random, itertools
def alternating_search(adj, roots, match_x, match_y):
"""BFS alternante desde roots (en X): fuera de M hacia Y, por M de vuelta a X.
Devuelve (y libre o None, parent: y -> x desde el que se alcanzó, X alcanzados)."""
parent, seen_x = {}, set(roots)
queue = deque(roots)
while queue:
x = queue.popleft()
for y in adj[x]:
if y in parent:
continue
parent[y] = x
if y not in match_y:
return y, parent, seen_x
x2 = match_y[y] # se vuelve a X por la arista de M
if x2 not in seen_x:
seen_x.add(x2)
queue.append(x2)
return None, parent, seen_x
def flip(y, parent, match_x, match_y):
"""Invierte el camino aumentante que termina en el puesto libre y."""
while True:
x = parent[y]
prev = match_x.get(x) # el puesto que x deja libre
match_x[x], match_y[y] = y, x
if prev is None: # x era la raíz, libre
return
y = prev
def hall_or_violator(adj, X):
"""('emparejamiento', M) con M: x -> y que satura X, o ('violador', S) con |N(S)| < |S|."""
match_x, match_y = {}, {}
for root in X:
y, parent, seen_x = alternating_search(adj, [root], match_x, match_y)
if y is None:
return "violador", seen_x # N(S) = Y alcanzados, emparejados con S − {root}
flip(y, parent, match_x, match_y)
return "emparejamiento", match_x
def N(adj, S):
return set().union(*(adj[x] for x in S)) if S else set()
def verify(adj, X, kind, cert):
"""Verificador independiente: no usa nada del algoritmo."""
if kind == "emparejamiento":
ys = list(cert.values())
return set(cert) == set(X) and len(set(ys)) == len(ys) and all(cert[x] in adj[x] for x in X)
S = set(cert)
return bool(S) and S <= set(X) and len(N(adj, S)) < len(S)
cadena = {"A": [1, 2], "B": [2, 3], "C": [3, 4], "D": [4, 5], "E": [5, 6], "F": [1]}
cuello = {"A": [2, 5], "B": [1, 2, 3], "C": [2, 5], "D": [3, 4, 6], "E": [2, 5], "F": [1, 4, 6]}
for nombre, adj in [("cadena", cadena), ("cuello de botella", cuello)]:
kind, cert = hall_or_violator(adj, list(adj))
detalle = cert if kind == "emparejamiento" else f"S = {sorted(cert)}, N(S) = {sorted(N(adj, cert))}"
print(f"{nombre:18s} {kind}: {detalle} verificado: {verify(adj, list(adj), kind, cert)}")
rng = random.Random(0)
validos = acuerdo = 0
for _ in range(3000):
X = list(range(6))
adj = {x: sorted(rng.sample(range(6), rng.randint(0, 3))) for x in X}
kind, cert = hall_or_violator(adj, X)
validos += verify(adj, X, kind, cert)
hall = all(len(N(adj, S)) >= len(S) for r in range(1, 7) for S in itertools.combinations(X, r))
acuerdo += (kind == "emparejamiento") == hall
print(f"3000 grafos al azar: certificados válidos {validos}; coincide con la condición de Hall por fuerza bruta: {acuerdo}")The maximum matching and König cover come from the same two functions. On thousands of random bipartite graphs with sides of different sizes, check the three claims in the König section: that is a cover, that , and that the final violator has deficiency . Then use brute force on small nonbipartite graphs.
def maximum_matching(adj, X):
match_x, match_y = {}, {}
for root in X:
y, parent, _ = alternating_search(adj, [root], match_x, match_y)
if y is not None:
flip(y, parent, match_x, match_y)
return match_x, match_y
def konig(adj, X):
"""Emparejamiento máximo M, cubrimiento C = (X − Z) ∪ (Y ∩ Z) y violador S = X ∩ Z."""
match_x, match_y = maximum_matching(adj, X)
libres = [x for x in X if x not in match_x]
y, parent, ZX = alternating_search(adj, libres, match_x, match_y)
assert y is None, "quedaba un camino aumentante: M no era máximo"
C = {("x", x) for x in set(X) - ZX} | {("y", y) for y in parent}
return match_x, C, ZX
def is_cover(adj, C):
return all(("x", x) in C or ("y", y) in C for x in adj for y in adj[x])
ok = 0
for _ in range(3000):
nx_, ny_ = rng.randint(1, 8), rng.randint(1, 8)
X = list(range(nx_))
adj = {x: sorted(rng.sample(range(ny_), rng.randint(0, min(3, ny_)))) for x in X}
M, C, S = konig(adj, X)
ok += is_cover(adj, C) and len(C) == len(M) and len(S) - len(N(adj, S)) == len(X) - len(M)
print(f"König en 3000 bipartitos al azar: {ok} certificados correctos")
M, C, S = konig(cuello, list(cuello))
print("cuello de botella: |M| =", len(M), " C =", sorted(C), " S =", sorted(S))
def nu_tau(n, edges):
"""Fuerza bruta: emparejamiento máximo y cubrimiento mínimo de un grafo cualquiera."""
nu = max(r for r in range(len(edges) + 1) for F in itertools.combinations(edges, r)
if len({v for e in F for v in e}) == 2 * r)
tau = min(r for r in range(n + 1) for C in itertools.combinations(range(n), r)
if all(u in C or v in C for u, v in edges))
return nu, tau
for nombre, n, E in [("triángulo", 3, [(0, 1), (1, 2), (0, 2)]), ("C5", 5, [(i, (i + 1) % 5) for i in range(5)]),
("C6", 6, [(i, (i + 1) % 6) for i in range(6)]), ("K4", 4, list(itertools.combinations(range(4), 2)))]:
nu, tau = nu_tau(n, E)
print(f"{nombre:10s} ν = {nu}, τ = {tau} {'(König se cumple)' if nu == tau else '(König falla: no es bipartito)'}")Now coloring. greedy colors in a given order, dsatur chooses the most saturated vertex at each step, and smallest_last constructs degeneracy order. To measure them we need exact , computed on small graphs by backtracking that breaks color symmetry (vertex can introduce only the next new color, never skip one).
def greedy(adj, order):
color = {}
for v in order:
usados = {color[w] for w in adj[v] if w in color}
c = 1
while c in usados:
c += 1
color[v] = c
return color
def dsatur(adj):
color = {}
while len(color) < len(adj):
v = max((u for u in adj if u not in color),
key=lambda u: (len({color[w] for w in adj[u] if w in color}), len(adj[u]), -u))
usados = {color[w] for w in adj[v] if w in color}
c = 1
while c in usados:
c += 1
color[v] = c
return color
def smallest_last(adj):
deg, quedan, orden = {v: len(adj[v]) for v in adj}, set(adj), []
while quedan:
v = min(quedan, key=lambda u: (deg[u], u))
orden.append(v)
quedan.remove(v)
for w in adj[v]:
if w in quedan:
deg[w] -= 1
return orden[::-1] # se colorea en orden inverso al de eliminación
def chromatic(adj):
vs = sorted(adj, key=lambda v: -len(adj[v]))
def can(k):
col = {}
def bt(i, usados):
if i == len(vs):
return True
v = vs[i]
for c in range(1, min(k, usados + 1) + 1):
if all(col.get(w) != c for w in adj[v]):
col[v] = c
if bt(i + 1, max(usados, c)):
return True
del col[v]
return False
return bt(0, 0)
return next(k for k in range(1, len(adj) + 1) if can(k))
def is_proper(adj, color):
return all(color[u] != color[v] for u in adj for v in adj[u])
def crown(n):
adj = {v: [] for v in range(2 * n)}
for i in range(n):
for j in range(n):
if i != j:
adj[i].append(n + j)
adj[n + j].append(i)
return adj
print(" n | u1 v1 u2 v2 ... | un lado y otro | DSatur | último de menor grado")
for n in range(3, 9):
adj = crown(n)
alterno = [v for i in range(n) for v in (i, n + i)]
cols = [max(greedy(adj, alterno).values()), max(greedy(adj, range(2 * n)).values()),
max(dsatur(adj).values()), max(greedy(adj, smallest_last(adj)).values())]
print(f"{n:2d} | {cols[0]:15d} | {cols[1]:14d} | {cols[2]:6d} | {cols[3]:21d}")
def gnp(n, p, r):
adj = {v: [] for v in range(n)}
for u, v in itertools.combinations(range(n), 2):
if r.random() < p:
adj[u].append(v)
adj[v].append(u)
return adj
exceso = {"voraz, orden al azar": [], "DSatur": [], "último de menor grado": []}
for _ in range(150):
adj = gnp(12, 0.35, rng)
chi = chromatic(adj)
orden = list(adj)
rng.shuffle(orden)
for nombre, col in [("voraz, orden al azar", greedy(adj, orden)), ("DSatur", dsatur(adj)),
("último de menor grado", greedy(adj, smallest_last(adj)))]:
assert is_proper(adj, col)
exceso[nombre].append(max(col.values()) - chi)
print("\n150 grafos G(12, 0.35):")
for nombre, ex in exceso.items():
print(f" {nombre:22s} óptima en el {sum(e == 0 for e in ex) / len(ex):.0%}, colores de más: media {sum(ex) / len(ex):.2f}, máximo {max(ex)}")The crown table matches the interactive, now up to : alternating order uses colors and the other three strategies use 2. On random graphs, greedy with a random order succeeds about half the time, and DSatur almost always, though neither guarantees anything.
For planarity, the “no” certificate computable from what we have seen is the girth bound. Girth is obtained by breadth-first search from every vertex: the first edge closing a cycle from gives a cycle of length , and the minimum over all is exact.
def girth(adj):
mejor = float("inf")
for s in adj:
dist, par, q = {s: 0}, {s: None}, deque([s])
while q:
u = q.popleft()
for w in adj[u]:
if w not in dist:
dist[w], par[w] = dist[u] + 1, u
q.append(w)
elif par[u] != w: # arista que cierra un ciclo
mejor = min(mejor, dist[u] + dist[w] + 1)
return mejor
def euler_certifica_no_planar(adj):
V, E, g = len(adj), sum(map(len, adj.values())) // 2, girth(adj)
if g == float("inf") or V < 3:
return False, V, E, g, None # un bosque siempre es planar
cota = g * (V - 2) / (g - 2)
return E > cota, V, E, g, cota
def from_edges(n, edges):
adj = {v: [] for v in range(n)}
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return adj
K33_edges = [(a, b) for a in range(3) for b in range(3, 6)]
grafos = {
"K5": from_edges(5, itertools.combinations(range(5), 2)),
"K3,3": from_edges(6, K33_edges),
"Petersen": from_edges(10, [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)]
+ [(5 + i, 5 + (i + 2) % 5) for i in range(5)]),
"K3,3 + arista": from_edges(6, K33_edges + [(0, 1)]),
"cubo": from_edges(8, [(i, (i + 1) % 4) for i in range(4)] + [(4 + i, 4 + (i + 1) % 4) for i in range(4)]
+ [(i, i + 4) for i in range(4)]),
}
for nombre, adj in grafos.items():
no, V, E, g, cota = euler_certifica_no_planar(adj)
print(f"{nombre:14s} V = {V:2d} E = {E:2d} g = {g} cota = {cota:5.2f} -> {'NO planar (certificado)' if no else 'la cota no decide'}")The cube is on the bound, : all its faces are squares. “K3,3 + edge” reminds us that the bound does not decide every case; that requires Kuratowski, which we will use through networkx.
Finally, Ramsey. For each , the table compares the greatest with , the simplified version , the deletion method, and the upper bound. Deletion improves the argument: take a coloring with (one exists because not all can be above the mean) and remove one vertex from each monochromatic ; at least vertices remain without any and, since their number is an integer, at least . Thus for every , and the table takes the best . Then simulate the interactive and verify Paley’s coloring.
from math import comb, floor, ceil
import matplotlib.pyplot as plt
def umbral_erdos(k):
n = k
while comb(n + 1, k) * 2 ** (1 - comb(k, 2)) < 1:
n += 1
return n
def borrado(k):
"""Mejor cota del borrado: R(k, k) > ⌈n − E[X]⌉, maximizando en n."""
return max(ceil(n - comb(n, k) * 2 ** (1 - comb(k, 2))) for n in range(k, 20 * 2 ** (k // 2)))
print(" k | E[X] < 1 hasta | ⌊2^(k/2)⌋ | borrado | cota superior C(2k−2, k−1)")
ks = list(range(3, 13))
for k in ks:
print(f"{k:2d} | {umbral_erdos(k):14d} | {floor(2 ** (k / 2)):9d} | {borrado(k):7d} | {comb(2 * k - 2, k - 1):10d}")
def mono_count(n, k, rojo):
return sum(len({rojo[u][v] for u, v in itertools.combinations(A, 2)}) == 1
for A in itertools.combinations(range(n), k))
def coloracion_al_azar(n, r):
rojo = [[None] * n for _ in range(n)]
for u, v in itertools.combinations(range(n), 2):
rojo[u][v] = rojo[v][u] = r.random() < 0.5
return rojo
for n, k in [(6, 4), (7, 4), (10, 4)]:
xs = [mono_count(n, k, coloracion_al_azar(n, rng)) for _ in range(1500)]
EX = comb(n, k) * 2 ** (1 - comb(k, 2))
print(f"n = {n:2d}, k = {k}: E[X] = {EX:.3f}, media = {sum(xs) / len(xs):.3f}, "
f"P(X = 0) ≈ {xs.count(0) / len(xs):.3f}, garantía 1 − E[X] = {max(0.0, 1 - EX):.3f}")
cuadrados = {x * x % 17 for x in range(1, 17)}
paley = [[(v - u) % 17 in cuadrados if u != v else None for v in range(17)] for u in range(17)]
print(f"Paley 17: cuadrados = {sorted(cuadrados)}; K4 de un solo color = {mono_count(17, 4, paley)}; "
f"al azar se esperarían {comb(17, 4) * 2 ** -5:.1f}")
fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.semilogy(ks, [umbral_erdos(k) + 1 for k in ks], "o-", label="inferior: E[X] < 1")
ax.semilogy(ks, [borrado(k) + 1 for k in ks], "s--", label="inferior: borrado")
ax.semilogy(ks, [comb(2 * k - 2, k - 1) for k in ks], "^-", label="superior: C(2k−2, k−1)")
ax.semilogy([3, 4], [6, 18], "k*", ms=12, label="valor exacto")
ax.vlines(5, 43, 46, colors="k", lw=3, label="R(5, 5) ∈ [43, 46]")
ax.set_xlabel("k"); ax.set_ylabel("R(k, k) (escala log)")
ax.set_title("Lo que se sabe de R(k, k): un hueco exponencial")
ax.legend(fontsize=8); plt.tight_layout(); plt.show()The simulation reproduces the interactive, and the table shows two facts worth reading carefully. First, exact condition is much better than its simplification: for it gives 231 versus 64. Second, deletion never loses, because at the threshold and , and from onward it wins by increasing margins: for , 276 versus 231. Even so, it improves the bound only by a constant factor, asymptotically. In the plot, lower and upper bounds are nearly straight lines with different slopes on a logarithmic scale, versus , and the few known exact values fall between them.
The professional version
networkx implements all of the above. The important thing is knowing what each function does and its pitfalls, for which the verifiers you just wrote are the perfect tool.
| Function | What it does | Watch out for |
|---|---|---|
bipartite.hopcroft_karp_matching(G, top_nodes) | maximum matching in , several augmenting paths per phase | returns a dictionary in both directions: its size is |
bipartite.to_vertex_cover(G, M, top_nodes) | König cover from a maximum matching | if is not maximum, the cover is not minimum and no longer certifies anything |
nx.greedy_color(G, strategy) | greedy coloring with an order: largest_first, smallest_last, DSATUR… | all are greedy; none guarantees |
nx.check_planarity(G, counterexample=True) | linear planarity test (left-right) | returns a plane embedding or Kuratowski subgraph |
import networkx as nx
from networkx.algorithms import bipartite
import time
# 1. Emparejamiento y cubrimiento de König: networkx frente al nuestro
r = random.Random(1)
for n in (150, 300):
adj = {i: sorted(r.sample(range(n), 3)) for i in range(n)}
top = [("x", i) for i in range(n)]
B = nx.Graph()
B.add_nodes_from(top, bipartite=0)
B.add_nodes_from((("y", j) for j in range(n)), bipartite=1)
B.add_edges_from((("x", i), ("y", j)) for i in adj for j in adj[i])
t0 = time.perf_counter(); M_hk = bipartite.hopcroft_karp_matching(B, top_nodes=top)
t1 = time.perf_counter(); C_nx = bipartite.to_vertex_cover(B, M_hk, top_nodes=top)
t2 = time.perf_counter(); M, C, S = konig(adj, list(range(n)))
t3 = time.perf_counter()
print(f"n = {n}: ν = {len(M_hk) // 2} (Hopcroft-Karp, {1e3 * (t1 - t0):.0f} ms) = {len(M)} (nuestro); "
f"|C| = {len(C_nx)} con to_vertex_cover en {1e3 * (t2 - t1):.0f} ms, nuestro König en {1e3 * (t3 - t2):.0f} ms")
# 2. Estrategias de greedy_color en la corona, con los vértices en el orden alterno
G = nx.Graph()
n = 20
G.add_nodes_from(v for i in range(n) for v in (f"u{i}", f"v{i}"))
G.add_edges_from((f"u{i}", f"v{j}") for i in range(n) for j in range(n) if i != j)
for s in ["largest_first", "smallest_last", "connected_sequential_bfs", "DSATUR"]:
col = nx.greedy_color(G, strategy=s)
print(f"corona n = {n}, {s:25s} {max(col.values()) + 1:2d} colores")
# 3. Planaridad con certificado en los dos sentidos
for nombre, H in [("Petersen", nx.petersen_graph()), ("K3,3 + arista", nx.Graph(K33_edges + [(0, 1)]))]:
planar, cert = nx.check_planarity(H, counterexample=True)
grados = sorted(d for _, d in cert.degree())
print(f"{nombre}: planar = {planar}; subgrafo de Kuratowski con {cert.number_of_edges()} aristas, grados {grados}")
H = nx.triangular_lattice_graph(3, 4)
planar, emb = nx.check_planarity(H)
vistas, F = set(), 0
for u, v in emb.edges(): # cada cara es una órbita de medias aristas
if (u, v) not in vistas:
emb.traverse_face(u, v, mark_half_edges=vistas)
F += 1
V, E = H.number_of_nodes(), H.number_of_edges()
print(f"red triangular: planar = {planar}; V = {V}, E = {E}, F = {F}, V − E + F = {V - E + F}")Three observations. First, largest_first, the default strategy of greedy_color, uses 20 colors on the crown because all degrees are equal and tie-breaking respects insertion order, which is alternating. Ordering by degree does not protect against the trap. Second, Petersen’s Kuratowski subgraph has six vertices of degree 3 and three of degree 2: it is a subdivision of , the one highlighted in the interactive. Third, to_vertex_cover gives the correct cover, but its cost grows much faster than our construction, a single breadth-first search: compare times when doubling . If you need König covers on large graphs, use the twenty-line version from the previous section.
Common mistakes
Exercises
More than one answer may be correct.
hall_certificate(G, X, Y). G is a dictionary assigning each candidate in X the list of its neighbors in Y (which may be empty). Return ('matching', M), with M a candidate → position dictionary saturating X, or ('violator', S), with S a set of candidates such that . The tests verify the certificate you return rather than comparing it with a fixed answer.def hall_certificate(G, X, Y):
# para cada candidato libre, busca un camino alternante hasta un puesto libre;
# si no existe, los candidatos alcanzados forman el conjunto violador
passSummary
- Matchings. A matching is maximum if and only if there is no augmenting path (Berge). In bipartite graphs, alternating search finds a path or gets stuck at a set with : this proves Hall, for every , and the maximum deficiency is what the best matching lacks.
- König. In bipartite graphs, , and cover comes from the same search. This is linear programming duality with integer solutions; it fails on a triangle.
- Coloring. , with Brooks reducing this to except for complete graphs and odd cycles. Greedy depends on order (on the crown, colors versus 2), an optimal order always exists, and DSatur and smallest-last are good heuristics without a general guarantee.
- Planarity. in a connected plane graph; hence , without triangles, and , , and Petersen are nonplanar. Kuratowski characterizes planarity, every planar graph has a vertex of degree , and 5 colors suffice (Kempe and Heawood). Four colors required a computer in 1976 and Coq in 2005.
- Ramsey. by the pigeonhole principle, so ; and because if some coloring has . An exponential gap between the two bounds remains open.