Module contents
Lesson 10 of 23Advanced 110 min

Structure and constraint programming: trees, global constraints and CP-SAT

Constraint-graph structure determines complexity: tree CSPs are solved without backtracking and general difficulty grows exponentially only in treewidth. This lesson studies efficiently filtered global constraints, conflict-directed backjumping, min-conflicts local search, symmetry breaking and professional modeling with CP-SAT.

After this lesson you can

  • Solve tree-structured CSPs without backtracking and exploit cycle cutsets, bucket elimination and tree decompositions.
  • Implement alldifferent filtering using bipartite matchings.
  • Explain conflict-directed backjumping and nogood learning as precursors to CDCL.
  • Apply min-conflicts and recognize CSPs on which local search fails.
  • Model scheduling problems in CP-SAT with native constraints and symmetry breaking.

Before you start

Motivation: structure decides

Deciding whether a finite-domain CSP has a solution is NP-complete: graph coloring is already NP-complete with three colors. Yet constraint solvers schedule real workshops, timetables and shifts daily, and in this lesson CP-SAT proves in seconds the optimum of a workshop that resisted for twenty-six years. There is no contradiction. NP-completeness concerns the worst case over all instances; real instances have structure, and the previous lesson (modeling, propagation and backtracking) exploited part of it: arc consistency prunes domains and maintaining consistency during search avoids dead branches.

This lesson goes further in four directions, all sharing the idea that blind search is the last resort.

  1. Graph shape. If the constraint graph is a tree, two linear passes solve the problem without backtracking. Otherwise exact inference cost grows exponentially in one number, treewidth, rather than the number of variables.
  2. Meaningful constraints. Saying “these 16 squares are all different” in one constraint permits reasoning over all 16 together using bipartite matchings, pruning what 120 binary inequalities miss.
  3. Learning from failure. When a branch dies, the cause is often far away. Jumping directly to it and remembering it is the idea that became CDCL in SAT.
  4. Giving up systematic search. For large problems with many solutions, repairing a complete assignment is remarkably effective: a million queens in about 50 moves.

The lesson closes with practice: how to model a scheduling problem in Google’s OR-Tools CP-SAT solver and read its output.

Tree CSPs: two passes and no backtracking

Start with the most favorable case. A binary CSP is tree-structured if its constraint graph is a tree: connected and acyclic (equivalently, connected with n−1n - 1 edges, or with a unique path between each pair of vertices; review tree characterizations). Choose a root and order variables so each follows its parent, for example breadth-first. That order is a linear extension of the “ancestor of” partial order.

This is half of arc consistency: support is required only forward, from each variable in later ones. One backward pass achieves it: for j=n,n−1,…,2j = n, n - 1, \dots, 2, revise each earlier neighbor XiX_i of XjX_j against XjX_j, deleting from DiD_i values unsupported in DjD_j. When XiX_i is revised against XjX_j, XjX_j‘s domain is already final, because only domains of variables earlier than the one processed change. Thus one pass suffices.

In a tree ordered from the root, each non-root variable has exactly one earlier neighbor, its parent. Pass 1 revises each parent against each child, leaves to root; pass 2 assigns root to leaves, choosing any value compatible with the parent’s for each variable.

The proof is a three-line induction you will reconstruct in the final guided exercise. Complexity follows by counting: there are n−1n - 1 edges and each revision compares at most d×dd \times d pairs. Compared with exhaustive search’s dnd^n, the tree makes an exponential problem linear.

InteractiveTwo passes on a tree
|a−b|≥2|a−b|=1≡ mód 2>a+b=5<a+b=5X₁11234X₂21234X₃31234X₄41234X₅51234X₆61234X₇71234X₈81234
step 32 / 32 · pass 2
  • value pruned by directional consistency
  • assigned value
  • constraint closing the cycle
  • edge label: a is the upper variable and b the lower
  • the small number beside each variable is its position in the order
Graph
Variable order
Order width1
Values pruned in pass 16
Dead ends up to this step0 (of 0 total)
Constraint checks in pass 215
Tree with root-first order: width 1, the theorem guarantees zero dead ends. Solution with 0 dead ends.
An 8-variable CSP with domains in {1,2,3,4}\{1, 2, 3, 4\} and a constraint on each tree edge read top to bottom: the edge from X2X_2 to X5X_5 says x2>x5x_2 > x_5. Step through both passes in root order: the first crosses out in red values unsupported by the child, the second assigns without a single dead end. Then switch to leaf order or add the dashed edge x4>x6x_4 > x_6, closing a cycle, and replay: how many dead ends appear and at which variable?

With root order, pass 1 prunes 6 values and pass 2 assigns all 8 variables with zero dead ends. The figure’s two experiments show that both theorem assumptions matter:

  • Order. From leaves, each parent has two earlier neighbors, its children, already assigned by its turn. Arc consistency guarantees each child’s value has support in the parent, but not that two children have a common support. This instance has 7 dead ends. Freuder gives the minimal example: two-coloring a binary tree is arc-consistent, but if postorder colors two siblings differently, the parent has no possible color.
  • Cycles. Edge x4>x6x_4 > x_6 gives X6X_6 two earlier neighbors, X3X_3 and X4X_4. The directional pass still prunes but no longer suffices: 3 dead ends.

Freuder stated the result generally. An order’s width is the maximum, over variables, of their number of earlier neighbors; graph width is the minimum over all orders. His theorem 1 says that if the strong-consistency level exceeds order width, search in that order never backtracks; theorem 3 says a connected graph has width 1 if and only if it is a tree. On a tree, arc consistency (strong level-2 consistency) suffices. Width ww would need strong consistency at level w+1w + 1, and achieving it may add constraints increasing width: bucket elimination, two sections below, resolves this vicious circle.

Implementation from scratch

The cell implements both passes and compares them with simple backtracking on 400 random trees with varied relations. It then measures checks on increasingly large trees.

[ ]Two passes on random treesBrowser
import random, time

def revise(D, x, y, ok):
    """Quita de D[x] los valores sin apoyo en D[y]; ok(a, b) dice si x = a, y = b es compatible."""
    quitados = [a for a in D[x] if not any(ok(a, b) for b in D[y])]
    for a in quitados:
        D[x].remove(a)
    return len(quitados)

def resolver_arbol(n, dominios, padre, rel):
    """CSP binario cuyo grafo es un árbol con raíz 0. padre[j] es el padre de j (padre[0] = None) y
    rel[j](a, b) la restricción entre padre[j] = a y j = b. Devuelve (asignación o None, comprobaciones)."""
    D = [list(d) for d in dominios]
    orden = [0]                                   # orden topológico desde la raíz (BFS)
    for x in orden:
        orden += [j for j in range(n) if padre[j] == x]
    comprobaciones = 0
    for j in reversed(orden[1:]):                 # pasada 1: de las hojas a la raíz
        p = padre[j]
        comprobaciones += len(D[p]) * len(D[j])
        revise(D, p, j, rel[j])
        if not D[p]:
            return None, comprobaciones
    valor = {}
    for x in orden:                               # pasada 2: de la raíz a las hojas, sin retroceso
        p = padre[x]
        candidatos = [b for b in D[x] if p is None or rel[x](valor[p], b)]
        comprobaciones += len(D[x])
        assert candidatos, "callejón sin salida: el teorema dice que es imposible"
        valor[x] = candidatos[0]
    return valor, comprobaciones

def satisfacible(n, dominios, restr):
    """Backtracking simple, para contrastar. restr: lista de (u, v, ok)."""
    val = {}
    def bt(i):
        if i == n:
            return True
        for a in dominios[i]:
            val[i] = a
            if all(ok(val[u], val[v]) for u, v, ok in restr if max(u, v) == i):
                if bt(i + 1):
                    return True
        del val[i]
        return False
    return bt(0)

RELS = [lambda a, b: a < b, lambda a, b: a != b, lambda a, b: abs(a - b) == 1,
        lambda a, b: (a + b) % 3 == 0, lambda a, b: a >= b + 2]
rnd = random.Random(0)
n, d, total, sat = 12, 4, 400, 0
for _ in range(total):
    padre = [None] + [rnd.randrange(j) for j in range(1, n)]   # árbol aleatorio con raíz 0
    rel = [None] + [rnd.choice(RELS) for _ in range(1, n)]
    dominios = [rnd.sample(range(d), rnd.randint(2, d)) for _ in range(n)]
    sol, _ = resolver_arbol(n, dominios, padre, rel)
    restr = [(padre[j], j, rel[j]) for j in range(1, n)]
    assert (sol is not None) == satisfacible(n, dominios, restr)
    if sol is not None:
        sat += 1
        assert all(r(sol[u], sol[v]) for u, v, r in restr) and all(sol[x] in dominios[x] for x in range(n))
print(f"{total} árboles aleatorios con n = {n}, d = {d}: {sat} satisfacibles; el algoritmo de dos pasadas")
print("coincide siempre con el backtracking y nunca encuentra un callejón sin salida")

# coste lineal en n: árboles aleatorios de ≠ con d = 10 (cada padre entre los 3 anteriores)
for n in [10, 100, 1000, 10000]:
    padre = [None] + [rnd.randrange(max(0, j - 3), j) for j in range(1, n)]
    rel = [None] + [lambda a, b: a != b] * (n - 1)
    dominios = [list(range(10))] * n
    sol, comp = resolver_arbol(n, dominios, padre, rel)
    print(f"n = {n:5d}: {comp:8d} comprobaciones = {comp / n:.1f} por variable")

The pass-2 assert never fires, and the 96 satisfiable instances of 400 are exactly those backtracking declares satisfiable. Checks per variable stabilize at d2+d=110d^2 + d = 110: cost is linear in nn, as the theorem promises.

Cycle-cutset conditioning

Almost no real problem is a tree, but many are nearly trees. Russell and Norvig’s Australia map is the textbook example: fixing South Australia’s color, which touches every other mainland region, leaves a chain.

If ∣S∣=c\abs{S} = c, there are at most dcd^c cutset assignments and each forest costs O((n−c)d2)\bigO((n - c)d^2), totaling O(dc(n−c)d2)\bigO(d^c (n - c) d^2): exponential only in cutset size. Finding the minimum cutset is the NP-hard feedback vertex set problem, but any cutset works and greedy heuristics give reasonable ones.

[ ]Cycle-cutset conditioningBrowser
import itertools, random

def corte_de_ciclos(n, aristas):
    """Heurística voraz: quita vértices de grado máximo del 2-núcleo hasta que no quedan ciclos."""
    vivos, corte = set(range(n)), []
    while True:
        nucleo = set(vivos)                       # 2-núcleo: borrar repetidamente vértices de grado <= 1
        cambio = True
        while cambio:
            cambio = False
            for v in list(nucleo):
                if sum(1 for a, b in aristas if v in (a, b) and {a, b} <= nucleo) <= 1:
                    nucleo.discard(v); cambio = True
        if not nucleo:
            return corte                          # lo que queda es un bosque
        v = max(nucleo, key=lambda v: sum(1 for a, b in aristas if v in (a, b) and {a, b} <= nucleo))
        corte.append(v); vivos.discard(v)

def resolver_bosque(vars_, D, aristas):
    """Dos pasadas en cada árbol del bosque inducido por vars_ (restricciones ≠)."""
    vecinos = {v: [] for v in vars_}
    for a, b in aristas:
        if a in vecinos and b in vecinos:
            vecinos[a].append(b); vecinos[b].append(a)
    D = {v: list(D[v]) for v in vars_}
    valor, comprob = {}, 0
    vistos = set()
    for r in vars_:
        if r in vistos:
            continue
        orden, padre = [r], {r: None}; vistos.add(r)
        for x in orden:
            for y in vecinos[x]:
                if y not in vistos:
                    vistos.add(y); padre[y] = x; orden.append(y)
        for j in reversed(orden[1:]):             # pasada 1
            p = padre[j]; comprob += len(D[p]) * len(D[j])
            D[p] = [a for a in D[p] if any(a != b for b in D[j])]
            if not D[p]:
                return None, comprob
        for x in orden:                           # pasada 2
            p = padre[x]
            valor[x] = next(b for b in D[x] if p is None or b != valor[p])
    return valor, comprob

def condicionamiento(n, D, aristas, corte):
    """Recorre TODAS las asignaciones del corte y cuenta cuántas se extienden a una solución."""
    resto = [v for v in range(n) if v not in corte]
    vec = {v: set() for v in range(n)}
    for u, v in aristas:
        vec[u].add(v); vec[v].add(u)
    probadas = comprob = buenas = 0
    primera = None
    for asign in itertools.product(*[D[c] for c in corte]):
        a = dict(zip(corte, asign))
        if any(a[u] == a[v] for u, v in aristas if u in a and v in a):
            continue                              # el corte ya es inconsistente
        probadas += 1
        D2 = {v: [x for x in D[v] if all(x != a[u] for u in vec[v] if u in a)] for v in resto}
        if any(not D2[v] for v in resto):
            continue
        sol, c = resolver_bosque(resto, D2, aristas)
        comprob += c
        if sol is not None:
            buenas += 1
            primera = primera or {**a, **sol}
    return primera, probadas, buenas, comprob

rnd = random.Random(7)
n, d = 40, 3
aristas = [(rnd.randrange(j), j) for j in range(1, n)]          # un árbol aleatorio...
while len(aristas) < n - 1 + 12:                                 # ...más 12 aristas que cierran ciclos
    a, b = sorted(rnd.sample(range(n), 2))
    if (a, b) not in aristas:
        aristas.append((a, b))
D = {v: list(range(d)) for v in range(n)}
for v in rnd.sample(range(n), 15):                               # algunos dominios recortados
    D[v] = rnd.sample(range(d), 2)
corte = corte_de_ciclos(n, aristas)
sol, probadas, buenas, comprob = condicionamiento(n, D, aristas, sorted(corte))
c = len(corte)
print(f"n = {n}, d = {d}, {len(aristas)} aristas; corte de ciclos de tamaño c = {c}: {sorted(corte)}")
print(f"asignaciones del corte: d^c = {d**c}; consistentes entre sí: {probadas}; se extienden a solución: {buenas}")
print("solución válida:", sol is not None and all(sol[u] != sol[v] for u, v in aristas) and all(sol[v] in D[v] for v in range(n)))
print(f"comprobaciones: {comprob}; cota d^c (n - c) d^2 = {d**c * (n - c) * d**2}; d^n = {d**n:.2e}")

A graph of 40 vertices with 12 independent cycles reduces to a cutset of 5 variables. Of its 35=2433^5 = 243 assignments, 108 are mutually consistent and 76 extend to a solution, and total checks (9194) are well below the 76 545 bound because many domains are reduced. The contrast with 340≈1.2×10193^{40} \approx 1.2\times 10^{19} is the point: the exponential part depends on how many vertices must be removed to break cycles, not problem size.

Bucket elimination and treewidth

Cycle cutsets pay dcd^c even when cycles are far apart. The alternative is to infer rather than condition: eliminate variables one by one, summarizing everything an eliminated variable imposed on neighbors in a new constraint.

Bucket elimination

Fix an order X1,…,XnX_1, \dots, X_n and place each constraint in the bucket of its latest variable. Process buckets from XnX_n to X1X_1. XiX_i’s bucket contains constraints on XiX_i and earlier variables; join them in a relation over their joint scope SiS_i and project out XiX_i: the resulting relation on Si∖{Xi}S_i \setminus \{X_i\} contains exactly those combinations admitting some value of XiX_i compatible with the whole bucket. The new relation goes to its latest variable’s bucket. This is Dechter and Pearl’s (1987) adaptive consistency, presented by Dechter (1999) as bucket elimination, the same scheme used to marginalize graphical models (variable elimination).

Afterward, assign from X1X_1 to XnX_n looking only at each variable’s bucket constraints, with no dead ends: by construction every surviving earlier-value combination admits an extension. What changes from trees is cost. Projecting XiX_i makes the new constraint connect all its earlier neighbors, equivalent to adding edges among them in the graph. The resulting graph, with those fill edges, is the order’s induced graph.

Proof

The scope SiS_i of XiX_i‘s bucket consists of XiX_i and its earlier neighbors in the induced graph, hence ∣Si∣≤w∗(o)+1\abs{S_i} \le w^*(o) + 1. Computing the join enumerates at most d∣Si∣d^{\abs{S_i}} tuples of SiS_i and checks each bucket constraint; each constraint, original or generated, is in exactly one bucket, and there are at most r+nr + n, giving the time bound. Each generated relation has scope size at most w∗(o)w^*(o) and thus at most dw∗(o)d^{w^*(o)} tuples, and one is generated per bucket. Correctness follows from projection: a tuple of Si∖{Xi}S_i \setminus \{X_i\} enters the new relation iff it extends to XiX_i satisfying all bucket constraints, so after processing XiX_i‘s bucket the problem has the same solutions, restricted to X1,…,Xi−1X_1, \dots, X_{i-1}, as the original.

∎

Thus complexity depends on order, and the best possible order yields a graph parameter:

Two classical facts connect the pieces. First, treewidth equals minimum induced width across all orders: an elimination order yields bags {Xi}∪{vecinas anteriores de Xi}\{X_i\} \cup \{\text{vecinas anteriores de } X_i\} forming a decomposition, and conversely eliminating decomposition leaves gives an order of the same width. Second, trees with at least one edge are exactly connected graphs of treewidth 1, where bucket elimination is the directional pass above. Dechter and Pearl’s (1989) tree clustering uses the decomposition directly: each bag becomes a metavariable whose domain is the bag’s consistent tuples (at most dtw⁡+1d^{\operatorname{tw}+1}), and the metavariable CSP is a tree solved by two passes.

The order remains to be chosen. Computing treewidth is NP-hard (Arnborg, Corneil and Proskurowski, 1987), although for fixed kk one can decide in linear time whether it is at most kk (Bodlaender, 1996), with constants making it impractical except for very small kk. Practice uses greedy orders:

  • min-degree: eliminate the variable with fewest remaining neighbors first.
  • min-fill: eliminate the variable whose removal creates fewest fill edges first.
InteractiveElimination orders and width
a1b2c3d4efghi
  • graph edge
  • fill edge
  • neighbors of the last eliminated vertex: its bucket
  • red number: position in elimination order
Graph
When selecting a vertex
Your ordera → b → c → d
Degrees at elimination2, 3, 3, 3
Width so far3
Fill edges6
min-degree · min-fill · treewidth3 · 3 · 3
Eliminating d left 3 neighbors: its bucket produces a constraint on 3 variables and adds 2 fill edges.
Click vertices in your chosen elimination order. Each elimination joins all remaining neighbors (dashed fill edges), and its degree then is the size of the constraint its bucket creates; order width is the maximum degree. Compare your order with min-degree, min-fill and the optimum, computed exactly by dynamic programming. Can you reach width 2 on the grid? In the ‘min-degree trap’ graph, which local choice spoils it? Use ‘Edit edges’ to build your own graphs.

On grid 3×33\times 3 no order goes below 3, its treewidth: grid k×kk\times k has treewidth kk, so exact inference in grid-structured models (images, the Ising model) is infeasible except on narrow grids. On the trap graph, min-degree with ties broken by smallest index gives width 4 and min-fill optimal width 3. Heuristic width is always an upper bound on treewidth, never necessarily its value; the exact number requires exponential search.

[ ]Bucket elimination on a 4×4 gridBrowser
import itertools, random

def eliminacion_por_cubos(dominios, restricciones, orden):
    """Consistencia adaptativa (Dechter y Pearl): restricciones = lista de (ámbito, conjunto de tuplas
    permitidas). Procesa los cubos del último al primero de `orden`. Devuelve los cubos (o None si es
    insatisfacible) y estadísticas de coste."""
    pos = {x: k for k, x in enumerate(orden)}
    cubos = {x: [] for x in orden}
    for alc, tuplas in restricciones:
        cubos[max(alc, key=pos.get)].append((tuple(alc), tuplas))
    anchura = enumeradas = mayor_tabla = 0
    for x in reversed(orden):
        if not cubos[x]:
            continue
        ambito = sorted({v for alc, _ in cubos[x] for v in alc}, key=pos.get)   # x es el último
        anchura = max(anchura, len(ambito) - 1)
        resto = ambito[:-1]
        nueva = set()
        for t in itertools.product(*[dominios[v] for v in ambito]):          # unión (join)...
            enumeradas += 1
            a = dict(zip(ambito, t))
            if all(tuple(a[v] for v in alc) in tuplas for alc, tuplas in cubos[x]):
                nueva.add(t[:-1])                                            # ...y proyección: se olvida x
        if not nueva:
            return None, anchura, enumeradas, mayor_tabla
        if resto:
            mayor_tabla = max(mayor_tabla, len(nueva))
            cubos[max(resto, key=pos.get)].append((tuple(resto), nueva))
    return cubos, anchura, enumeradas, mayor_tabla

def asignar(cubos, dominios, orden):
    """Pasada hacia delante: cada variable solo mira las restricciones de su cubo. Cuenta callejones."""
    a, callejones = {}, 0
    for x in orden:
        buenos = [v for v in dominios[x]
                  if all(tuple({**a, x: v}[u] for u in alc) in tuplas for alc, tuplas in cubos[x])]
        if not buenos:
            callejones += 1
            return None, callejones
        a[x] = buenos[0]
    return a, callejones

# CSP aleatorio sobre una rejilla 4x4, d = 3, cada restricción permite 6 de los 9 pares
rnd = random.Random(1)
k, d = 4, 3
V = [(i, j) for i in range(k) for j in range(k)]
dominios = {v: list(range(d)) for v in V}
aristas = [((i, j), (i, j + 1)) for i in range(k) for j in range(k - 1)] + \
          [((i, j), (i + 1, j)) for i in range(k - 1) for j in range(k)]
restricciones = [((a, b), set(rnd.sample(list(itertools.product(range(d), repeat=2)), 6))) for a, b in aristas]

ordenes = {
    "por filas": V,
    "en zigzag": [(i, j) for j in range(k) for i in (range(k) if j % 2 == 0 else reversed(range(k)))],
    "aleatorio": rnd.sample(V, len(V)),
    "centro primero": sorted(V, key=lambda v: (min(v[0], k - 1 - v[0]) + min(v[1], k - 1 - v[1]), v), reverse=True),
}
for nombre, orden in ordenes.items():
    cubos, w, enum, tabla = eliminacion_por_cubos(dominios, restricciones, orden)
    if cubos is None:
        print(f"{nombre:18s} anchura inducida {w}: insatisfacible"); continue
    sol, callejones = asignar(cubos, dominios, orden)
    ok = all((sol[a], sol[b]) in t for (a, b), t in restricciones)
    print(f"{nombre:18s} anchura inducida {w}: {enum:6d} tuplas enumeradas, mayor tabla nueva {tabla:3d}, "
          f"solución correcta: {ok}, callejones: {callejones}")

All four orders find a correct solution without a dead end, as the theorem guarantees; the price differs. Row and zigzag orders have induced width 4, the treewidth of grid 4×44\times 4, and enumerate 2658 tuples; random and center-first reach width 6, enumerate 6006 and 4926 tuples and generate tables up to 369 and 324 tuples versus 72 and 81. With d=3d = 3 the difference is a factor of 2; each unit of width multiplies by dd, so with d=10d = 10 and widths 4 versus 6 it would be on the order of 100. Treewidth as a general parameter of exact inference returns with treewidth and the junction tree in probabilistic models.

Global constraints: alldifferent and matchings

Change perspective. So far constraints were binary. Many natural constraints concern many variables at once: “all different,” “at every instant total consumption is within capacity,” “yy is the xx-th element of this list.” They can be decomposed into binaries, but information is lost.

The canonical example is alldifferent⁡(x1,…,xn)\operatorname{alldifferent}(x_1, \dots, x_n). Its decomposition is the (n2)\binom{n}{2} constraints xi≠xjx_i \neq x_j, and arc consistency on a binary ≠\neq prunes only when one variable has a singleton domain: if ∣Dj∣≥2\abs{D_j} \ge 2, every value of xix_i has support in xjx_j. Now consider x1,x2∈{1,2}x_1, x_2 \in \{1, 2\} and x3∈{1,2,3}x_3 \in \{1, 2, 3\}. No binary ≠\neq prunes anything, but x1x_1 and x2x_2 share {1,2}\{1, 2\} between them, so x3=3x_3 = 3. With four variables in {1,2,3}\{1, 2, 3\} the problem is impossible (the pigeonhole principle), which binaries do not detect without search. The general argument is Hall’s theorem: if a set of kk variables has a domain union of size exactly kk (a Hall set), those values are reserved for them.

The value graph

Régin (1994) turned this intuition into an exact algorithm. The constraint’s value graph is bipartite, with variables on one side, values on the other, and an edge (xi,a)(x_i, a) for each a∈Dia \in D_i. An assignment satisfying alldifferent is exactly a matching covering all variables. Hence:

Proof

The first equivalence is the definition: a support of xi=ax_i = a is an assignment with all values distinct, i.e. a matching covering variables and containing (xi,a)(x_i, a). For the second, let M′M' be another matching covering variables and containing (xi,a)(x_i, a). Symmetric difference M⊕M′M \oplus M' is a disjoint union of cycles and paths alternating edges of MM and M′M' (each vertex touches at most one edge of each). Since MM and M′M' cover the same variables, no path can end at a variable touching only one, so paths have even length and endpoints are values, one free in MM and one free in M′M'. Edge (xi,a)∈M′∖M(x_i, a) \in M' \setminus M lies on an alternating cycle or one such path. In the directed graph, traversing an alternation goes from value to variable along a free edge and variable to value along one in MM, so an alternating cycle is directed (endpoints are in the same strongly connected component) and an even path from a free MM value is a directed path from that value. Conversely, if (xi,a)(x_i, a) lies on a directed cycle or path beginning at a free value, swapping MM edges and free edges along it gives another matching still covering variables and containing (xi,a)(x_i, a). This is Berge’s lemma, cited by Régin as property 1.

∎

The algorithm follows: a maximum matching with Hopcroft-Karp in O(mn)\bigO(m\sqrt{n}), with m=∑i∣Di∣m = \sum_i \abs{D_i} edges; if it does not cover the variables, the constraint fails. Otherwise Tarjan’s strongly connected components and a search from free values, both in O(n+m)\bigO(n + m), classify every edge at once. Prune those not in MM, a cycle, or a path from a free value. Régin bounds the worst case of maintaining consistency while deleting edges one at a time by O(p2d2)\bigO(p^2 d^2) for a constraint over pp variables with domains of size dd, versus generic generalized consistency enumerating tuples.

InteractiveAlldifferent as matching
x₁x₂x₃x₄x₅x₆1234567
D1234567
x₁
x₂
x₃
x₄
x₅
x₆
  • in the matching
  • on an even alternating cycle (same strongly connected component)
  • on an even alternating path from a free value
  • in no matching covering the variables: pruned
  • free value
Example
Maximum matching6 of 6 variables
Values pruned by alldifferent (Régin)3
Values pruned by AC on binary ≠0
Free values (unmatched)7
Régin prunes 3 value(s) (x4x_4: 2; x5x_5: 3, 4). Arc consistency on binary ≠ prunes 0.
Variables above, values below, one edge per domain value. Thick: a maximum matching; aqua: edges in an alternating cycle; orange: edges on an alternating path from a free value; dashed red: edges in no matching covering variables, pruned. The initial example is Régin's figure 2: no binary inequality prunes anything and alldifferent prunes three values. Remove values in the table, enable orientation to follow cycles and try the pigeonhole and sudoku row.

In Régin’s example, x1,x2,x3x_1, x_2, x_3 form a Hall set over {1,2,3}\{1, 2, 3\}: the matching covers them with edges forming an alternating cycle, and all their values survive. Conversely (x4,2)(x_4, 2) and (x5,3)(x_5, 3), (x5,4)(x_5, 4) are on no cycle or path from free value 7, so are pruned: x4=4x_4 = 4, x5∈{5,6}x_5 \in \{5, 6\} and x6∈{6,7}x_6 \in \{6, 7\} remain. In the sudoku row filtering chains several Hall sets ({x1,x3}\{x_1, x_3\} over {1,2}\{1, 2\}, then {x1,x2,x3}\{x_1, x_2, x_3\} over {1,2,3}\{1, 2, 3\}) and fixes x2=3x_2 = 3, x5=4x_5 = 4 and x4=5x_4 = 5 without search, while binary inequalities prune nothing.

Two more global constraints

  • cumulative(s,p,c,C)(s, p, c, C): tasks with starts sis_i, durations pip_i and consumption cic_i of a resource with capacity CC; at every instant, total consumption of active tasks is at most CC. It generalizes NoOverlap (capacity 1, consumption 1) and is filtered using edge-finding and energetic reasoning, deducing that a task cannot start before a time because energy available in a window is insufficient. It was introduced in CHIP (Aggoun and Beldiceanu, 1993).
  • element(x,[t0,…,tk−1],y)(x, [t_0, \dots, t_{k-1}], y): y=txy = t_x, indexing a table with a variable. Filtering keeps in DxD_x only indices ii with ti∈Dyt_i \in D_y, and in DyD_y only tit_i with i∈Dxi \in D_x. This expresses choice-dependent costs such as setup time between jobs.

Lab: Régin filtering with networkx

The implementation uses networkx for Hopcroft-Karp matching and strongly connected components, and is checked against brute force.

[ ]Régin filtering with networkxBrowser
import itertools, random
import networkx as nx
from networkx.algorithms import bipartite

def regin(dominios):
    """Filtrado de alldifferent (Régin, 1994). dominios: dict variable -> conjunto de valores.
    Devuelve el conjunto de pares (x, v) que no están en ningún emparejamiento que cubra las variables,
    o None si no existe tal emparejamiento (la restricción falla)."""
    X = [("x", x) for x in dominios]
    G = nx.Graph()
    G.add_nodes_from(X)
    G.add_edges_from((("x", x), ("v", v)) for x, D in dominios.items() for v in D)
    M = bipartite.hopcroft_karp_matching(G, top_nodes=X)
    if any(x not in M for x in X):
        return None
    # grafo orientado: emparejadas de variable a valor, libres de valor a variable
    R = nx.DiGraph()
    R.add_nodes_from(G)
    for x, D in dominios.items():
        for v in D:
            if M[("x", x)] == ("v", v):
                R.add_edge(("x", x), ("v", v))
            else:
                R.add_edge(("v", v), ("x", x))
    comp = {u: k for k, c in enumerate(nx.strongly_connected_components(R)) for u in c}
    libres = [u for u in G if u[0] == "v" and u not in M]
    alcanzable = set(libres)
    for u in libres:
        alcanzable |= nx.descendants(R, u)
    return {(x, v) for x, D in dominios.items() for v in D
            if M[("x", x)] != ("v", v)                       # no está en el emparejamiento,
            and comp[("x", x)] != comp[("v", v)]             # ni en un ciclo alternante par,
            and ("v", v) not in alcanzable}                  # ni en un camino par desde un valor libre

def regin_fuerza_bruta(dominios):
    xs = list(dominios)
    soporte = {(x, t[i]) for t in itertools.product(*[sorted(dominios[x]) for x in xs])
               if len(set(t)) == len(t) for i, x in enumerate(xs)}
    if not soporte:
        return None
    return {(x, v) for x in xs for v in dominios[x]} - soporte

ejemplo = {1: {1, 2}, 2: {2, 3}, 3: {1, 3}, 4: {2, 4}, 5: {3, 4, 5, 6}, 6: {6, 7}}   # figura 2 de Régin
print("podados en el ejemplo de Régin:", sorted(regin(ejemplo)))

rnd = random.Random(0)
for _ in range(300):
    n = rnd.randint(2, 6)
    dom = {x: set(rnd.sample(range(7), rnd.randint(1, 4))) for x in range(n)}
    assert regin(dom) == regin_fuerza_bruta(dom), dom
print("300 casos aleatorios: coincide con la fuerza bruta")

Now integrate it into a consistency-maintaining solver: the previous lesson’s MAC scheme with minimum remaining values first (MRV) and two interchangeable propagators. The binary ≠\neq propagator enforces arc consistency, which for ≠\neq removes a fixed cell’s value from all its peers. The alldifferent propagator runs regin on each affected row, column or box to a fixed point. The 16×1616\times 16 sudokus are generated by permuting a valid pattern and emptying 150 of 256 cells.

[ ]16×16 sudokus: binary inequalities versus alldifferentBrowser
import random, time

def unidades_sudoku(B):
    N = B * B
    filas = [[(r, c) for c in range(N)] for r in range(N)]
    cols = [[(r, c) for r in range(N)] for c in range(N)]
    cajas = [[(br * B + i, bc * B + j) for i in range(B) for j in range(B)] for br in range(B) for bc in range(B)]
    U = filas + cols + cajas
    de = {}
    for k, u in enumerate(U):
        for x in u:
            de.setdefault(x, []).append(k)
    return U, de

def propagar(D, U, de, modo, pendientes):
    """modo 'ne': consistencia de arco sobre las ≠ binarias (solo actúan los dominios unitarios).
    modo 'alldiff': filtrado de Régin en cada unidad afectada. pendientes: celdas que han cambiado."""
    if modo == "ne":
        pila = [x for x in pendientes if len(D[x]) == 1]
        while pila:
            x = pila.pop()
            (a,) = D[x]
            for k in de[x]:
                for y in U[k]:
                    if y != x and a in D[y]:
                        D[y] = D[y] - {a}
                        if not D[y]:
                            return False
                        if len(D[y]) == 1:
                            pila.append(y)
        return True
    cola = {k for x in pendientes for k in de[x]}
    while cola:
        k = cola.pop()
        podar = regin({x: D[x] for x in U[k]})
        if podar is None:
            return False
        for x, a in podar:
            D[x] = D[x] - {a}
            cola.update(de[x])
    return True

def mac(D, U, de, modo, stats, limite):
    stats["nodos"] += 1
    if stats["nodos"] > limite:
        return None
    libres = [x for x in D if len(D[x]) > 1]
    if not libres:
        return D
    x = min(libres, key=lambda x: len(D[x]))           # MRV
    for a in sorted(D[x]):
        D2 = dict(D); D2[x] = {a}
        if propagar(D2, U, de, modo, [x]):
            r = mac(D2, U, de, modo, stats, limite)
            if r is not None:
                return r
    return None

def generar(B, huecos, semilla):
    """Sudoku resuelto por permutaciones de un patrón válido, con `huecos` celdas vaciadas al azar."""
    N, rnd = B * B, random.Random(semilla)
    base = lambda r, c: (B * (r % B) + r // B + c) % N
    digs = rnd.sample(range(N), N)
    filas = [b * B + i for b in rnd.sample(range(B), B) for i in rnd.sample(range(B), B)]
    cols = [b * B + i for b in rnd.sample(range(B), B) for i in rnd.sample(range(B), B)]
    sol = {(r, c): digs[base(filas[r], cols[c])] for r in range(N) for c in range(N)}
    vaciar = set(rnd.sample(sorted(sol), huecos))
    return {x: v for x, v in sol.items() if x not in vaciar}

def resolver(B, pistas, modo, limite=2000):
    N = B * B
    U, de = unidades_sudoku(B)
    D = {(r, c): {pistas[(r, c)]} if (r, c) in pistas else set(range(N)) for r in range(N) for c in range(N)}
    stats = {"nodos": 0}
    t = time.perf_counter()
    r = mac(D, U, de, modo, stats, limite) if propagar(D, U, de, modo, list(D)) else None
    return r, stats["nodos"], time.perf_counter() - t

for semilla in [0, 2]:
    pistas = generar(4, 150, semilla)
    (ok1, n1, t1), (ok2, n2, t2) = [(r is not None, nodos, dt) for r, nodos, dt in
                                    (resolver(4, pistas, modo) for modo in ["ne", "alldiff"])]
    print(f"16x16 con {256 - 150} pistas (semilla {semilla}): ≠ binarias: "
          f"{'resuelto en ' + str(n1) + ' nodos' if ok1 else 'sin resolver al llegar a 2000 nodos'}; "
          f"alldifferent: {'resuelto' if ok2 else 'sin resolver'} en {n2} nodos; "
          f"coste por nodo alldifferent / ≠: {(t2 / n2) / (t1 / n1):.0f}x")

In the first sudoku binary inequalities exhaust the 2000-node limit without solving it while alldifferent solves it in 21; in the second, 698 nodes versus 18. Each alldifferent node is far more expensive (the cell prints a ratio of two orders of magnitude, machine-dependent), but the search tree shrinks even more, and in practice the latter decides: node count for MAC with weak propagation has a heavy tail, and an early poor choice can cost thousands of nodes strong propagation never opens.

Conflict-directed backjumping and nogoods

Chronological backtracking returns to the immediately preceding variable at a dead end. If the cause lies much earlier, it repeatedly traverses the unrelated intervening part of the tree: thrashing.

The update makes chained jumps correct too. If xix_i fails, assignments to variables in conf⁡(xi)\operatorname{conf}(x_i) suffice to leave xix_i without values: no skipped variable can fix it, so skipping them loses no solutions. On reaching xhx_h and exhausting its values too, blame is shared between causes of xhx_h‘s failures and xix_i‘s, hence they are inherited. That partial assignment, {xk=vk:xk∈conf⁡(xi)}\{x_k = v_k : x_k \in \operatorname{conf}(x_i)\}, is a nogood: a combination belonging to no solution. CBJ uses it once and forgets it. Nogood learning stores it as a new constraint so search does not stumble over it in another branch.

[ ]Chronological versus conflict-directed backtrackingBrowser
import random, statistics

def buscar(n, D, ok, saltar):
    """Backtracking (saltar=False) o retroceso dirigido por conflictos de Prosser (saltar=True) para un CSP
    binario con orden fijo 0..n-1. ok[(h, i)](a, b) con h < i. Devuelve (solución o None, nodos, primer nogood)."""
    val, conf = [None] * n, [set() for _ in range(n)]
    restantes = [list(D[0])] + [None] * (n - 1)
    i, nodos, nogood = 0, 0, None
    while 0 <= i < n:
        consistente = False
        while restantes[i] and not consistente:
            val[i] = restantes[i].pop(0); nodos += 1
            consistente = True
            for h in range(i):                               # comprobar contra las anteriores, en orden
                if (h, i) in ok and not ok[(h, i)](val[h], val[i]):
                    conf[i].add(h); consistente = False; break
        if consistente:
            i += 1
            if i < n:
                restantes[i], conf[i] = list(D[i]), set()
            continue
        if not saltar:                                       # cronológico: a la anterior
            h = i - 1
        else:
            if not conf[i]:
                return None, nodos, nogood
            h = max(conf[i])                                 # la más profunda del conjunto conflicto
            if nogood is None and h < i - 1:
                nogood = {x: val[x] for x in sorted(conf[i])}
            if h >= 0:
                conf[h] |= conf[i] - {h}                     # hereda las causas del fallo
        for j in range(h + 1, i + 1):
            restantes[j], conf[j] = None, set()
        i = h
    return (list(val) if i == n else None), nodos, nogood

# 1) un conflicto lejano: x0 = 0 deja sin valores a x11, y entre medias una cadena de ≠ que no tiene que ver
n = 12
D = [[0, 1, 2]] * 11 + [[0]]
ok = {(i, i + 1): (lambda a, b: a != b) for i in range(1, 10)}
ok[(0, 11)] = lambda a, b: a != b
for saltar in (False, True):
    sol, nodos, nogood = buscar(n, D, ok, saltar)
    print(f"{'dirigido por conflictos' if saltar else 'cronológico':24s} nodos = {nodos:5d}   solución x0 = {sol[0]}"
          + (f"   primer salto aprende el nogood {nogood}" if saltar else ""))

# 2) CSP aleatorios: n = 15, d = 5, densidad 0.25 (probabilidad de cada restricción), estrechez 0.4 (pares prohibidos)
def aleatorio(n, d, p1, p2, rnd):
    ok = {}
    for h in range(n):
        for i in range(h + 1, n):
            if rnd.random() < p1:
                prohibidos = set(rnd.sample([(a, b) for a in range(d) for b in range(d)], round(p2 * d * d)))
                ok[(h, i)] = (lambda P: lambda a, b: (a, b) not in P)(prohibidos)
    return [list(range(d))] * n, ok

rnd = random.Random(4)
cocientes, sat = [], 0
for _ in range(25):
    D, ok = aleatorio(15, 5, 0.25, 0.4, rnd)
    s1, n1, _ = buscar(15, D, ok, False)
    s2, n2, _ = buscar(15, D, ok, True)
    assert (s1 is None) == (s2 is None)
    sat += s1 is not None
    cocientes.append(n1 / n2)
print(f"25 CSP aleatorios ({sat} satisfacibles): nodos cronológico / dirigido por conflictos: "
      f"mediana {statistics.median(cocientes):.1f}, mínimo {min(cocientes):.1f}, máximo {max(cocientes):.1f}")

In the constructed example chronological backtracking needs 6156 nodes: with x0=0x_0 = 0 it traverses every coloring of chain x1,…,x10x_1, \dots, x_{10} (there are 3⋅29=15363 \cdot 2^9 = 1536), each dying at x11x_{11}. CBJ needs 34: the first x11x_{11} failure has conflict set {x0}\{x_0\}, jumps straight there and learns nogood x0=0x_0 = 0. In the 25 random CSPs, all satisfiable, median savings are a factor of 22.8, with cases showing no gain (1.0) and others over a thousand: gain depends on distant conflicts, which random instances may or may not have.

Local search: min-conflicts

All previous methods are systematic: if a solution exists they find it, otherwise they prove none exists. The local search alternative starts with a complete assignment violating constraints and repairs it.

Minton and colleagues extracted it from Johnston and Adorf’s GDS neural network for scheduling Hubble Space Telescope observations: ten to thirty thousand observations per year, with orbital, power and stray-light constraints, and an earlier classical system that reportedly would have needed more than three weeks to schedule one. Their most famous result is different. With a greedy initial assignment placing each queen in order in its column’s square with fewest conflicts with earlier queens, mean repairs to solve nn queens were 57.0, 55.6, 48.8, 48.5, 52.8 and 48.3 for n=10,102,…,106n = 10, 10^2, \dots, 10^6 (their table 1, one hundred runs per size), and they solved one million queens in under four minutes on a SPARCstation 1. Backtracking with the most-constrained-variable heuristic, under the same 100 n100\,n move limit, failed to finish in 19 % of runs with n=1000n = 1000.

InteractiveOne million queens
  • queen (column, row), scaled
  • queen in conflict
Problem
1000
Initial assignment
0.00
Repair steps0
Queens in conflict: initial · current0 · 0
Solved in 0 steps with 1000 queens. The greedy assignment began with only 0 conflicting queens.
Live min-conflicts. Above, the board (one queen per column; conflicting queens in red), or for n>64n > 64 each queen's scaled position. Below, conflicting queens versus repairs. Press ‘Solve’ with n=1000n = 1000 then raise nn to 100 000: the curve barely changes. Compare random initialization. ‘Sweep n’ repeats Minton et al.'s experiment with 3 seeds per size. Then switch to sparse 3-coloring: with noise 0, does it reach zero conflicts? With noise 0.1?

The initial assignment explains the constant step count. Greedy leaves very few queens in conflict (Minton et al. measured a mean of 3.1 at n=10n = 10 to 12.8 at n=106n = 10^6), and nn-queens solutions are so numerous and spread out that one is always a few repairs away. Random initialization, by contrast, starts with on the order of 0.9 n0.9\,n queens in conflict and steps grow linearly with nn. Each repair costs O(n)\bigO(n) because the column’s nn rows must be inspected, and incremental row and diagonal counters make each query O(1)\bigO(1). With greedy initialization, repair costs on the order of 50 n50\,n operations total: linear, as Minton et al. observe. The expensive part becomes greedy initialization itself, which brute-force checks nn rows per column: O(n2)\bigO(n^2).

Sparse 3-coloring is the opposite. The graph has a planted coloring, so it is satisfiable, but solutions are scarce and separated by barriers. With mean degree 3 and no noise, the method quickly descends to a strict local minimum with a few conflicting vertices: each already has its unique conflict-minimizing color, no step changes anything and it remains forever (the figure detects this and stops). With mean degree 4 it sometimes reaches a strict minimum, other times wanders a plateau of sideways moves without improvement for 20 000 steps. Minton et al. warn that the method is “less effective” coloring sparsely connected graphs, and their analysis shows error probability grows with distance to a solution. Some noise (with probability pp, a random value instead of the best) permits escape. This is the idea behind WalkSAT and simulated annealing.

Lab: min-conflicts with incremental structures

[ ]Min-conflicts for n queensBrowser
import random, time
import numpy as np

class Reinas:
    """n reinas, la reina i en la columna i y la fila q[i]. Contadores incrementales: cuántas reinas hay en
    cada fila y en cada diagonal (r + i) y antidiagonal (r - i + n - 1). Conflictos de la casilla (r, i):
    filas[r] + d1[r + i] + d2[r - i + n - 1], todo O(1). Se guardan como listas (acceso escalar rápido)
    y como arrays de NumPy (barridos de una columna entera en O(n) vectorizado)."""

    def __init__(self, n, semilla, voraz=True, muestras=256):
        self.n, self.rnd = n, random.Random(semilla)
        self.F, self.D1, self.D2 = np.zeros(n, np.int32), np.zeros(2 * n, np.int32), np.zeros(2 * n, np.int32)
        self.q = np.zeros(n, np.int64)
        f, d1, d2 = [0] * n, [0] * (2 * n), [0] * (2 * n)
        self.barridos = 0
        for i in range(n):
            o, r = n - 1 - i, -1
            if voraz:      # voraz de Minton et al.: fila de menos conflictos con las ya colocadas, empates al azar
                for _ in range(muestras):           # la primera fila libre muestreada es uniforme entre las libres
                    x = self.rnd.randrange(n)
                    if f[x] == 0 and d1[x + i] == 0 and d2[x + o] == 0:
                        r = x; break
                if r < 0:                           # no hay (o no la encontramos): barrido completo
                    self.barridos += 1
                    r = self.mejor_fila(i)
            else:
                r = self.rnd.randrange(n)
            f[r] += 1; d1[r + i] += 1; d2[r + o] += 1
            self.poner(i, r)

    def poner(self, i, r):
        self.q[i] = r; self.F[r] += 1; self.D1[r + i] += 1; self.D2[r - i + self.n - 1] += 1

    def quitar(self, i):
        r = self.q[i]; self.F[r] -= 1; self.D1[r + i] -= 1; self.D2[r - i + self.n - 1] -= 1

    def mejor_fila(self, i):
        o = self.n - 1 - i
        c = self.F + self.D1[i:i + self.n] + self.D2[o:o + self.n]
        cand = np.flatnonzero(c == c.min())
        return int(cand[self.rnd.randrange(len(cand))])

    def en_conflicto(self):
        i = np.arange(self.n)
        return np.flatnonzero(self.F[self.q] + self.D1[self.q + i] + self.D2[self.q - i + self.n - 1] > 3)

def min_conflicts(R, max_pasos=100_000):
    inicial = len(R.en_conflicto())
    for paso in range(max_pasos):
        malas = R.en_conflicto()
        if len(malas) == 0:
            return paso, inicial
        i = int(malas[R.rnd.randrange(len(malas))])   # una reina en conflicto al azar
        R.quitar(i)
        R.poner(i, R.mejor_fila(i))                   # a la fila de menos conflictos
    return None, inicial

for n in [10, 100, 1000, 10000]:
    filas = []
    for semilla in range(5):
        pasos, ini = min_conflicts(Reinas(n, semilla))
        filas.append((pasos, ini))
    al = [min_conflicts(Reinas(n, s, voraz=False)) for s in range(3)] if n <= 1000 else None
    print(f"n = {n:6d}: voraz -> pasos {[p for p, _ in filas]}, en conflicto al empezar {[c for _, c in filas]}"
          + (f"\n            aleatoria -> pasos {[p for p, _ in al]}, en conflicto al empezar {[c for _, c in al]}" if al else ""))

Two implementation details. Exact greedy traverses nn rows per column, O(n2)\bigO(n^2) total, which at n=105n = 10^5 already gives 101010^{10} operations. Here rows are sampled randomly until a conflict-free one is found; only if 256 attempts fail is the full traversal performed. This is not an approximation: the first free row found in uniform sampling is uniform among free rows, so its distribution exactly matches greedy with random tie-breaking. Worst case remains quadratic, but only the last columns, when few free rows remain, need a full scan (2.4 % in the 10510^5-queens cell). The number of conflicting queens is recomputed each step with NumPy, in vectorized O(n)\bigO(n), which with a few hundred steps does not warrant incremental maintenance.

With greedy initialization steps stay between 0 and 121 at all sizes, with 0 to 16 initially conflicting queens. With random initialization they rise from around a hundred at n=100n = 100 to about 700 at n=1000n = 1000. Now the million scale, reduced to 10510^5 to fit in the browser:

[ ]One hundred thousand queensBrowser
t = time.perf_counter()
R = Reinas(100_000, semilla=0)
t_ini = time.perf_counter() - t
pasos, ini = min_conflicts(R)
print(f"n = 100 000: {ini} reinas en conflicto tras la voraz ({R.barridos} columnas necesitaron el barrido completo)")
print(f"resuelto en {pasos} reparaciones; la inicialización se llevó el {100 * t_ini / (time.perf_counter() - t):.0f} % del tiempo")
print("comprobación independiente: ¿solución?", len(set(R.q)) == R.n
      and len(set(R.q + np.arange(R.n))) == R.n and len(set(R.q - np.arange(R.n))) == R.n)

Six queens in conflict after greedy initialization, 2418 columns fully scanned and 37 repairs solve one hundred thousand queens. Almost all time goes into initialization: search itself is trivial when starting so close.

Symmetries and symmetry breaking

Many CSPs have symmetries: transformations mapping solutions to solutions and nonsolutions to nonsolutions. For nn queens, the square’s 8 symmetries (90°, 180° and 270° rotations, four reflections and identity); in coloring, k!k! color permutations; in a timetable, swapping two identical rooms. An unaware solver explores each space region as many times as the group size and pays that entire factor when proving unsatisfiability.

Proof

Every orbit is finite and lexicographic order total, so it has a minimum s∗\vb{s}^*. For every σ∈G\sigma \in G, σ(s∗)\sigma(\vb{s}^*) is in the same orbit, hence s∗≤lexσ(s∗)\vb{s}^* \le_{\text{lex}} \sigma(\vb{s}^*): the minimum satisfies all constraints and any subset. If another solution s\vb{s} in the orbit satisfies them all, since s∗=σ(s)\vb{s}^* = \sigma(\vb{s}) for some σ\sigma, we have s≤lexs∗\vb{s} \le_{\text{lex}} \vb{s}^*, and by minimality s=s∗\vb{s} = \vb{s}^*.

∎

Using the whole group can be expensive (some have exponentially many elements), so practice breaks a subset: no orbit is lost, only some symmetry remains. For interchangeable values such as colors, standard value precedence says color c+1c + 1 cannot be used before cc in variable order. Two alternatives to static constraints are dynamic symmetry breaking during search (such as SBDS, adding constraints on backtracking), or letting the solver detect symmetry, as CP-SAT presolve does.

[ ]Symmetries in n queensBrowser
def reinas(n, extra=None, valores=None, primera=False):
    """Backtracking columna a columna. extra(q) poda asignaciones parciales; valores: orden de las filas.
    Devuelve (soluciones, nodos)."""
    valores = valores or list(range(n))
    sols, nodos, q = [], 0, []
    usadas, d1, d2 = set(), set(), set()
    def bt(i):
        nonlocal nodos
        if i == n:
            sols.append(tuple(q)); return primera
        for r in valores:
            if r in usadas or r + i in d1 or r - i in d2:
                continue
            nodos += 1
            q.append(r)
            if extra is None or extra(q, n):
                usadas.add(r); d1.add(r + i); d2.add(r - i)
                if bt(i + 1):
                    return True
                usadas.discard(r); d1.discard(r + i); d2.discard(r - i)
            q.pop()
        return False
    bt(0)
    return sols, nodos

def simetrias(n):
    """Las 8 simetrías del cuadrado como funciones sobre casillas (columna, fila)."""
    m = n - 1
    return [lambda c, r: (c, r), lambda c, r: (r, m - c), lambda c, r: (m - c, m - r), lambda c, r: (m - r, c),
            lambda c, r: (m - c, r), lambda c, r: (c, m - r), lambda c, r: (r, c), lambda c, r: (m - r, m - c)]

def aplicar(g, q):
    casillas = sorted(g(c, r) for c, r in enumerate(q))       # vuelve a una reina por columna
    return tuple(r for _, r in casillas)

n = 8
sols, _ = reinas(n)
G = simetrias(n)
orbitas = {min(aplicar(g, s) for g in G) for s in sols}
lider = [s for s in sols if all(s <= aplicar(g, s) for g in G[1:])]      # restricciones lex-leader
print(f"{n} reinas: {len(sols)} soluciones, {len(orbitas)} órbitas, {len(lider)} cumplen lex-leader;",
      "una por órbita:", set(lider) == orbitas)

# dos simetrías rotas con su restricción lex-leader, que solo mira la primera componente distinta:
#   espejo horizontal r -> n-1-r:  q[0] < n-1-q[0]  (se decide en la primera columna)
#   espejo vertical   c -> n-1-c:  q[0] < q[n-1]    (no se decide hasta la última)
horizontal = lambda q, n: q[0] < n - 1 - q[0]
vertical = lambda q, n: len(q) < n or q[0] < q[-1]
n = 10
todas, nod = reinas(n)
for nombre, f in [("q[0] < n-1-q[0]", horizontal), ("q[0] < q[n-1]", vertical)]:
    rotas, nod_r = reinas(n, extra=f)
    print(f"n = {n}: {len(todas)} soluciones en {nod} nodos; con {nombre}: {len(rotas)} soluciones en {nod_r} nodos")

# la trampa: la heurística de valores y la rotura tiran en sentidos opuestos (primera solución)
print("nodos hasta la primera solución (sin romper / con q[0] < q[n-1]):")
for n in [8, 10, 12]:
    fila = []
    for nombre, vals in [("filas ascendentes", None), ("filas descendentes", list(range(n - 1, -1, -1)))]:
        _, a = reinas(n, valores=vals, primera=True)
        _, b = reinas(n, extra=vertical, valores=vals, primera=True)
        fila.append(f"{nombre} {a} / {b}")
    print(f"  n = {n}: " + ";  ".join(fila))

The 92 eight-queens solutions form 12 orbits, and exactly 12 satisfy all seven lex-leader constraints, one per orbit as the theorem says. Two symmetries broken separately on the ten-board show when breaking helps. Both retain 362 of 724 solutions, but horizontal reflection is decided in the first column and halves nodes (17 774 versus 35 538), whereas q0<qn−1q_0 < q_{n-1} is checked only on a full board and saves no nodes. The last part is the trap: with rows descending, search favors solutions with large q0q_0, exactly those excluded, and with n=12n = 12 it goes from 261 to 63 886 nodes to the first solution. Symmetry breaking should select as orbit representative the one the heuristic would find first.

Professional modeling with CP-SAT

CP-SAT, Google’s OR-Tools constraint solver, is a reference tool for these problems. Internally it combines constraint-programming propagation, SAT-solver clause learning (constraints are explained with clauses to learn from conflicts, called lazy clause generation), linear relaxations with cuts like an integer-programming solver, and a portfolio of parallel strategies. How SAT and theories fit together appears in the SMT lesson (DPLL(T)). Here the external view matters: the model.

Fisher and Thompson’s workshop

Job-shop scheduling is the classic benchmark: JJ jobs, each a sequence of operations with a machine and duration; each machine processes one operation at a time without interruption, and the goal is minimum makespan, the last operation’s finish time. Fisher and Thompson’s (1963) ft06 instance has 6 jobs and 6 machines. In CP-SAT each operation is an interval variable: an object with start, duration and end known to satisfy fin=inicio+duracioˊn\text{fin} = \text{inicio} + \text{duración}, acted on by scheduling constraints such as NoOverlap or Cumulative with specialized propagators.

[ ]ft06 with interval variablesLocal GPU
from ortools.sat.python import cp_model

# ft06 (Fisher y Thompson, 1963), formato de la OR-Library: por trabajo, pares (máquina, duración)
FT06 = """2 1 0 3 1 6 3 7 5 3 4 6
1 8 2 5 4 10 5 10 0 10 3 4
2 5 3 4 5 8 0 9 1 1 4 7
1 5 0 5 2 5 3 3 4 8 5 9
2 9 1 3 4 5 5 4 0 3 3 1
1 3 3 3 5 9 0 10 4 4 2 1"""

def leer(texto):
    trabajos = []
    for linea in texto.strip().splitlines():
        v = list(map(int, linea.split()))
        trabajos.append([(v[2 * k], v[2 * k + 1]) for k in range(len(v) // 2)])
    return trabajos

def modelo_intervalos(trabajos, simetrias=()):
    m = cp_model.CpModel()
    H = sum(p for ops in trabajos for _, p in ops)              # horizonte: todo en serie
    ini, fin, por_maquina = {}, {}, {}
    for j, ops in enumerate(trabajos):
        for k, (maq, p) in enumerate(ops):
            ini[j, k] = m.new_int_var(0, H, f"ini_{j}_{k}")
            fin[j, k] = m.new_int_var(0, H, f"fin_{j}_{k}")
            iv = m.new_interval_var(ini[j, k], p, fin[j, k], f"op_{j}_{k}")   # impone fin = ini + p
            por_maquina.setdefault(maq, []).append(iv)
            if k > 0:
                m.add(ini[j, k] >= fin[j, k - 1])                 # orden dentro del trabajo
    for ivs in por_maquina.values():
        m.add_no_overlap(ivs)                                     # una operación a la vez por máquina
    makespan = m.new_int_var(0, H, "makespan")
    m.add_max_equality(makespan, [fin[j, len(ops) - 1] for j, ops in enumerate(trabajos)])
    for a, b in simetrias:                                        # trabajos idénticos: a empieza antes que b
        m.add(ini[a, 0] <= ini[b, 0])
    m.minimize(makespan)
    return m, ini

def resolver(m, hilos=1, limite=60.0, semilla=0, **params):
    s = cp_model.CpSolver()
    s.parameters.num_workers = hilos
    s.parameters.max_time_in_seconds = limite
    s.parameters.random_seed = semilla
    for k, v in params.items():
        setattr(s.parameters, k, v)
    estado = s.solve(m)
    return s, s.status_name(estado)

ft06 = leer(FT06)
m, ini = modelo_intervalos(ft06)
s, estado = resolver(m)
print(f"ft06: {estado}, makespan = {s.objective_value:.0f}, cota demostrada = {s.best_objective_bound:.0f}")
print(f"ramas = {s.num_branches}, conflictos = {s.num_conflicts}")
print("inicios por trabajo:", [[s.value(ini[j, k]) for k in range(6)] for j in range(6)])
print("\n".join(l for l in s.response_stats().splitlines() if l.split(":")[0].strip() in
                ("status", "objective", "best_bound", "booleans", "conflicts", "branches", "propagations", "walltime")))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Read the output as follows. OPTIMAL means the solver has a solution and proof that none is better: the proven lower bound (best_bound) equals objective 55, ft06’s known optimum. If time runs out earlier, status is FEASIBLE and the distance between objective and bound is what you know about your solution, the gap. Branches and conflicts measure search: 214 branches and 3 conflicts show ft06 is trivial for this solver. booleans counts internal Boolean variables: 85, although the model declares none, because the solver creates them to reason with clauses over integers. To follow a long run, log_search_progress = True prints presolve, each new solution and bound evolution.

InteractiveThe ft06 workshop
0102030405060708090100M1M2M3M4M5M6J1J1J1J2J2J2J2J2J2J3J3J3J3J3J4J4J4J4J4J5J5J5J6J6J6 time

Makespan for each schedule: Optimum 55 · MWKR 67 · FIFO 68 · SPT 94 · LPT 86 · LWKR 96

  • J1
  • J2
  • J3
  • J4
  • J5
  • J6
  • makespan
  • optimum, 55
  • lower bound, 47
Schedule
Rows
Makespan55
Optimum · bound max(load, job)55 · 47
Excess over optimum0 %
Optimum (CP-SAT): schedule from the CP-SAT cell, proven optimal. Operations with thick borders form the critical path: delaying any delays completion.
Gantt chart of ft06: each row is a machine (or job), each bar an operation colored by job. The optimal schedule is the previous cell's output; the others are Giffler–Thompson active schedules using classical priority rules, computed live. Thick-bordered bars form the critical path. Compare rule makespans with optimum 55 and the trivial lower bound (the largest machine load or job duration): how much does a dispatch rule lose and where can you see it?

Dispatch rules build a schedule in one pass without search, and the best of five (most work remaining first, MWKR) gives 67, 22 % above optimum; the worst gives 96. Even the optimum misses the lower bound of 47, job J2’s duration: the gap from 47 to 55 is what search must prove.

Native constraints versus big-M

Those coming from integer linear programming may write the disjunction “either aa before bb, or bb before aa” using Boolean yy and large constant HH: sa+pa≤sb+H(1−y)s_a + p_a \le s_b + H(1 - y) and sb+pb≤sa+Hys_b + p_b \le s_a + H y. The cell compares this with the interval model on ft10, the 10×1010\times 10 instance Fisher and Thompson published in 1963 whose optimum, 930, was not proven until 1989 (Carlier and Pinson), and also runs it through HiGHS, an integer-programming solver, via SciPy.

[ ]Big-M versus NoOverlapLocal GPU
import time
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds

FT10 = """0 29 1 78 2 9 3 36 4 49 5 11 6 62 7 56 8 44 9 21
0 43 2 90 4 75 9 11 3 69 1 28 6 46 5 46 7 72 8 30
1 91 0 85 3 39 2 74 8 90 5 10 7 12 6 89 9 45 4 33
1 81 2 95 0 71 4 99 6 9 8 52 7 85 3 98 9 22 5 43
2 14 0 6 1 22 5 61 3 26 4 69 8 21 7 49 9 72 6 53
2 84 1 2 5 52 3 95 8 48 9 72 0 47 6 65 4 6 7 25
1 46 0 37 3 61 2 13 6 32 5 21 9 32 8 89 7 30 4 55
2 31 0 86 1 46 5 74 4 32 6 88 8 19 9 48 7 36 3 79
0 76 1 69 3 76 5 51 2 85 9 11 6 40 7 89 4 26 8 74
1 85 0 13 2 61 6 7 8 64 9 76 5 47 3 52 4 90 7 45"""
ft10 = leer(FT10)

def modelo_big_m(trabajos):
    """Lo que no hay que hacer: una booleana por par de operaciones de la misma máquina y dos desigualdades
    con una constante grande H que desactiva la que no toca."""
    m = cp_model.CpModel()
    H = sum(p for ops in trabajos for _, p in ops)
    ini, ops_m = {}, {}
    for j, ops in enumerate(trabajos):
        for k, (maq, p) in enumerate(ops):
            ini[j, k] = m.new_int_var(0, H, "")
            ops_m.setdefault(maq, []).append((j, k, p))
            if k > 0:
                m.add(ini[j, k] >= ini[j, k - 1] + ops[k - 1][1])
    for L in ops_m.values():
        for a in range(len(L)):
            for b in range(a + 1, len(L)):
                (j1, k1, p1), (j2, k2, p2) = L[a], L[b]
                y = m.new_bool_var("")                         # y = 1: la primera va antes
                m.add(ini[j1, k1] + p1 <= ini[j2, k2] + H * (1 - y))
                m.add(ini[j2, k2] + p2 <= ini[j1, k1] + H * y)
    mk = m.new_int_var(0, H, "makespan")
    for j, ops in enumerate(trabajos):
        m.add(mk >= ini[j, len(ops) - 1] + ops[-1][1])
    m.minimize(mk)
    return m

print("ft10: makespan óptimo conocido 930")
for hilos in (8, 1):
    for nombre, mod in [("intervalos + NoOverlap", modelo_intervalos(ft10)[0]), ("big-M", modelo_big_m(ft10))]:
        s, estado = resolver(mod, hilos=hilos, limite=60)
        print(f"  {hilos} hilo(s), {nombre:22s}: {estado:8s} makespan {s.objective_value:.0f}, cota {s.best_objective_bound:.0f}, "
              f"ramas {s.num_branches}, {s.wall_time:.1f} s")
print("restricciones de cada modelo:", len(modelo_intervalos(ft10)[0].proto.constraints), "frente a",
      len(modelo_big_m(ft10).proto.constraints))

# ¿qué hace el presolve con el big-M? Lo dice el registro de CP-SAT
s = cp_model.CpSolver()
s.parameters.num_workers = 1
s.parameters.log_search_progress = True
s.parameters.log_to_stdout = False
lineas = []
s.log_callback = lineas.append
s.solve(modelo_big_m(ft06))
print("registro del presolve con ft06 en big-M:")
print("\n".join("  " + l.strip() for l in "\n".join(lineas).splitlines() if "enforcement literal" in l or "num_relations" in l))

def big_m_highs(trabajos, limite):
    """El mismo big-M en un resolutor MIP (HiGHS, a través de SciPy)."""
    ops = [(j, k, maq, p) for j, o in enumerate(trabajos) for k, (maq, p) in enumerate(o)]
    pares = [(a, b) for a in range(len(ops)) for b in range(a + 1, len(ops)) if ops[a][2] == ops[b][2]]
    nS, nY = len(ops), len(pares)
    MK = nS + nY
    nv = MK + 1
    H = sum(o[3] for o in ops)
    idx = {(j, k): i for i, (j, k, _, _) in enumerate(ops)}
    filas, lb = [], []
    def fila(coefs, cota):
        r = np.zeros(nv)
        for i, c in coefs:
            r[i] += c
        filas.append(r)
        lb.append(cota)
    for j, o in enumerate(trabajos):
        for k in range(1, len(o)):
            fila([(idx[j, k], 1), (idx[j, k - 1], -1)], o[k - 1][1])
        fila([(MK, 1), (idx[j, len(o) - 1], -1)], o[-1][1])
    for t, (a, b) in enumerate(pares):
        fila([(b, 1), (a, -1), (nS + t, -H)], ops[a][3] - H)       # y = 1: a antes que b
        fila([(a, 1), (b, -1), (nS + t, H)], ops[b][3])            # y = 0: b antes que a
    A = np.array(filas)
    c = np.zeros(nv)
    c[MK] = 1
    cotas = Bounds(np.zeros(nv), np.r_[np.full(nS, H), np.ones(nY), H])
    integ = np.r_[np.zeros(nS), np.ones(nY), 0]
    relajacion = milp(c, constraints=LinearConstraint(A, lb, np.inf), bounds=cotas)
    t = time.perf_counter()
    r = milp(c, constraints=LinearConstraint(A, lb, np.inf), integrality=integ, bounds=cotas, options={"time_limit": limite})
    return relajacion.fun, r, time.perf_counter() - t

for nombre, tr in [("ft06", ft06), ("ft10", ft10)]:
    lp, r, dt = big_m_highs(tr, 60)
    print(f"HiGHS con big-M en {nombre}: relajación lineal {lp:.0f}; {'óptimo' if r.status == 0 else 'límite de tiempo'}, "
          f"mejor solución {r.fun:.0f}, cota {r.mip_dual_bound:.1f}, {r.mip_node_count} nodos, {dt:.1f} s")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The result is more nuanced than textbook advice; read it all.

  • Size. The interval model has 201 constraints (100 intervals, 90 precedences, 10 NoOverlap and the maximum); big-M has 1000, because each machine with 10 operations needs (102)=45\binom{10}{2} = 45 Booleans and 90 inequalities.
  • CP-SAT undoes big-M. With 8 threads both models prove optimum 930 in seconds. With one thread, in this run big-M finishes before intervals, with fewer branches (130 394 versus 162 379). The log explains: for ft06 presolve applies “extracted enforcement literal” 180 times, once per big-M inequality (2×6×(62)2 \times 6 \times \binom{6}{2}). It rewrites each sa+pa≤sb+H(1−y)s_a + p_a \le s_b + H(1 - y) as implication y⇒sa+pa≤sby \Rightarrow s_a + p_a \le s_b, the classical disjunctive model; thereafter single-thread search follows different paths depending on the starting model, sometimes better and sometimes worse. Repeat the cell with different seeds before drawing timing conclusions.
  • An integer-programming solver does not undo it. HiGHS solves ft06 in 128 nodes, but on ft10 reaches the 60 s limit with solution 1046 and bound 742.8, far from 930. The linear relaxation gives 47 on ft06 and 655 on ft10, exactly the longest job’s duration: with y=1/2y = 1/2 and large HH both inequalities hold simultaneously, so the relaxation ignores machines entirely and bounds must come from branching.

The practical lesson is not “big-M is slow in CP-SAT,” which this cell disproves, but that the native constraint expresses the intent, occupies a fraction of the size, extends effortlessly (optional intervals, Cumulative, setup times), and does not depend on a particular solver’s presolve recognizing the trick.

Workshop symmetries

ft06 has no obvious symmetries, so the experiment uses a workshop with two identical copies of each job: swapping all operations of two copies transforms schedules into schedules. Break this with the simplest lex-leader constraint, “copy aa starts before bb,” and compare with and without CP-SAT automatic symmetry detection (symmetry_level).

[ ]Symmetry breaking in CP-SATLocal GPU
# Simetría: un taller con dos copias de cada trabajo de ft06. Intercambiar todas las operaciones de dos
# copias transforma calendarios en calendarios: la rompemos con «la copia a empieza antes que la b».
doble = ft06 + ft06
pares = [(j, j + 6) for j in range(6)]
for nombre, sims, nivel in [("sin romper", (), 2), ("con ini[a,0] <= ini[b,0]", pares, 2),
                            ("sin romper, sin detección de simetrías", (), 0),
                            ("con ini[a,0] <= ini[b,0], sin detección", pares, 0)]:
    m, _ = modelo_intervalos(doble, simetrias=sims)
    s, estado = resolver(m, hilos=1, limite=120, symmetry_level=nivel)
    print(f"{nombre:42s}: {estado}, makespan {s.objective_value:.0f}, ramas {s.num_branches}, conflictos {s.num_conflicts}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All four variants prove the same optimum, 95. The breaking constraint reduces branches from 1703 to 901 and conflicts from 260 to 190. Disabling symmetry detection (symmetry_level = 0) changes nothing in this model, so the gain comes entirely from the explicit constraint. It is correct because the symmetry swaps two entire jobs: in each pair of symmetric schedules, one has copy aa starting no later than bb. Here << would also work, because both copies start on the same machine and never simultaneously; in general ≤\le is safe because a strict inequality would discard symmetry-fixed schedules.

Against custom backtracking

Finally, the comparison any honest lab asks for: a solver written from scratch. It is branch and bound over Giffler and Thompson’s (1960) active schedules, which always contain an optimum, using the simplest bound: what remains for each machine and job from when it becomes free.

[ ]Custom backtracking versus CP-SATLocal GPU
import random, time

def bb_taller(trabajos, limite=3_000_000):
    """Nuestro backtracking: ramificación y poda sobre calendarios activos (Giffler y Thompson, 1960).
    En cada nodo, la operación disponible de menor fin posible c* fija una máquina; se ramifica sobre las
    operaciones de esa máquina que pueden empezar antes de c*. Cota: lo que le queda a cada máquina y a cada
    trabajo desde el instante en que queda libre."""
    nJ, M = len(trabajos), 1 + max(m for o in trabajos for m, _ in o)
    rm0 = [sum(p for o in trabajos for m, p in o if m == k) for k in range(M)]
    rj0 = [sum(p for _, p in o) for o in trabajos]
    mejor, nodos = [sum(rj0) + 1], [0]
    def rec(sig, lj, lm, rm, rj, mk):
        nodos[0] += 1
        if nodos[0] > limite:
            return
        if max([mk] + [lm[k] + rm[k] for k in range(M)] + [lj[j] + rj[j] for j in range(nJ)]) >= mejor[0]:
            return
        disp = [j for j in range(nJ) if sig[j] < len(trabajos[j])]
        if not disp:
            mejor[0] = mk
            return
        ini = lambda j: max(lj[j], lm[trabajos[j][sig[j]][0]])
        js = min(disp, key=lambda j: (ini(j) + trabajos[j][sig[j]][1], j))
        ms, cs = trabajos[js][sig[js]][0], ini(js) + trabajos[js][sig[js]][1]
        for j in sorted((j for j in disp if trabajos[j][sig[j]][0] == ms and ini(j) < cs), key=ini):
            m, p = trabajos[j][sig[j]]
            s = ini(j)
            sig2, lj2, lm2, rm2, rj2 = sig[:], lj[:], lm[:], rm[:], rj[:]
            sig2[j] += 1
            lj2[j] = lm2[m] = s + p
            rm2[m] -= p
            rj2[j] -= p
            rec(sig2, lj2, lm2, rm2, rj2, max(mk, s + p))
    rec([0] * nJ, [0] * nJ, [0] * M, rm0, rj0, 0)
    return mejor[0], nodos[0], nodos[0] <= limite

rnd = random.Random(0)
instancias = [("ft06", ft06)] + [(f"aleatoria {n}x{n}", [[(m, rnd.randint(1, 99)) for m in rnd.sample(range(n), n)] for _ in range(n)])
                                 for n in (6, 7, 8)]
for nombre, tr in instancias:
    t = time.perf_counter()
    mk, nodos, completo = bb_taller(tr)
    dt = time.perf_counter() - t
    s, estado = resolver(modelo_intervalos(tr)[0], hilos=8, limite=60)
    print(f"{nombre:16s} backtracking propio: {'óptimo' if completo else 'sin terminar'} {mk} en {nodos} nodos ({dt:.1f} s) | "
          f"CP-SAT: {estado} {s.objective_value:.0f} en {s.wall_time:.2f} s")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On ft06 both reach 55, ours with 6814 nodes. In random instances with durations 1 to 99, our tree grows from 72 795 nodes with 6×66\times 6 to 1 752 535 with 7×77\times 7, and with 8×88\times 8 exhausts the three-million-node limit with a schedule of 766, while CP-SAT proves optimum 651 in a fraction of a second. The difference is not implementation (Python versus C++), which would give a constant factor, but reasoning: our bound considers each machine separately, while CP-SAT combines NoOverlap propagation, conflict learning and linear relaxations to prune trees ours must traverse.

Common mistakes

Exercises

ProofTrees do not backtrack
Prove: Let a binary CSP's constraint graph be a tree rooted at X1X_1, with variables ordered X1,…,XnX_1, \dots, X_n so each follows its parent, and suppose no domain is empty after directional arc consistency (from XnX_n to X2X_2, revising each parent against its child). Then assignment in that order, selecting for each variable a domain value compatible with those assigned, never reaches a dead end.
0
Induct on position: X1X_1 takes any value of nonempty D1D_1. Suppose X1,…,Xk−1X_1, \dots, X_{k-1} assigned without failure and consider XkX_k, k≥2k \ge 2, whose parent XpX_p, p<kp < k, has value aa.

Step 1 of 3. With which already assigned variables is XkX_k constrained?

NumericCycle-cutset cost
A CSP has n=50n = 50 variables with domains of size d=4d = 4 and a cycle cutset of size c=5c = 5. Using the cycle-cutset conditioning bound dc⋅(n−c)⋅d2d^c \cdot (n - c) \cdot d^2 (one forest solution per cutset assignment), how many checks are required at most?
NumericWidth of a long grid
The constraint graph is a grid with 3 rows and 8 columns (each variable constrained with neighbors above, below, left and right). You eliminate variables by rows: the first row left to right, then the second and third, joining remaining neighbors at each step. What is this elimination order's width, the greatest number of remaining neighbors of a variable when eliminated?
QuizModeling a timetable
Three subjects sharing a teacher must occupy distinct slots. Room availability gives A∈{1,2}A \in \{1, 2\}, B∈{1,2}B \in \{1, 2\} and C∈{1,2,3}C \in \{1, 2, 3\}. You model all-different using three binary ≠\neq constraints or one alldifferent, and propagate to a fixed point before searching. What happens?
QuizWhen min-conflicts works
Which statements about min-conflicts are correct?

More than one answer may be correct.

QuizWhere does it jump?
Search uses order x1,…,x6x_1, \dots, x_6. Variable x6x_6 runs out of values and its conflict set is {x2,x4}\{x_2, x_4\}; x4x_4's was {x1}\{x_1\}. What does conflict-directed backjumping do?
QuizWhat Régin prunes
Alldifferent over x1∈{1,2}x_1 \in \{1, 2\}, x2∈{1,2}x_2 \in \{1, 2\}, x3∈{2,3}x_3 \in \{2, 3\}, x4∈{1,3,4}x_4 \in \{1, 3, 4\}. Which values does Régin filtering remove?

More than one answer may be correct.

NumericOne per orbit
The 6-queens problem has 4 solutions; written as each column's queen row (rows 1 to 6), they are (2,4,6,1,3,5)(2, 4, 6, 1, 3, 5), (3,6,2,5,1,4)(3, 6, 2, 5, 1, 4), (4,1,5,2,6,3)(4, 1, 5, 2, 6, 3) and (5,3,1,6,4,2)(5, 3, 1, 6, 4, 2). If you add lex-leader constraints x≤lexσ(x)\vb{x} \le_{\text{lex}} \sigma(\vb{x}) for the 7 nontrivial board symmetries, how many solutions survive?
QuizSymmetry breaking that slows search
You add x1<xnx_1 < x_n to break left-right reflection and first-solution search rises from 300 to 60 000 nodes. Your heuristic chooses variable values largest first. What is the most likely diagnosis?
QuizModeling in CP-SAT
Operations with start sis_i (integer variable) and fixed duration pip_i share a machine. Which no-overlap formulation is appropriate in CP-SAT?
CodeFilter alldifferent using matchings
Implement podar_alldiff(dominios): it receives a list of sets (each variable domain) and returns the set of pairs (i, v) such that value v in variable i's domain occurs in no assignment with all values distinct, or None if no such assignment exists. Do this without enumerating assignments: maximum matching by augmenting paths and Régin edge classification (alternating cycles and paths from free values). Do not use networkx. Tests compare with brute force.
def podar_alldiff(dominios):
  """dominios: lista de conjuntos. Devuelve el conjunto de pares (i, v) que se podan, o None si no hay
  ninguna asignación con todos los valores distintos."""
  # 1) emparejamiento máximo (caminos de aumento); si no cubre todas las variables, devuelve None
  # 2) grafo orientado: variable -> su valor emparejado; valor -> variables que lo tienen sin emparejar
  # 3) una arista (i, v) fuera del emparejamiento sobrevive si v es alcanzable desde un valor libre,
  #    o si v es alcanzable desde la variable i (ciclo alternante)
  return set()
Shift+Enter to run

Summary

Key idea
A CSP’s difficulty is determined by structure rather than size: constraint-graph width, constraint semantics and solution density determine whether inference, strong propagation or repair suffices; exponential search remains when none of the three does.
  • A binary tree CSP is solved in O(nd2)\bigO(n d^2): directional arc consistency from leaves to root, then root-to-leaf assignment without backtracking (Freuder). Order and acyclicity are essential.
  • Cycle-cutset conditioning costs O(dc(n−c)d2)\bigO(d^c (n - c) d^2); bucket elimination costs O((n+r) dw∗+1)\bigO((n + r)\, d^{w^* + 1}) with w∗w^* the order’s induced width. Its minimum over orders is treewidth, NP-hard to compute; min-degree and min-fill give upper bounds only.
  • Global constraints reason over many variables together. Alldifferent is arc-consistent iff each value-graph edge belongs to a matching covering variables; Régin checks with one matching and strongly connected components.
  • Conflict-directed backjumping jumps to the deepest cause of failure and passes along remaining causes; saving causes as nogoods is the idea CDCL refines in SAT.
  • Min-conflicts solves nn queens in nearly constant repairs thanks to greedy initialization and abundant solutions; sparse-solution problems need noise or restarts.
  • Lex-leader constraints break symmetry while retaining one solution per orbit, and should align with the search heuristic.
  • CP-SAT models with interval variables and native constraints; read status, objective, bound and gap. Big-M formulations are unnecessary when a global constraint exists.