The Assignment Problem
Suppose worker $i$ can perform task $j$ at cost $c_{ij}$. We must choose exactly one task for every worker and exactly one worker for every task. If permutation $\pi$ records the chosen task for each worker, the optimization problem is
Graphically, workers and tasks form the two sides of a weighted bipartite graph. A feasible assignment is a perfect matching; the goal is the perfect matching with minimum total edge weight. Brute force checks $n!$ permutations. The Hungarian algorithm reaches an optimum in $O(n^3)$ time.
Feasible
Every row and every column is used exactly once.
Objective
Minimize the sum of the selected matrix entries.
Certificate
Dual prices prove that no cheaper assignment exists.
Intuition: Prices and Tight Edges
Think of each row and column as carrying a price. After subtracting those prices, the remaining entry is a reduced cost: how much more expensive that pairing is than the current lower-bound explanation. A zero is a tight edge—a pairing whose original cost is fully explained by the current prices.
Market Analogy
Workers seek tasks with zero remaining premium. If several workers compete for too few tight tasks, the algorithm adjusts prices until a new zero appears. An alternating path then rearranges earlier choices and increases the matching by one without abandoning tight edges.
Zeros Are Opportunities, Not Assignments
A matrix may contain many zeros that collide in one row or column. The stopping condition is not “at least $n$ zeros”; it is “$n$ independent zeros,” one in every row and column.
Two Views of the Same Algorithm
The familiar matrix presentation is excellent for hand calculation:
- Row reduction: subtract the minimum of each row.
- Column reduction: subtract the minimum of each column.
- Zero graph: connect a row to a column wherever the reduced entry is zero, then find a maximum matching.
- Stop or expose: a matching of size $n$ is optimal. Otherwise, use a minimum vertex cover of the zero graph to mark rows and columns.
- Adjust: subtract the smallest uncovered entry from every uncovered cell and add it at every doubly covered intersection; repeat.
The implementation later uses the equivalent primal–dual shortest augmenting-path view. It grows the assignment one row at a time, maintains row/column potentials, stores each unused column's minimum slack, and updates only the values needed to reveal the next tight edge. This is the route to the compact $O(n^3)$ code.
Where Matching Theory Enters
Kőnig's theorem says the maximum number of independent zeros equals the minimum number of rows and columns covering every zero. Therefore fewer than $n$ cover lines precisely means the current zero graph lacks a perfect matching.
Worked Matrix Example
Use workers $A,B,C$ and tasks $1,2,3$ with the cost matrix below. Row reduction subtracts $9,6,6$. The second reduced column then has minimum $2$, so column reduction subtracts $2$ there.
Why does a zero assignment recover the original cost? The reductions subtracted $9+6+6+2=23$ from every complete assignment. The selected entries total $0$ after reduction, so their original total is $0+23=23$. Checking the other five permutations confirms none is cheaper.
When Zeros Conflict
Reduction does not always reveal a perfect zero matching immediately. In the reduced matrix below, rows $A$ and $B$ can initially use only column $1$. The maximum independent-zero matching has size $2$, and all zeros can be covered by column $1$ plus row $C$.
| 1 | 2 | 3 | Zero options | |
|---|---|---|---|---|
| $A$ | 0 | 2 | 2 | $1$ only |
| $B$ | 0 | 2 | 2 | $1$ only |
| $C$ | 2 | 0 | 0 | $2$ or $3$ |
The smallest uncovered value is $\delta=2$. Subtract it from uncovered cells $(A,2),(A,3),(B,2),(B,3)$ and add it to the doubly covered intersection $(C,1)$. The new matrix is
which admits independent zeros such as $A\to1$, $B\to2$, $C\to3$. The adjustment creates useful tight edges without invalidating the current dual prices.
Why the Method Is Correct
1. Reductions preserve the winner
Subtracting $r_i$ from row $i$ and $s_j$ from column $j$ subtracts the same total $\sum_i r_i+\sum_j s_j$ from every perfect assignment, because each assignment selects every row and column exactly once. Relative costs therefore do not change.
2. Potentials provide a lower bound
Choose row potentials $u_i$ and column potentials $v_j$ satisfying $u_i+v_j\le c_{ij}$. For any assignment $\pi$,
The right-hand side is a lower bound on every feasible assignment. Reduced costs $c_{ij}-u_i-v_j$ are nonnegative; their zeros are exactly the tight edges.
3. A tight perfect matching closes the gap
If every selected edge is tight, its total cost equals the dual lower bound. A feasible solution that attains a universal lower bound must be optimal. The algorithm alternates between improving the matching on tight edges and adjusting potentials until such a perfect matching exists.
Primal–Dual Mental Model
The matching is the candidate solution (primal). The prices are the proof of how low any solution could possibly be (dual). Hungarian finishes when the candidate and proof have exactly the same value.
Implementation
The arrays mirror the proof:
uandvare row and column potentials.minv[j]is the smallest known reduced-cost slack for reaching unused columnj.way[j]remembers the alternating-path predecessor used to reconstruct an augmentation.p[j]stores the row currently matched to columnj; column0is a sentinel that anchors the search.
Indexing and Ties
The public assignment uses zero-based indices: assignment[i] = j. When several optima exist, iteration order determines which one is returned; the minimum total is unchanged.
Complexity
For each of $n$ rows, the augmenting search can visit $O(n)$ columns, and each visit scans up to $O(n)$ unused columns. Therefore:
The classroom cover-and-adjust matrix presentation can take $O(n^4)$ when its matching and covering work is implemented naively. The shortest-augmenting-path potential formulation in the code avoids rescanning the full matrix after every small adjustment and achieves the standard cubic bound.
Rectangular, Maximization, and Forbidden Assignments
| Situation | Transformation | Important interpretation |
|---|---|---|
| $r\ne c$ | pad to $N=\max(r,c)$ with dummy rows or columns | a dummy match means “unassigned” |
| maximize value $w_{ij}$ | use $c_{ij}=M-w_{ij}$, or negate values if the implementation supports negatives | choose one common $M$; it adds the same constant to every complete assignment |
| optional assignments | set dummy-edge costs to the desired non-assignment penalty | zero is correct only when leaving an item unmatched is truly free |
| forbidden pair | use a carefully bounded large penalty, then reject any result that selects it | the sentinel must not overflow arithmetic or masquerade as feasible |
| floating-point costs | use tolerances when testing reduced costs for zero | exact equality is brittle after many updates |
Padding Changes the Model
Dummy entries are decisions, not bookkeeping. Their costs encode the business meaning of leaving a worker or task unmatched. Pick those penalties before running the algorithm, then remove dummy matches from the reported result.
Where Assignment Modeling Appears
Multi-Object Tracking in Computer Vision
A tracker can place existing tracks in the rows and new detections in the columns. Each cost combines motion disagreement, geometric overlap, and appearance dissimilarity. Solving the assignment chooses a globally consistent one-to-one association for that frame; dummy entries represent births, missed detections, or retired tracks.
- Workforce scheduling: assign people to shifts or jobs using travel time, preference, or qualification penalties.
- Resource allocation: map machines to jobs, vehicles to requests, or channels to users.
- Evaluation and label alignment: optimally align predicted clusters, components, or identities with reference labels.
- Data association: match observations across images, time steps, or sensor streams.
The one-to-one, additive objective is the key. If a task needs several workers, assignments interact through time, or costs depend on combinations of pairs, the model has moved beyond the classical linear assignment problem.
Common Pitfalls and a Reliable Checklist
| Pitfall | Consequence | Reliable practice |
|---|---|---|
| choosing each row minimum greedily | several rows may claim one column | maintain a global matching |
| counting zeros instead of matching them | colliding zeros look falsely complete | seek $n$ independent zeros |
| subtracting only uncovered cells | breaks the reduction invariant | also add $\delta$ at doubly covered intersections |
| padding with arbitrary zeroes | unmatched items may become artificially attractive | encode the real non-assignment penalty |
| using a huge sentinel near the integer limit | potential arithmetic can overflow | derive a safe bound and validate the final assignment |
| assuming the optimum is unique | tests reject a different valid optimum | verify feasibility and total cost, not one exact permutation |
Before You Run It
Confirm the objective is additive and one-to-one; define dummy and forbidden costs; choose integer widths or floating tolerances; validate matrix dimensions; and decide how ties should be reported.
Exercises
- Trace: reproduce both reductions in the SVG and list all six original assignment totals.
- Conflict: for the adjustment matrix, find a minimum line cover, apply $\delta=2$, and give two different perfect zero matchings in the result.
- Certificate: recover row and column potentials for the worked example and verify that each selected edge is tight.
- Maximization: transform rewards $[[8,7,6],[6,9,5],[7,8,9]]$ into costs and confirm the best total reward.
- Rectangular case: model three workers and two tasks where leaving a worker unassigned costs $4$. Explain the dummy column before solving.
- Testing: compare the Python output against brute force on random matrices up to $n=7$, checking the total rather than the exact assignment.
History and Takeaway
Harold Kuhn published the Hungarian method in 1955, naming it for the foundational work of Hungarian mathematicians Dénes Kőnig and Jenő Egerváry. James Munkres studied assignment and transportation algorithms in 1957, helping establish the method's strongly polynomial character. The original matrix-style method is commonly analyzed at $O(n^4)$; later augmenting-path refinements produced the $O(n^3)$ form implemented above.
The Mental Model to Keep
Hungarian grows a one-to-one matching while adjusting row and column prices. Those prices keep every reduced cost nonnegative; zero reduced-cost edges are currently justified choices. Once a perfect matching uses only justified edges, its cost meets the price-based lower bound, so optimality is proven—not guessed.