Linear Programming

A workshop that builds 42 tables and 24 chairs a week earns $4,140, the most its three limits allow. The simplex method finds that plan in two pivots. It walks from corner to corner of the allowed region.

Learn CLRS Chapter 29: standard and slack form, the simplex method, degeneracy, duality and shadow prices, shortest paths and max flow as LPs, and interior-point methods.

Press Run simplex and watch the walk. Then drag the table profit and run it again. The best corner moves, and so does the path. Then we build the method, piece by piece, from one corner.

You need a little Python and school algebra: straight lines, and inequalities such as 4x + 3y ≤ 240. We build the rest from zero.

Re-taught from Chapter 29, Linear Programming, in the third edition of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms (CLRS). The workshop and the toys are our own, and a script checked every pivot against scipy.

Walk the corners to the best plan

$70
$50

Illustrative workshop. Limits: carpentry 4 h a table and 3 h a chair, 240 h a week; lumber 3 units and 1 unit, 150 units; finishing 2 h and 4 h, 200 h. The pivot rule is the largest coefficient (Chapter 4).

Chapter 0

The Best Plan Sits on a Corner

Draw the plans a workshop can make, and see why the best one is a corner

You run a small workshop. A table earns $70 and a chair earns $50. Three resources run out each week:

ResourcePer tablePer chairEach week
Carpentry hours43240
Lumber units31150
Finishing hours24200

How many tables and chairs should you build? Call the number of tables x1 and the number of chairs x2. Each plan is one point on a plane.

Drag a plan and try to beat $4,140

Drag the dot. It turns red when the plan breaks a limit. The dashed line holds every plan with the same profit.

Illustrative workshop. Fractions of a table are allowed here; the end of this chapter says why that matters.

Each limit is a straight line, and the allowed side is a half of the plane. The plans that obey all limits form the feasible region: here a teal polygon with five corners. The thing you maximize, 70x1 + 50x2, is the objective. A problem with a straight-line objective and straight-line limits is a linear program (LP).

Now look at the dashed line. Every plan on it earns the same profit. Push it outward and the profit grows. The last point of the region it touches is the best plan. A straight line leaving a polygon with straight sides last touches a corner (a vertex), or a whole side that ends in corners. The best plan is the corner (42, 24): 70 × 42 + 50 × 24 = $4,140.

The region has no dents: it is convex. So a plan with no better neighbour is the best of all. That is why a walk that only goes uphill, from corner to corner, can find the optimum.

The failure, as symptom, measurement and fix

The symptom is a search that never ends: try every corner of a large LP. To measure it, count the candidates. Two variables and three limits give at most 10. A hundred variables and two hundred limits give up to C(300, 100), about 4 × 1081. The fix is the simplex method: visit only corners that raise the profit.

The road

  1. Standard form: one way to write every LP, and how to start when zero is not allowed.
  2. Slack form: turn each limit into an equation; a corner is a basic solution.
  3. One pivot: pick a variable to raise, and the ratio test says how far.
  4. The simplex walk: pivot until no raise helps, and read the answer.
  5. Where simplex stalls: ties, cycles, and walks through every corner.
  6. Duality: a buyer's prices put a ceiling on your profit.
  7. Shadow prices: what one more unit of a resource is worth.
  8. Shortest paths and max flow: two graph problems written as LPs.
  9. Interior points: cut through the middle instead of walking the edge.
  10. The field guide: terms, numbers, checks, code and links.
Why can the search for the best plan look only at corners?

Chapter 1

Standard Form: One Way to Write Every LP

Rewrite any LP as maximize, at-most limits, and no negative variables

You can write one LP many ways: minimize or maximize, at most or at least, equal signs, variables that may go negative. An algorithm wants one fixed shape. CLRS calls it standard form: maximize, every limit is "at most", and every variable is zero or more.

Put the profit per unit in a list c and the amounts you choose in a list x. Put the resource use per unit in a table A, and the supplies in a list b.

Say it aloud

Maximize c-transpose x, subject to A x at most b, and x at least zero.

maximize
maximize choose x to make the next quantity as large as the limits allow.
x
x the plan: n amounts, here x1 tables and x2 chairs. Each is zero or more.
cTx
c-transpose x multiply each profit cj by its amount xj and add: the total profit.
A
A a table with one row per resource and one column per product: the use per unit.
≤
at most applied row by row: each resource's use stays within its supply.
b
b the supply of each resource: 240 hours, 150 units, 200 hours.
In plain words

Pick amounts x. Row by row, the use A x must not pass the supply b. Among those plans, take the one with the largest profit cTx.

With numbers

The workshop: c = (70, 50), b = (240, 150, 200). For x = (42, 24), cTx = 2,940 + 1,200 = 4,140. Row one of A is (4, 3): 4 × 42 + 3 × 24 = 240, exactly the supply.

Four rewrites bring any LP to this shape. None changes the best plan.

  1. Minimize cTx? Maximize −cTx instead.
  2. An equation a = b? Write two limits: a ≤ b and a ≥ b.
  3. An at-least limit a ≥ b? Multiply by −1: −a ≤ −b.
  4. A free variable x2 that may be negative? Write x2 = x2′ − x2″ with both parts zero or more.

Rewrite an LP, one rule at a time

Press Next rule. Blue marks the line that changed.

A made-up LP. scipy gives the same best plan before and after: x1 = 6, x2 = 4.

The failure, as symptom, measurement and fix

The symptom is a simplex run that cannot start. It starts at the plan x = 0, and that plan breaks a limit whenever some bi is negative. Above, b = (10, −10, −2). The fix in CLRS is an auxiliary LP: add one variable x0 and subtract it from every left side, so A x − x0 ≤ b. Then minimize x0. With x0 large, x = 0 is allowed, so this LP can start.

If the smallest x0 is 0, the original LP has a feasible plan, and simplex starts there. Above, it reaches x0 = 0 at (6, 4). For the limits x1 + x2 ≤ 1 and x1 + x2 ≥ 3, x0 cannot go below 1, so no plan exists: the LP is infeasible.

Which standard-form limit replaces x1 − x2 ≥ 2?

Chapter 2

Slack Form and Basic Solutions

Give each limit a slack variable, and find the corners by setting two variables to zero

Algebra is easier with equations than with "at most". So give each limit a new variable that holds the leftover. Call the leftover of resource i its slack, si. Call the supply bi and the use per unit of product j, aij.

Say it aloud

s-i equals b-i minus the sum over j of a-i-j times x-j.

si
s-i the slack of resource i: how much is left over. It must be zero or more.
bi
b-i the supply of resource i each week.
Σj
the sum over j add one term per product, here j = 1 (tables) and j = 2 (chairs).
aij
a-i-j how much of resource i one unit of product j uses.
xj
x-j how many units of product j the plan makes.
In plain words

For resource i, multiply each amount xj by its use aij and add. Take that from the supply bi. What remains is si. The limit holds exactly when si is zero or more.

With numbers

Plan (30, 30), carpentry: s1 = 240 − 4 × 30 − 3 × 30 = 30 hours left. Lumber: s2 = 150 − 90 − 30 = 30. Finishing: s3 = 200 − 60 − 120 = 20.

Now the workshop has 5 variables (x1, x2, s1, s2, s3) and 3 equations. Set any 2 of them to zero, the nonbasic variables, and the 3 equations fix the other 3, the basic variables. The result is a basic solution. If every value is zero or more, it is a basic feasible solution, and it is a corner of the region.

Set two variables to zero

Pick a pair. The bars show all five values. A negative bar means the point breaks a limit.

There are C(5, 2) = 10 pairs. Five give corners; five give points outside the region.

Setting si = 0 means the plan sits on line i. Setting xj = 0 means it sits on an axis. So each pair picks two lines and their crossing. The simplex method moves from one basic feasible solution to the next by swapping one variable in the pair.

The failure, as symptom, measurement and fix

The symptom is a "corner" that looks better than the best. Lumber and finishing cross at (40, 30), with profit $4,300. To measure it, compute every slack: s1 = 240 − 160 − 90 = −10. The plan needs 10 carpentry hours you do not have. The fix is to keep every value at zero or more on each move. The ratio test in Chapter 3 does that.

Plan (40, 20). What are the slacks (s1, s2, s3)?

Chapter 3

One Pivot: Enter, Ratio Test, Leave

Raise one variable until the first slack hits zero, then swap the two

Start at the corner (0, 0): build nothing, all slacks full. The profit is z = 70x1 + 50x2. Both coefficients are positive, so raising either variable helps. The variable you raise is the entering variable. Take x1, and keep x2 at 0.

As x1 grows, every slack shrinks: s1 = 240 − 4x1, s2 = 150 − 3x1, s3 = 200 − 2x1. You must stop when the first one hits zero. That slack is the leaving variable. Call the entering variable e, and the use per unit of e in row i, aie.

Raise one variable until a slack runs out

Pick the entering variable and press Raise. Each bar is how far that limit lets it go. The shortest bar wins.

Illustrative workshop. Each ratio is supply divided by use per unit.

Say it aloud

t equals the minimum, over the rows i where a-i-e is above zero, of b-i over a-i-e.

t
t the step: how far the entering variable can rise.
mini : aie > 0
the minimum over the rows where a-i-e is above zero the smallest ratio wins. Rows with aie ≤ 0 do not shrink, so they set no limit.
bi
b-i the current value of the basic variable in row i (at the start, the full supply).
aie
a-i-e how much row i's basic variable drops per unit of the entering variable e.
In plain words

For each row with aie above zero, divide bi by aie. That is how far e can rise before row i's variable hits zero. Take the smallest as t. That row's variable leaves.

With numbers

Raising x1: 240 / 4 = 60, 150 / 3 = 50, 200 / 2 = 100. So t = 50 and lumber s2 leaves. The plan moves to (50, 0) and the profit to 70 × 50 = $3,500.

The pivot rewrites the equations around the new corner. Solve the lumber row for x1: x1 = 50 − x2/3 − s2/3. Put that into the profit:

z = 70(50 − x2/3 − s2/3) + 50x2 = 3,500 + (80/3)x2 − (70/3)s2

Now x1 is basic and s2 is nonbasic. The profit still has a positive coefficient, 80/3 on x2, so another pivot can help.

The failure, as symptom, measurement and fix

The symptom is a ratio test with no rows: every aie is zero or negative. Nothing stops e, so the profit has no ceiling: the LP is unbounded.

Example: maximize x1 with only x1 − x2 ≤ 5. Raise both together and the profit grows forever. To measure it, check the entering column for a positive entry. The fix is in the model: a limit is missing.

At (0, 0) you raise x2 instead. The ratios are 240/3, 150/1 and 200/4. Which slack leaves, and where does the plan go?

Chapter 4

The Simplex Walk and the Stopping Rule

Pivot until every coefficient in the profit row is negative or zero

The simplex method (George Dantzig, 1947) repeats the pivot. Pick a nonbasic variable with a positive profit coefficient. Run the ratio test. Swap. When no coefficient is positive, stop. A tableau is the table that stores the equations: one row per basic variable, one column per variable, plus the profit row.

Step the tableau, watch the walk

Press Pivot. The entering column is blue; the leaving row is purple. Then switch the rule and walk again.

The profit row shows each coefficient c̄j as the tableau stores it, with its sign flipped: a negative entry there means "raising this helps". Values are exact fractions.

With the largest-coefficient rule the walk takes two pivots. After the first, z = 3,500 + (80/3)x2 − (70/3)s2. Now x2 enters. The ratios are 40/(5/3) = 24 for carpentry, 50/(1/3) = 150 for lumber and 100/(10/3) = 30 for finishing. Carpentry leaves, and the plan reaches (42, 24).

Write the profit using only the nonbasic variables. Call the constant part v, and the coefficient of nonbasic variable j its reduced cost, c̄j (read "c-bar-j").

Say it aloud

z equals v plus the sum, over the nonbasic j, of c-bar-j times x-j.

z
z the profit of a plan, in dollars.
v
v the profit at the current corner, where every nonbasic variable is 0.
Σj ∈ N
the sum over j in N one term for each nonbasic variable; N is the set of them.
c̄j
c-bar-j the reduced cost: dollars gained per unit if you raise xj from 0.
xj
x-j a nonbasic variable, now 0. It can be a product or a slack.
In plain words

Read each c̄j. If one is positive, raising that xj raises z: pivot on it. If every c̄j is zero or negative, no move helps, and v is the best profit.

With numbers

At (42, 24): z = 4,140 − 16s1 − 2s2. So v = 4,140, c̄ = −16 for carpentry slack and −2 for lumber slack. Leaving an hour idle costs $16; leaving a unit of lumber costs $2. Stop: $4,140 is optimal.

The other rule enters x2 first and walks (0, 0) → (0, 50) → (36, 32) → (42, 24). Three pivots, same answer. The rule changes the path, never the result.

The failure, as symptom, measurement and fix

The symptom is a loop that never stops in floating point. A coefficient that should be 0 comes out as −1 × 10−15, and the code keeps pivoting on it. To measure it, count pivots and print the profit row. The fix is a tolerance: treat any value within 10−9 of zero as zero.

A profit row reads z = 900 + 4x2 − 3s1. What is true?

Chapter 5

Where Simplex Stalls: Ties, Cycles, Long Walks

See a pivot that does not move, a loop of bases, and a walk through every corner

Take a smaller LP: maximize x1 + x2 with x1 + x2 ≤ 4, 2x1 + x2 ≤ 6 and x1 + 2x2 ≤ 6. All three lines pass through (2, 2). A corner where more lines meet than the number of variables is degenerate.

Step through a tie and a long walk

Pick a case and press Pivot. Watch the ratio test on the tied corner, and count the corners on the square.

Both LPs are small textbook-style examples; every pivot is computed live and was checked in exact fractions.

From (3, 0), x2 enters and the ratio test ties: row 1 gives 1/(1/2) = 2 and row 3 gives 3/(3/2) = 2. One slack leaves. The other stays basic with value 0. Any later pivot on that zero row has t = 0: the basis changes, the point does not. That is a degenerate pivot.

A run of degenerate pivots can come back to a basis it has seen. Then simplex cycles forever. A classic 4-variable example (in Chvátal's textbook) cycles every 6 pivots under the largest-coefficient rule. Bland's rule (1977) breaks every tie by the smallest index, for the entering and the leaving variable. It cannot cycle. On that example it stops after 7 pivots.

Klee and Minty (1972) built LPs that force a long walk. In d dimensions the region is a squashed cube with 2d corners, and the largest-coefficient rule visits all of them:

Dimensions dCorners 2dPivots, largest coefficient
243
387
66463
d2d2d − 1

On real LPs simplex is fast. Spielman and Teng's smoothed analysis (2001) gives one reason: add small random noise to the numbers and the expected number of pivots becomes polynomial. Nobody has found a pivot rule that is proven polynomial on every LP.

The failure, as symptom, measurement and fix

The symptom is a profit that stays flat for many pivots. To measure it, store each basis as a sorted tuple and check for a repeat. The fix is Bland's rule, or a tiny random change to b that removes the ties.

The ratio test gives t = 0. What happens in that pivot?

Chapter 6

Duality: A Price for Every Resource

Price the resources so no product pays more, and that price caps your profit

A buyer wants all your resources for the week. She offers y1 dollars per carpentry hour, y2 per lumber unit and y3 per finishing hour. You sell only if the resources in a table are worth at least the table's $70, and the same for a chair's $50:

4y1 + 3y2 + 2y3 ≥ 70 (a table's resources) 3y1 + y2 + 4y3 ≥ 50 (a chair's resources) minimize 240y1 + 150y2 + 200y3, every y ≥ 0

This is the dual LP. The workshop problem is the primal. In matrix form the dual is: minimize bTy subject to ATy ≥ c and y ≥ 0. The table A turns on its side; supplies and profits swap places.

Price the resources, get a ceiling

Move the prices. Each product bar must reach its profit line. Then the offer is a ceiling on any plan's profit.

$10
$10
$5

Illustrative workshop. The best primal profit, $4,140, is the dashed line.

Why is any covering offer a ceiling? Call the plan x and the prices y.

Say it aloud

c-transpose x is at most b-transpose y.

cTx
c-transpose x the profit of any plan x that obeys every limit.
≤
is at most holds for every such pair; this is weak duality.
bTy
b-transpose y the buyer's total offer: each supply bi times its price yi, added. The prices must cover each product.
In plain words

At prices y, each product earns at most what its resources cost. So the profit cTx is at most the cost of the resources the plan uses, yTAx. The plan uses at most the supply, so that cost is at most bTy.

With numbers

Plan (36, 32) earns 4,120. Prices (0, 18, 8) cover both products (70 and 50 exactly) and offer 150 × 18 + 200 × 8 = 4,300. Prices (16, 2, 0) offer 3,840 + 300 = 4,140. So no plan beats 4,140, and the plan (42, 24) reaches it.

cTx ≤ (ATy)Tx = yT(Ax) ≤ yTb

Strong duality says more: if the primal has a best plan, the dual has best prices, and the two values are equal. Here both are $4,140. CLRS proves it from the final simplex tableau, which holds the best prices in its profit row (the 16 and 2 of Chapter 4).

The failure, as symptom, measurement and fix

The symptom is a "ceiling" below a plan you can build: prices (10, 0, 0) offer $2,400, but plan (42, 24) earns $4,140. To measure it, check ATy ≥ c: a table's resources are worth only 40, short of 70. The fix: only covering prices give a ceiling.

You find a plan worth 100 and covering prices worth 100. What do you know?

Chapter 7

Shadow Prices and Complementary Slackness

Read what one more unit of each resource is worth, and why a leftover resource is free

The best prices are y = (16, 2, 0). Each is a shadow price: the extra profit from one more unit of that resource. Lumber is worth $2 a unit to you. Finishing is worth nothing, because 20 hours of it are already idle.

Add lumber, read the slope

Drag the lumber supply. One panel shows the region and the best plan. The other plots best profit against lumber; its slope is the shadow price.

150

Illustrative workshop; every point of the curve is a fresh solve. scipy agrees at 100, 120, 140, 160 and 180.

The curve has three straight pieces. Between 140 and 180 units the slope is 2. Below 140 lumber gets scarcer and the slope is 18. Above 180 carpentry runs out and more lumber is worth 0.

Why is idle finishing free? Call the leftover of resource i its slack, bi − aix, where ai is row i of A.

Say it aloud

y-i times, b-i minus a-i x, equals zero.

yi
y-i the best price of resource i, from the dual.
bi
b-i the supply of resource i.
aix
a-i x how much of resource i the best plan uses.
0
zero for every resource i at once. This is complementary slackness.
In plain words

For each resource, either the plan uses all of it, or its price yi is zero. A product made in positive amount pays exactly its resource cost.

With numbers

Carpentry: 16 × (240 − 240) = 0. Lumber: 2 × (150 − 150) = 0. Finishing: 0 × (200 − 180) = 0. Tables: 4 × 16 + 3 × 2 = 70, exactly the profit, as it must be since x1 = 42 > 0.

So a shadow price answers "should I buy more?". If a carpenter rents at $10 an hour and the shadow price is $16, each hour adds $6, up to 250 hours. Past that the basis changes and the price drops.

The failure, as symptom, measurement and fix

The symptom is a forecast that overshoots. Buy 50 more lumber at a shadow price of $2 and you predict +$100. The real gain is +$60, from $4,140 to $4,200. To measure it, re-solve at the new supply. The fix: a shadow price holds only inside its range, here 140 to 180 units.

The best plan leaves 20 finishing hours idle. What is finishing's shadow price?

Chapter 8

Shortest Paths and Max Flow Are LPs

Write two graph problems as LPs, and see max-flow min-cut as duality

CLRS section 29.2 writes graph problems as LPs. Start with a shortest path from s to t. Give each vertex v a number dv, its distance from s. Call the weight of the edge from u to v w(u, v).

Say it aloud

d-v is at most d-u plus w of u, v, for every edge from u to v.

dv
d-v the LP variable for vertex v; at the optimum it is the distance from s.
≤
is at most one limit per edge. Add ds = 0, and maximize dt.
du
d-u the variable of the edge's start.
w(u, v)
w of u, v the weight of the edge from u to v.
In plain words

Each edge caps dv at du plus the edge's weight. Push dt as high as the caps allow. The tightest chain of caps is the shortest path.

With numbers

Made-up weights: s→a 2, s→b 5, a→b 1, a→t 6, b→t 2. Then da ≤ 2, db ≤ min(5, 2 + 1) = 3, dt ≤ min(2 + 6, 3 + 2) = 5. scipy returns dt = 5, the path s, a, b, t.

Why maximize? The limits are upper caps, so only maximizing presses dt against them. Minimize dt and scipy reports the LP as unbounded.

Maximum flow is an LP too. Give each edge a flow f(u, v). Keep 0 ≤ f(u, v) ≤ c(u, v), its capacity. At each inner vertex, flow in equals flow out. Maximize the flow out of s.

Raise one capacity, watch the cut

Drag the capacity of a→t. Blue numbers are the flows the LP finds. Purple marks the smallest cut: its source side and the edges that leave it.

2

Made-up capacities. The flow comes from augmenting paths; scipy's LP gives the same value for every setting.

The dual of the max-flow LP is a cut LP. At its best, it picks a set of vertices with s inside and t outside, and pays the capacity of every edge leaving the set. So max-flow equals min-cut is strong duality on one graph. Capacity 2 gives flow 8 and the cut {s, a} paying 4 + 2 + 2 = 8.

The failure, as symptom, measurement and fix

The symptom is a flow larger than the network can carry. Drop the "in equals out" rule at a, and the LP reports 9 with capacity a→t at 0, where the true maximum is 6. To measure it, add in and out at every inner vertex. The fix: one equation per inner vertex.

The shortest-path LP has limits dv ≤ du + w(u, v). Why does it maximize dt?

Chapter 9

Through the Middle: Interior Points

Replace hard walls with a soft push, and slide along the central path to the corner

Simplex walks the edges. Two other methods solve every LP in polynomial time. The ellipsoid method (Khachiyan, 1979) proved it possible, but it is slow in practice. Interior-point methods (Karmarkar, 1984) are polynomial and fast. They move through the inside of the region.

Replace each wall with a soft push. Call the slack of each limit slacki, including x1 and x2 themselves. Call the push strength μ (mu).

Say it aloud

Maximize c-transpose x plus mu times the sum over i of the natural log of slack-i.

maximize
maximize over plans x strictly inside the region.
cTx
c-transpose x the profit, as before.
μ
mu the barrier strength, a positive number you shrink step by step.
Σi
the sum over i one term per wall: 3 resources and 2 "at least zero" rules, so 5 here.
ln
the natural log of it falls toward minus infinity as its input nears 0, so the plan never touches a wall.
slacki
slack-i the distance to wall i: bi − aix for a resource, xj for an axis.
In plain words

Add μ times the log of every slack to the profit. Find the best plan of that smooth problem with Newton's method. Shrink μ and repeat from there. The best points trace the central path to the optimal corner.

With numbers

With μ = 100 the best point is (38.0, 25.5), profit $3,936. On the central path the gap to the optimum is at most 5 × μ = 500; here it is 204. With μ = 1 the point is (41.7, 24.3) and the gap is 2.

Shrink the barrier, follow the path

Drag μ down. The yellow point is the best plan of the barrier problem. Blue is simplex's edge walk, for contrast.

10,000

Illustrative workshop. Each point is a live Newton solve; scipy matches it to 3 decimals at μ = 10,000, 1,000, 100, 10, 1 and 0.1.

MethodYearWorst caseWhere it moves
Simplex1947Exponential (Klee-Minty)Corner to corner
Ellipsoid1979PolynomialShrinking ellipsoids
Interior point1984PolynomialThe central path

The failure, as symptom, measurement and fix

The symptom is an answer that sits near a corner but not on it, such as (41.7, 24.3). To measure it, look at the slacks: none is exactly zero. The fix is to shrink μ until the gap bound is below your tolerance, then snap to the nearest corner, a step solvers call crossover.

What happens as μ shrinks toward 0?

Chapter 10

The Field Guide

Keep the terms, the numbers, the checks and the code in one place

An LP maximizes a straight-line objective over a convex region cut by straight-line limits, so a corner is optimal. Simplex walks corners by pivots and stops when no reduced cost is positive. The dual prices the limits, and its best value equals the primal's.

Terms

TermMeaning
Standard formMaximize cTx, A x ≤ b, x ≥ 0
Slack formEach limit as an equation with a slack si ≥ 0
Basic feasible solutionn variables set to 0, the rest solved and all ≥ 0: a corner
PivotOne variable enters, the ratio test picks one to leave
Reduced cost c̄jProfit per unit from raising nonbasic xj; stop when all ≤ 0
Degenerate cornerMore limits meet than there are variables; pivots may not move
DualMinimize bTy, ATy ≥ c, y ≥ 0
Shadow priceBest dual value yi: profit per extra unit of resource i, inside its range

The numbers from this page

WhatNumberWhy it matters
Workshop optimum(42, 24), $4,140Carpentry and lumber bind
Simplex path(0, 0) → (50, 0) → (42, 24)Two pivots, largest coefficient
Final profit row4,140 − 16s1 − 2s2Optimal, and the dual prices
Dual prices(16, 2, 0), $4,140Strong duality
Lumber shadow price$2, from 140 to 180 unitsOutside the range it changes
Klee-Minty, d dimensions2d − 1 pivotsSimplex is exponential in the worst case
Max flow, cap a→t = 28 = cut {s, a}Max-flow min-cut is duality
Barrier, μ = 100(38.0, 25.5), gap 204 ≤ 500Gap at most (walls) × μ

Checks after any solve

The core, in Python

pythonimport numpy as np
from scipy.optimize import linprog

def simplex(c, A, b, eps=1e-9):
    """Maximize c @ x subject to A @ x <= b, x >= 0. Needs b >= 0."""
    m, n = A.shape
    T = np.hstack([A, np.eye(m), b.reshape(-1, 1)]).astype(float)
    z = np.concatenate([-c, np.zeros(m + 1)]).astype(float)   # profit row, signs flipped
    basis = list(range(n, n + m))                              # start: slacks are basic
    while z[:-1].min() < -eps:                               # some reduced cost > 0
        e = int(np.argmin(z[:-1]))                              # largest coefficient enters
        col = T[:, e]
        ratios = np.where(col > eps, T[:, -1] / np.where(col > eps, col, 1), np.inf)
        if np.isinf(ratios).all():
            raise ValueError("unbounded")
        l = int(np.argmin(ratios))                                # ratio test: row that leaves
        T[l] /= T[l, e]
        for i in range(m):
            if i != l: T[i] -= T[i, e] * T[l]
        z -= z[e] * T[l]
        basis[l] = e
    x = np.zeros(n + m)
    x[basis] = T[:, -1]
    y = z[n:n + m]                                             # dual prices under the slacks
    return x[:n], z[-1], y

c = np.array([70, 50]); A = np.array([[4, 3], [3, 1], [2, 4]]); b = np.array([240, 150, 200])
print(simplex(c, A, b))          # x = [42, 24], z = 4140, y = [16, 2, 0]
res = linprog(-c, A_ub=A, b_ub=b, method="highs")   # linprog minimizes: negate c
print(res.x, -res.fun, -res.ineqlin.marginals)        # [42. 24.] 4140.0 [16. 2. 0.]

Where it sits

LP solves in polynomial time, but no algorithm is known whose step count depends only on the number of variables and limits (a strongly polynomial one). Add "whole numbers only" and the problem becomes NP-hard. Some LPs, such as max flow with whole capacities and bipartite matching, have whole-number corners anyway, so the LP answer is already whole.

Keep going

The takeaway. Write the problem as an objective, variables and limits. The best plan is a corner, simplex walks there, and the dual's prices prove you arrived.
A solver returns plan x with profit 500 and prices y with bTy = 500, but one product's resources at prices y are worth less than its profit. What do you conclude?

Now press Present or Teach. Explain from memory why the best plan is a corner, how one pivot works, how to read the final profit row, and why the dual is a ceiling. Then go back to the hero, set the table profit to $140, and say why the walk ends at the same corner.

Credit and source

This lesson re-teaches Chapter 29, Linear Programming, in the third edition of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms: standard and slack forms (29.1), formulating problems as LPs (29.2), the simplex algorithm (29.3), duality (29.4) and the initial basic feasible solution (29.5). The workshop, the networks and the toys are our own; every number was checked with scipy.optimize.linprog and exact fractions.

CLRS Chapter 29: Linear Programming
The book · Back to Gleams