Sub topic 15
Reductions in Practice: Encoding Problems for SAT Solvers, LP, and Max Flow
This chapter assumes you know many-one reductions, how their direction works, and the Cook-Levin theorem from earlier chapters. You should also be comfortable reading Python and know the basic definitions of conjunctive normal form (CNF) and flow networks.
Earlier chapters used reductions mostly to prove that problems are hard. Practitioners use the same tool in the forward direction, which is the direction that transfers algorithms. You have a new problem A. You know an excellent solver for a well-studied problem B. You write a reduction from A to B, run the solver, and translate its answer back. Engineers do this daily with SAT solvers, linear programming (LP) solvers, and maximum flow algorithms.
The Encode, Solve, Decode Pattern
A practical reduction has three parts:
- Encode: map an instance of A to an instance of B.
- Solve: call a mature solver for B.
- Decode: map B's solution back to a solution of A.
The correctness proof still has two directions. Every solution of A must produce a solution of B, so the encoding does not lose answers. Every solution of B must decode to a valid solution of A, so the encoding does not invent false answers. In practice you also verify each decoded answer directly, because checking a solution is cheap and encoding bugs are common.
Encoding into SAT
A SAT solver takes a CNF formula and either returns a satisfying assignment or reports that none exists. Modern solvers such as MiniSat, CaDiCaL, and Kissat handle formulas with millions of clauses. This makes SAT a common target for scheduling, hardware verification, package dependency resolution, and puzzles.
Most SAT encodings use three kinds of constraints:
- At least one: a single clause
x1 OR x2 OR ... OR xk. - At most one: one clause
NOT xi OR NOT xjfor each pair, which gives quadratic size. - Conflicts: clauses that forbid combinations the problem does not allow.
Graph k-coloring is a standard example. Create a variable x(v, c) that means "vertex v gets color c." Each vertex gets at least one color and at most one color. The endpoints of an edge never share a color.
from itertools import combinations, product
def coloring_to_cnf(n, edges, k):
def var(v, c):
return v * k + c + 1 # DIMACS variables start at 1
clauses = []
for v in range(n):
clauses.append([var(v, c) for c in range(k)]) # at least one color
for c1, c2 in combinations(range(k), 2):
clauses.append([-var(v, c1), -var(v, c2)]) # at most one color
for u, v in edges:
for c in range(k):
clauses.append([-var(u, c), -var(v, c)]) # neighbors differ
return n * k, clauses
def brute_force_sat(num_vars, clauses):
# Stand-in for a real SAT solver; only usable on tiny formulas.
for bits in product([False, True], repeat=num_vars):
if all(any(bits[abs(l) - 1] == (l > 0) for l in cl) for cl in clauses):
return bits
return None
def decode(bits, n, k):
return [next(c for c in range(k) if bits[v * k + c]) for v in range(n)]
edges = [(0, 1), (1, 2), (0, 2)] # a triangle
num_vars, clauses = coloring_to_cnf(3, edges, 3)
model = brute_force_sat(num_vars, clauses)
colors = decode(model, 3, 3)
assert all(colors[u] != colors[v] for u, v in edges) # check the decoded answer
print("3-coloring:", colors)
assert brute_force_sat(*coloring_to_cnf(3, edges, 2)) is None
print("triangle is not 2-colorable")To use a real solver, write the clauses in DIMACS format: a header line p cnf <vars> <clauses>, then one clause per line, with its literals followed by 0. Libraries such as PySAT accept the same lists of integer literals directly.
Encoding as Maximum Flow
Max flow is solvable in polynomial time, so reducing to it gives a guaranteed efficient algorithm, not just a heuristic that is fast in practice. Bipartite matching is the classic example. Suppose workers can do certain jobs and each worker takes at most one job. Add a source s with a capacity-1 edge to every worker. Add a capacity-1 edge from each worker to each job they can do. Add a capacity-1 edge from every job to a sink t. The integrality theorem guarantees that an integer maximum flow exists, and the augmenting-path algorithm finds one. In that flow, the saturated worker-to-job edges form a maximum matching.
from collections import deque
def max_flow(cap, s, t):
# Edmonds-Karp on a residual-capacity dict: cap[u][v] = remaining capacity.
flow = 0
while True:
parent = {s: None}
queue = deque([s])
while queue and t not in parent:
u = queue.popleft()
for v, c in cap[u].items():
if c > 0 and v not in parent:
parent[v] = u
queue.append(v)
if t not in parent:
return flow
path, v = [], t
while parent[v] is not None:
path.append((parent[v], v))
v = parent[v]
bottleneck = min(cap[u][v] for u, v in path)
for u, v in path:
cap[u][v] -= bottleneck
cap[v][u] = cap[v].get(u, 0) + bottleneck
flow += bottleneck
def bipartite_matching(left, right, pairs):
cap = {"s": {}, "t": {}}
for a in left:
cap["s"][("L", a)] = 1
cap[("L", a)] = {}
for b in right:
cap[("R", b)] = {"t": 1}
for a, b in pairs:
cap[("L", a)][("R", b)] = 1
size = max_flow(cap, "s", "t")
# Flow on L->R shows up as residual capacity on the reverse edge R->L.
matching = [(a, b) for a, b in pairs if cap[("R", b)].get(("L", a), 0) == 1]
return size, matching
workers = ["ann", "bo", "cy"]
jobs = ["db", "web", "ml"]
can_do = [("ann", "db"), ("ann", "web"), ("bo", "db"), ("cy", "web"), ("cy", "ml")]
size, matching = bipartite_matching(workers, jobs, can_do)
assert size == len(matching) == 3
assert len({a for a, _ in matching}) == len({b for _, b in matching}) == 3
print(size, matching)The same pattern covers project selection, image segmentation via minimum cut, baseball elimination, and assigning students to sections with capacity limits. In each case node capacities and edge capacities encode the constraints of the original problem.
Encoding as Linear Programming
An LP asks for real variables that maximize a linear objective subject to linear inequalities. LP is solvable in polynomial time, and solvers such as HiGHS, Gurobi, and the one behind scipy.optimize.linprog are mature. Shortest paths, max flow, min-cost flow, and many resource-allocation problems all have direct LP formulations.
Integer linear programming (ILP) adds the requirement that some variables be integers. ILP is NP-hard, and in this way it plays the same role as SAT. It is a general-purpose target that can be slow in the worst case but is often fast on real instances.
Choosing a Target
| Target | Complexity of target | Good fit | Main risk |
|---|---|---|---|
| SAT | NP-complete | Logical constraints, puzzles, configuration, verification | Encoding blowup; no polynomial guarantee |
| ILP | NP-hard | Constraints with costs, budgets, counts | Weak formulations solve slowly |
| LP | Polynomial | Continuous allocation, flows, relaxations | Fractional answers when integers are needed |
| Max flow / min cut | Polynomial | Matching, assignment, separation, capacities | Only fits problems with network structure |
A useful rule: if your problem reduces to max flow or LP with integral optima, prefer those targets, because the reduction proves a polynomial-time algorithm. Use SAT or ILP when the problem is NP-hard or when its constraints don't fit a network.
Common Errors
- Reducing in the wrong direction. To solve A with a B-solver, map A to B. Mapping B to A shows only that A is at least as hard as B, and it gives you no algorithm.
- Skipping the decode check. A missing clause can make the solver accept assignments that are not real solutions. Always verify the decoded answer against the original instance.
- Ignoring encoding size. A reduction that is polynomial on paper but has 10⁹ clauses is useless in practice.
- Forgetting the "no" case. If the target is unsatisfiable or has flow below the bound, the encoding must guarantee that the original instance has no solution. That is the second correctness direction.
Exercise
A course has n students and m sections. Each student lists acceptable sections, and section j has capacity c_j. Describe a max-flow reduction that decides whether every student can be placed, and say how to decode the placement.
Show answer
Build a source s, one node per student, one node per section, and a sink t. Add edges s→student with capacity 1, student→section with capacity 1 for each acceptable section, and section j→t with capacity c_j. Every student can be placed exactly when the max flow equals n. By the integrality theorem an integer maximum flow exists. Each student sends one unit along a single student→section edge, and that edge gives the student's section. The capacities on the edges into t keep every section within its limit.
Exercise
In coloringtocnf, suppose you delete the "at most one color" clauses. Is the reduction still correct for deciding k-colorability? What changes in decoding?
Show answer
The yes/no answer stays correct. Any satisfying assignment still gives each vertex at least one color, and for each color, the endpoints of an edge never both have it. So choosing any one true color per vertex gives a proper coloring. Decoding must pick one true color per vertex, for example the first one, which is what decode already does. The deleted clauses only make the solution space smaller, which sometimes helps or hurts solver speed.
Exercise
You formulate maximum matching in a general (non-bipartite) graph as an LP with constraints sum of xe over edges at each vertex ≤ 1 and 0 ≤ xe ≤ 1. On a triangle, what can go wrong?
Show answer
The LP can set x_e = 0.5 on all three edges. That meets every vertex constraint and has value 1.5, but the largest real matching in a triangle has size 1. The constraint matrix of a non-bipartite graph is not totally unimodular, so optimal solutions can be fractional. Fixing this requires integrality constraints (ILP) or extra odd-set constraints, as in Edmonds' matching polytope.