Problems in Disguise: Modeling & Reductions
When a puzzle is secretly a graph, a flow or a dynamic program.
A puzzle about nesting envelopes, a currency trader's loop of exchanges and a school timetable look nothing alike. Underneath they are a longest increasing subsequence, a negative cycle and a bipartite matching. Modeling is the skill of seeing the known problem inside the unfamiliar one, and of proving that the translation loses nothing.
What you’ll learn
- Model a problem as a known one by a transformation, and prove the transformation correct in both directions.
- Solve systems of difference constraints with shortest paths, and detect arbitrage as a negative cycle.
- Reduce assignment and chain-cover problems to bipartite matching, and selection and segmentation problems to minimum cuts.
- Recognize longest increasing subsequences, walk counts and 2-SAT in disguise, and explain why modeling in the opposite direction proves hardness.
A model is a reduction
Both directions matter. Direction (1) alone shows only that the model's optimum is at least as good as the real one, and a model that admits extra, fake solutions will report impossible answers. Direction (2) alone can hide real solutions that the model forgot.
Some models are one line. In a word ladder, words are vertices and one-letter changes are edges, so the fewest changes is a BFS distance. The number of ways to make exactly moves from to in a graph with adjacency matrix is the entry , so "count the walks of length " is a matrix power, by repeated squaring. In a triangle, for instance, there are 6 closed walks of length 4 from each corner. Other models need care, like this one.
Nesting envelopes. Envelope fits inside when and , both strictly. What is the longest chain of envelopes, each inside the next? Sort by width ascending and, among equal widths, by height descending; then nesting chains are exactly the strictly increasing subsequences of the heights, and the answer is a longest increasing subsequence.
Chains become subsequences. In a nesting chain the widths strictly increase, so its envelopes appear in sorted order, and their heights strictly increase.
Subsequences become chains. Take a strictly increasing subsequence of the heights. Two of its envelopes cannot share a width, because equal widths appear with heights in decreasing order. So the widths strictly increase as well, and every envelope fits in the next.
Cost. Sorting takes , and the patience-sorting LIS with binary search takes more.
from bisect import bisect_left
def max_nested(envelopes):
"""Longest chain in which width and height both strictly increase."""
env = sorted(envelopes, key=lambda e: (e[0], -e[1])) # width up; ties: height down
tails = [] # tails[L] = least last height of an increasing chain of length L + 1
for _, h in env:
i = bisect_left(tails, h) # strictly increasing heights
if i == len(tails):
tails.append(h)
else:
tails[i] = h
return len(tails)
print(max_nested([(4, 6), (2, 3), (5, 5), (4, 4), (6, 7)])) # 4: (2,3) (4,4) (5,5) (6,7)Checked against an DP on 3,000 random sets of envelopes. Sort equal widths by ascending height instead and returns 2, though neither envelope fits in the other: the forgotten half of the proof, direction (2), is exactly where the bug hides.
Difference constraints and negative cycles
Scheduling with gaps produces constraints of one shape. "Task 2 starts at least 3 hours after task 1" is ; "task 3 starts at most 6 hours after task 1" is . A system of difference constraints looks like linear programming, but it is a shortest-path problem in disguise: is exactly the triangle inequality that shortest-path distances satisfy.
No negative cycle gives a solution. Every vertex is reachable from , so the distances are finite, and they satisfy the triangle inequality on every edge, which is the constraint itself:
A negative cycle forbids every solution. Add the constraints along a cycle : the left sides telescope to zero, the right sides add up to the cycle's weight.
Algorithm. The graph has vertices and edges for constraints, and weights may be negative, so run Bellman–Ford: time, and a round that still improves something after rounds proves infeasibility.
import math
def solve_difference_constraints(n, cons):
"""cons: triples (i, j, c) meaning x_j - x_i <= c, variables 1..n. A solution, or None."""
edges = [(0, v, 0) for v in range(1, n + 1)] + list(cons) # source 0 -> each variable
d = [math.inf] * (n + 1)
d[0] = 0
for _ in range(n): # n + 1 vertices: n rounds of relaxation
for u, v, w in edges:
if d[u] + w < d[v]:
d[v] = d[u] + w
if any(d[u] + w < d[v] for u, v, w in edges):
return None # still improving: a negative cycle
return d[1:]
tasks = [(2, 1, -3), (3, 2, -2), (1, 3, 6), (4, 1, -1), (3, 4, -1)]
print(solve_difference_constraints(4, tasks)) # [-5, -2, 0, -1]
print(solve_difference_constraints(4, tasks + [(1, 3, 4)])) # NoneFive rules for four tasks: , , , , . Shifting the solution by 5 gives start times 0, 3, 5, 4. Tighten the third rule to and the cycle weighs : the first two rules force .
Arbitrage. With exchange rates (one unit of currency buys units of ), a loop of trades makes money when the product of its rates exceeds 1. Taking turns products into sums and "greater than 1" into "negative": a profitable loop is a negative cycle under the weights . Dollars to euros at 0.9, euros to pounds at 0.8 and pounds to dollars at 1.4 multiply to , a 0.8% profit per loop, and the cycle weighs .
Matchings and cuts in disguise
Whenever a statement pairs things up, such as people with jobs, students with seats or tasks with time slots, look for a bipartite graph: one side for each kind of thing, an edge for each acceptable pair. A maximum matching is the largest assignment, and when not everyone can be matched, Hall's theorem (1935) supplies a certificate: a set of people who together accept fewer than slots.
Chains give a matching. List each chain of a cover by chains in increasing order, and match each element's left copy to the right copy of the next element in its chain. No copy is used twice, and a chain of elements contributes edges:
A matching gives paths. In a matching, each element has at most one successor (the with matched) and at most one predecessor. Following successors never returns to an element, since every link goes up in the order, so the elements split into paths, one starting at each element whose right copy is unmatched:
Paths are chains, because is transitive: consecutive elements are comparable, hence all of them are. The two directions give equality, and a maximum matching (Hopcroft–Karp, ) finds the cover. On a DAG that is not transitively closed, the same construction counts the fewest vertex-disjoint paths instead.
| Problem | Model | Why the cut is the answer |
|---|---|---|
| Project selection (Picard, 1976): projects with profits or costs, and prerequisites | source to each profitable project, each costly project to the sink, an infinite edge from each project to every prerequisite | infinite edges keep the chosen set closed under prerequisites; best profit = total positive profit − minimum cut |
| Image segmentation (Greig, Porteous & Seheult, 1989): label pixels foreground or background | source to pixel with its foreground score , pixel to sink with its background score , neighbors joined by their separation penalty | a cut pays for each background pixel, for each foreground pixel and every penalty it separates: maximizing the labeling's score is minimizing the cut |
| Elimination (Schwartz, 1966): can a team still finish first? | one node per remaining game and per rival, capacities from the games left and from each rival's slack | the team survives exactly when the maximum flow carries every remaining game |
| Edge-disjoint routes between two sites | unit capacities | by Menger's theorem, the most edge-disjoint paths equal the fewest edges whose removal separates the sites |
Each of 500 students lists the courses, out of 300, that they would accept, and course has seats. You must place as many students as possible. How do you model it?
- Greedy: give each student, in order, their first listed course that still has a seat
- Maximum flow: source to each student (capacity 1), student to each acceptable course (capacity 1), course to the sink (capacity )
- Dynamic programming over the students in input order
- A minimum spanning tree of the student–course graph
Show the answer
B. Maximum flow: source to each student (capacity 1), student to each acceptable course (capacity 1), course to the sink (capacity )
Each unit of flow places one student in one course: capacity 1 out of the source gives each student at most one seat, and capacity into the sink enforces the seats. With integer capacities there is an integral maximum flow, which is a placement, and its value is the largest number of students that can be placed. It is bipartite matching with seats.
Binary choices, the reverse direction, and solvers
Binary choices with rules about pairs are 2-SAT. Let the variable mean "team presents on Monday", false meaning Tuesday. Every rule about two teams becomes clauses of two literals:
| Rule | Clauses |
|---|---|
| and are not both on Monday | |
| and are not both on Tuesday | |
| and present on the same day | |
| must present on Monday |
The formula is satisfiable exactly when no variable lies in the same strongly connected component as its negation in the implication graph, which takes linear time to check (Aspvall, Plass & Tarjan, 1979; see the lesson 2-SAT).
Now give each team three possible days and keep only the rules "these two must not share a day". Teams become vertices, rules become edges, and the question is whether the graph can be colored with three colors: NP-complete. One extra option per variable moved the problem across the P versus NP line, which is why modeling and hardness are two sides of one skill.
When no clean model appears, write the problem as an integer linear program or a SAT formula and hand it to a solver; the Optimal lesson SAT Solvers in Practice explains why that works far more often than worst-case theory suggests. Flow models carry a bonus that explains their integer answers: the constraint matrix of a network flow problem is totally unimodular, so whenever the capacities are integers its linear program has an optimal solution in integers (Hoffman & Kruskal, 1956).
Key takeaways
- A model is a reduction: map instances forward and solutions back, and prove both directions, so that the model has no fake solutions and loses no real ones.
- Difference constraints are shortest paths: feasible exactly when the constraint graph has no negative cycle, with ; arbitrage is a negative cycle under weights .
- Nesting chains are longest increasing subsequences after a careful sort, and walk counts are matrix powers.
- Pairings are matchings and flows; a partial order's fewest covering chains number minus a maximum matching (Dilworth's theorem via König's); closed selections and segmentations are minimum cuts.
- Binary choices with pairwise rules are 2-SAT, solvable in linear time, while three choices turn the same rules into NP-complete 3-coloring. Model forward to solve; reduce from a known hard problem to prove hardness.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You suspect your scheduling problem is NP-hard. Which reduction proves it?
- A polynomial-time reduction from to 3-SAT
- A polynomial-time reduction from 3-SAT to
- A polynomial-time reduction from to shortest paths
- Any polynomial-time reduction between and 3-SAT, in either direction
Show the answer
B. A polynomial-time reduction from 3-SAT to
If every 3-SAT instance can be turned into an instance of , then a fast algorithm for would solve 3-SAT fast: is at least as hard as 3-SAT. A reduction from to 3-SAT shows the opposite, that is no harder than 3-SAT.
A system of difference constraints has no solution exactly when…
- some is negative
- the constraint graph contains a cycle
- the constraint graph contains a cycle of negative total weight
- Dijkstra's algorithm fails on the constraint graph
Show the answer
C. the constraint graph contains a cycle of negative total weight
Adding the constraints around a cycle gives the cycle's weight, impossible exactly when the weight is negative; without negative cycles, shortest-path distances from the extra source are a solution.
A partial order on 10 elements has a maximum matching of size 6 in its bipartite "left copy, right copy" graph. What is the fewest number of chains that cover all 10 elements?
- 6
- 4
- 10
- 16
Show the answer
B. 4
Each matched pair links an element to its successor in a chain, so a matching of size glues the elements into chains, and no chain cover can do better: . By Dilworth's theorem, the poset's largest antichain then also has 4 elements.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), the section on difference constraints and shortest paths.
- J. Kleinberg & É. Tardos, Algorithm Design (Pearson, 2005), chapter 7, on applications of network flow.
- R. P. Dilworth, "A decomposition theorem for partially ordered sets," Annals of Mathematics 51 (1950).
- D. R. Fulkerson, "Note on Dilworth's decomposition theorem for partially ordered sets," Proceedings of the American Mathematical Society 7 (1956).
- B. Aspvall, M. F. Plass & R. E. Tarjan, "A linear-time algorithm for testing the truth of certain quantified Boolean formulas," Information Processing Letters 8(3) (1979).