Author: Hang Li (@flgkd)
Note: Titles marked with ⭐ highlight key concepts and important summaries.
This note studies the assignment problem and the Hungarian algorithm, together with their connections to bipartite matching, combinatorial optimization, and integer programming.
This note is primarily based on Sun and Li's Integer Programming [1]. The weighted Hungarian-method overview also draws on [8,9], while the unweighted bipartite-matching discussion is supported by [10,11,12]. All eleven figures in Sections 3-5 are adapted and redrawn from Pecco's Zhihu article [11], which is also the source of the three graph-modeling examples used there.
Two assignment models should be distinguished from the beginning:
- the classical assignment problem, also called the one-to-one assignment problem;
- the generalized assignment problem (GAP).
The classical assignment problem imposes a one-to-one correspondence between agents and tasks. In the balanced case, every agent receives exactly one task and every task is assigned to exactly one agent.
In the standard generalized assignment problem, each job is still assigned to one machine or agent, but the one-job-per-agent restriction is relaxed. A machine or agent may receive several jobs as long as its resource capacity is respected.
This distinction has an important computational consequence:
The classical assignment problem is polynomially solvable, while the generalized assignment problem is NP-hard.
A second distinction is equally important:
The classical weighted assignment problem is a minimum-cost or maximum-weight perfect matching problem. An unweighted maximum-cardinality bipartite matching problem is related, but it is not the same optimization problem.
This matters because the phrase Hungarian algorithm is used in two different ways in practice. In operations research, it usually refers to the Kuhn-Munkres method for the weighted assignment problem [2,3,9,14]. In some competitive-programming materials, a DFS-based augmenting-path algorithm for unweighted bipartite maximum matching is also informally called the Hungarian algorithm [10,11]. This note treats both ideas, while keeping them conceptually separate.
Suppose there are
If machine
if machine
otherwise.
The maximum-profit assignment problem can be written as
Each task must be assigned to exactly one machine:
Each machine must receive exactly one task:
The decision variables are binary:
This is the standard balanced one-to-one assignment model [1-3].
The source material also presents the equivalent minimum-cost form. If
with the same assignment constraints.
Construct a bipartite graph with two vertex sets:
and
The left vertices represent machines or workers, while the right vertices represent jobs.
An edge
A feasible classical assignment selects exactly one incident edge for every vertex on both sides. Therefore, it is a perfect matching.
With costs, the problem is a minimum-cost perfect matching in a bipartite graph.
With profits, it is a maximum-weight perfect matching in a bipartite graph [13,14].
This is more precise than simply calling the classical assignment problem a “maximum matching problem.” Maximum cardinality matching only maximizes the number of matched pairs and ignores edge costs or profits.
Although the classical assignment problem has binary variables, its linear-programming relaxation has a special integral structure.
If we replace
by
the constraints already imply
This is one reason the classical assignment problem is polynomially solvable despite having a natural binary integer-programming formulation.
This example is also important for understanding what is meant when we say that integer linear programming is NP-hard.
The statement does not mean that every optimization problem written in ILP form is individually NP-hard. Many special classes of ILP have additional structure and can be solved in polynomial time. The classical assignment problem is a particularly clear counterexample: it has a binary ILP formulation, yet it admits polynomial-time exact algorithms.
The correct complexity statement is about the general ILP problem under the usual finite binary encoding of its numerical data. General ILP is NP-hard, meaning that a polynomial-time algorithm capable of solving arbitrary ILP instances to global optimality would also solve NP-hard problems in polynomial time. Therefore, unless
So the logical relationship is:
general ILP
→ NP-hard
a particular problem with an ILP formulation
→ may be NP-hard
→ may also belong to a polynomially solvable special class
The classical assignment problem belongs to the second category.
For a more detailed discussion of NP-hardness, special cases, and the difference between a general problem class and individual structured subclasses, see:
Kuhn introduced the Hungarian method for the assignment problem in 1955 [2], and Munkres later gave a refined algorithmic treatment and established its strongly polynomial character [3]. Modern refinements admit dense
For a square minimum-cost matrix
- subtract the minimum value in each row from every entry of that row;
- subtract the minimum value in each column from every entry of that column;
- search for a set of independent zeros corresponding to a complete assignment;
- if a complete assignment cannot yet be formed, cover all zeros with a minimum number of horizontal and vertical lines;
- adjust uncovered and doubly covered entries to create additional zeros;
- repeat until
$n$ independent zeros can be selected.
The row and column reductions preserve the relative cost of complete assignments, while the zero-creation steps progressively expose an optimal perfect matching [2,3,8].
A standard modern implementation of the minimum-cost Hungarian algorithm runs in
time for an
Therefore, the Hungarian algorithm finds a globally optimal solution in polynomial time for the classical assignment problem.
This point is worth emphasizing from an integer-programming perspective. The classical assignment model is naturally written with binary variables, so it is an ILP formulation. Nevertheless, the existence of the polynomial-time Hungarian algorithm shows directly that
having an ILP formulation does not imply that the resulting optimization problem is NP-hard.
What is NP-hard is the general ILP problem, not every structured optimization problem that happens to be expressible as an ILP.
Equivalently, the NP-hardness of general ILP means that there is no single polynomial-time exact algorithm for arbitrary ILP instances unless
This makes the assignment problem and the Hungarian algorithm a useful counterexample to the incorrect statement:
“Every problem written as an ILP is NP-hard.”
For the general complexity distinction, see again:
The following Python implementation returns the minimum cost and one optimal assignment:
def hungarian_min_cost(cost):
n = len(cost)
m = len(cost[0])
if n > m:
raise ValueError("This implementation assumes n <= m.")
u = [0] * (n + 1)
v = [0] * (m + 1)
p = [0] * (m + 1)
way = [0] * (m + 1)
for i in range(1, n + 1):
p[0] = i
j0 = 0
minv = [float("inf")] * (m + 1)
used = [False] * (m + 1)
while True:
used[j0] = True
i0 = p[j0]
delta = float("inf")
j1 = 0
for j in range(1, m + 1):
if used[j]:
continue
cur = cost[i0 - 1][j - 1] - u[i0] - v[j]
if cur < minv[j]:
minv[j] = cur
way[j] = j0
if minv[j] < delta:
delta = minv[j]
j1 = j
for j in range(m + 1):
if used[j]:
u[p[j]] += delta
v[j] -= delta
else:
minv[j] -= delta
j0 = j1
if p[j0] == 0:
break
while True:
j1 = way[j0]
p[j0] = p[j1]
j0 = j1
if j0 == 0:
break
assignment = [-1] * n
for j in range(1, m + 1):
if p[j] != 0:
assignment[p[j] - 1] = j - 1
min_cost = -v[0]
return min_cost, assignmentFor a balanced maximum-profit problem, one can transform profits into costs by replacing each profit
The source material develops the assignment problem through bipartite matching. This is especially useful for understanding feasibility, perfect matching, minimum vertex cover, and several graph-modeling applications.
A graph
such that every edge has one endpoint in
A bipartite graph with vertex sets X and Y. Adapted and redrawn from [11].
A matching is a set of edges no two of which share an endpoint.
A maximum matching is a matching with the largest possible number of edges.
A perfect matching is a matching that covers every vertex.
For a balanced bipartite graph with
a perfect matching has exactly
The following illustration uses a pairing interpretation. Boys and girls form the two vertex sets, and an edge represents an admissible pair.
A bipartite pairing graph. Adapted and redrawn from [11].
The maximum-matching problem asks:
What is the largest number of pairwise compatible pairs that can be selected so that no person belongs to more than one pair?
Mathematically, this is exactly the maximum-cardinality matching problem in a bipartite graph.
The key idea behind the DFS-based bipartite matching algorithm is the augmenting path.
Suppose we currently have a matching
An augmenting path is a path that:
- starts at an unmatched vertex;
- ends at an unmatched vertex;
- alternates between edges not in
$M$ and edges in$M$ .
If the matched and unmatched status of every edge on such a path is reversed, the size of the matching increases by exactly one.
Berge's augmenting-path theorem gives the converse criterion: a matching is maximum if and only if there is no augmenting path with respect to it [14]. This is what justifies stopping after all augmenting-path searches fail.
This is the logic behind the familiar “try another partner for the currently matched vertex” interpretation.
Candidate edges in the bipartite matching example. Adapted and redrawn from [11].
Consider the following sequence conceptually:
- try to match
$B_1$ to an available neighbor; - when
$B_2$ wants a vertex already used by$B_1$ , search recursively for an alternative neighbor for$B_1$ ; - if that rerouting succeeds, assign the freed vertex to
$B_2$ ; - continue with the remaining left-side vertices.
The next figures illustrate this rerouting idea.
An augmenting-path rematching step. Adapted and redrawn from [11].
Further matching updates in the same example. Adapted and redrawn from [11].
The concrete sequence in Figures 3-5 is useful for seeing the recursion more clearly:
- first match
$B_1$ with$G_2$ ; - when
$B_2$ also needs$G_2$ , recursively try to move$B_1$ to another available neighbor; - since
$B_1$ can also use$G_4$ , rematch$B_1$ with$G_4$ and then match$B_2$ with$G_2$ ; -
$B_3$ can then be matched with$G_1$ ; - finally,
$B_4$ can only use$G_4$ . To free$G_4$ ,$B_1$ would have to move back to$G_2$ , but$G_2$ is occupied by$B_2$ , which has no alternative neighbor.
Therefore no augmenting path starting from
A different search order may produce a different maximum matching, but the maximum cardinality remains the same.
The precise drawing order is not important. The invariant is that after a successful augmenting-path search, the matching cardinality increases by one.
The following Python version corresponds to the recursive C++ implementation in the source material.
def maximum_bipartite_matching(adj, n_right):
match_right = [-1] * n_right
def augment(u, visited):
for v in adj[u]:
if visited[v]:
continue
visited[v] = True
if match_right[v] == -1 or augment(match_right[v], visited):
match_right[v] = u
return True
return False
matching_size = 0
for u in range(len(adj)):
visited = [False] * n_right
if augment(u, visited):
matching_size += 1
return matching_size, match_rightHere:
-
adj[u]stores the right-side neighbors of left vertex$u$ ; -
match_right[v]stores the left vertex currently matched to right vertex$v$ ; -
visited[v]prevents repeatedly exploring the same right-side vertex in one augmenting search.
If
This is often written as
This algorithm solves unweighted maximum-cardinality bipartite matching. It should not be confused with the
A vertex cover is a set of vertices such that every edge has at least one endpoint in the set.
A minimum vertex cover is a vertex cover containing as few vertices as possible.
Alternating reachability used to construct a minimum vertex cover. Adapted and redrawn from [11].
For every bipartite graph,
the size of a maximum matching equals the size of a minimum vertex cover.
This is König's theorem [12,14].
If a maximum matching has size
and a minimum vertex cover has size
then for bipartite graphs,
After finding a maximum matching, a minimum vertex cover can be constructed by alternating reachability.
Let
- Start from all unmatched left vertices.
- From a left vertex, traverse unmatched edges to the right.
- From a right vertex, traverse its matched edge back to the left.
- Continue until no new vertices can be reached.
Let:
-
$Z_X$ be the reached left vertices; -
$Z_Y$ be the reached right vertices.
Then a minimum vertex cover is
For the running example, consider the maximum matching
The resulting minimum vertex cover is therefore
Its size is
This result is extremely useful because the augmenting-path computation for maximum matching can be reused to recover a minimum vertex cover.
The source material gives several problems that do not initially look like assignment or matching problems but become simple after an appropriate bipartite-graph transformation.
A representative problem is Luogu P1129 [ZJOI2007] Matrix Game.
Consider an
The allowed operations are:
- exchange any two rows;
- exchange any two columns.
The goal is to determine whether row and column permutations can make every main-diagonal entry equal to
Construct a bipartite graph:
- left vertex
$X_i$ represents row$i$ ; - right vertex
$Y_j$ represents column$j$ ; - add edge
$(X_i,Y_j)$ if matrix entry$(i,j)$ equals$1$ .
The question becomes:
Can we choose one
$1$ in every row and one$1$ in every column?
That is exactly the existence of a perfect matching.
Row and column exchanges only relabel the row and column vertices. They do not change the underlying bipartite adjacency structure.
Row or column permutations can be interpreted as relabeling one side of the bipartite graph. Adapted and redrawn from [11].
Therefore the matrix game is feasible if and only if the bipartite graph has matching size
There is also a direct connection to the combinatorial concept of a system of distinct representatives (SDR). For each row
The following Python implementation corresponds to the source C++ code:
import sys
def maximum_matching_from_matrix(matrix):
n = len(matrix)
match_right = [-1] * n
def augment(row, visited):
for col in range(n):
if matrix[row][col] == 0 or visited[col]:
continue
visited[col] = True
if match_right[col] == -1 or augment(match_right[col], visited):
match_right[col] = row
return True
return False
matching_size = 0
for row in range(n):
visited = [False] * n
if augment(row, visited):
matching_size += 1
return matching_size
def solve():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
t = next(it)
answers = []
for _ in range(t):
n = next(it)
matrix = [[next(it) for _ in range(n)] for _ in range(n)]
if maximum_matching_from_matrix(matrix) == n:
answers.append("Yes")
else:
answers.append("No")
print("\n".join(answers))
if __name__ == "__main__":
solve()A representative problem is vijos1204, CoVH: Conan Unlocking.
Another example uses a rectangular grid in which some cells are initially raised.
One operation presses an entire row or an entire column.
A grid with selected cells. Adapted and redrawn from [11].
Construct a bipartite graph:
- one left vertex for each row;
- one right vertex for each column;
- an edge
$(X_i,Y_j)$ for every raised cell$(i,j)$ .
Bipartite representation of the row-column grid. Adapted and redrawn from [11].
Pressing row
Pressing column
Therefore, pressing the minimum number of rows and columns so that every raised cell is handled is exactly a minimum vertex cover problem.
By König's theorem,
A representative problem is TYVJ P1035, Chessboard Covering.
Consider an
A
Color the board in a checkerboard pattern.
Checkerboard coloring of the board. Adapted and redrawn from [11].
Every pair of orthogonally adjacent cells has opposite colors. Therefore every domino always covers:
- one cell from the first color class;
- one cell from the second color class.
After deleting unavailable cells:
A checkerboard with deleted cells. Adapted and redrawn from [11].
Construct a bipartite graph:
- one partition contains all remaining cells of one color;
- the other partition contains all remaining cells of the other color;
- connect two vertices if the corresponding cells are orthogonally adjacent.
Each selected matching edge corresponds to one domino, and no two matching edges share a cell.
Because every grid cell has at most four orthogonal neighbors, the resulting bipartite graph is sparse. For larger boards, an adjacency-list representation is therefore preferable to storing a dense adjacency matrix.
Therefore,
If a problem asks for the number of covered cells instead of the number of dominoes, the answer is twice the matching size.
A Python implementation is:
import sys
def max_dominoes(n, removed):
blocked = [[False] * n for _ in range(n)]
for r, c in removed:
blocked[r][c] = True
left_id = {}
right_id = {}
for r in range(n):
for c in range(n):
if blocked[r][c]:
continue
if (r + c) % 2 == 0:
left_id[(r, c)] = len(left_id)
else:
right_id[(r, c)] = len(right_id)
adj = [[] for _ in range(len(left_id))]
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for (r, c), u in left_id.items():
for dr, dc in directions:
nr = r + dr
nc = c + dc
if (nr, nc) in right_id:
adj[u].append(right_id[(nr, nc)])
match_right = [-1] * len(right_id)
def augment(u, visited):
for v in adj[u]:
if visited[v]:
continue
visited[v] = True
if match_right[v] == -1 or augment(match_right[v], visited):
match_right[v] = u
return True
return False
matching_size = 0
for u in range(len(adj)):
visited = [False] * len(right_id)
if augment(u, visited):
matching_size += 1
return matching_size
def solve():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(map(int, data))
n = next(it)
m = next(it)
removed = []
for _ in range(m):
x = next(it) - 1
y = next(it) - 1
removed.append((x, y))
print(max_dominoes(n, removed))
if __name__ == "__main__":
solve()The generalized assignment problem replaces the one-to-one structure of the classical assignment problem with capacity constraints.
Suppose there are:
-
$m$ machines; -
$n$ jobs; - available resource capacity
$b_i$ on machine$i$ ; - resource consumption
$a_{ij}$ if machine$i$ performs job$j$ ; - cost
$c_{ij}$ if machine$i$ performs job$j$ .
Define
if job
otherwise.
The minimum-cost GAP formulation in [1,4] is
Each machine must respect its capacity:
Each job must be assigned to exactly one machine:
The variables are binary:
This differs fundamentally from the classical assignment model because one machine may receive multiple jobs, provided its capacity is not exceeded.
Another common formulation treats machines as bins and jobs as items [5,7].
Let:
-
$t_i$ be the capacity of bin$i$ ; -
$w_{ij}$ be the weight consumed if item$j$ is assigned to bin$i$ ; -
$p_{ij}$ be the profit obtained from that assignment.
Then the optional-assignment max-profit GAP can be written as
Capacity constraints:
Each item is assigned to at most one bin:
Binary restrictions:
If every item must be assigned, replace the inequality with
So the term GAP is used for closely related minimization and maximization formulations. The exact assignment requirement should always be stated explicitly.
The generalized assignment problem is NP-hard [4,5,7].
The classical assignment problem has only one-to-one matching constraints. GAP additionally introduces machine-dependent resource consumption and capacity limits.
Those capacity constraints couple many assignment decisions together, destroying the simple perfect-matching structure that makes the classical assignment problem polynomially solvable.
This is an important example of a broader principle:
A small-looking modeling change can completely change computational complexity.
Because GAP is NP-hard, approximation and heuristic algorithms are important for large instances.
For maximum GAP, LP-based approximation methods can achieve strong constant-factor guarantees. In particular, Fleischer, Goemans, Mirrokni, and Sviridenko give a
The source material also presents the residual-profit framework of Cohen, Katzir, and Raz [6] for the version in which not every item must be assigned.
Suppose an ALG is available for a single knapsack problem, with
Their framework obtains a
approximation for GAP [6]. In particular, using a knapsack FPTAS with ratio
Let
Use
if item
During the iteration for bin
If item
If item
Thus the residual profit measures the net improvement obtained by moving item
The framework is:
Initialize T[i] = -1 for every item i.
For each bin j:
1. Construct the residual-profit function P_j.
2. Call a knapsack approximation algorithm ALG for bin j.
3. Let S_j be the selected item set.
4. Set T[i] = j for every item i in S_j.
The tentative assignment may change during later iterations because an item can be reassigned to a different bin if doing so provides sufficient residual profit.
This approach reveals a direct algorithmic connection between GAP and the knapsack problem studied in Note 12.
| Property | Classical Assignment Problem | Generalized Assignment Problem |
|---|---|---|
| Basic structure | one-to-one assignment | capacity-constrained assignment |
| Number of jobs per agent | exactly one in the balanced model | potentially multiple |
| Job assignment | exactly one agent per job | exactly one or at most one, depending on variant |
| Main graph interpretation | weighted bipartite perfect matching | multiple knapsack-like assignment |
| Standard exact method | Hungarian / Kuhn-Munkres method | MILP, branch-and-bound, branch-and-cut, decomposition, etc. |
| Typical complexity | polynomial | NP-hard |
The difference is not merely terminology. The underlying combinatorial structure changes from a perfect matching polytope to a capacity-constrained packing-and-assignment model.
- The classical assignment problem is a one-to-one resource-allocation problem.
- Its natural binary formulation is equivalent to a weighted perfect matching problem in a bipartite graph.
- The weighted Hungarian / Kuhn-Munkres method finds a globally optimal classical assignment in polynomial time, commonly
$O(n^3)$ . - The classical assignment problem is an important counterexample to the claim that every optimization problem with an ILP formulation is NP-hard.
- General ILP is NP-hard, but special structured ILP subclasses may still admit polynomial-time exact algorithms.
- Unweighted maximum-cardinality bipartite matching is related but should not be confused with weighted assignment.
- The DFS augmenting-path algorithm repeatedly searches for alternating paths that increase the matching size by one.
- König's theorem states that, in bipartite graphs, the maximum matching size equals the minimum vertex-cover size.
- Matrix permutation, row-column covering, and domino-placement problems can all be transformed into bipartite matching or vertex-cover problems.
- GAP introduces capacity constraints and allows one machine or bin to receive multiple jobs or items.
- GAP is NP-hard, so exact MILP methods, approximation algorithms, and heuristics become important.
- Knapsack algorithms are directly connected to approximation methods for GAP.
- Sun, Xiaoling, and Duan Li. Integer Programming. Beijing: Science Press, 2010. ISBN: 978-7-03-029380-0.(孙小玲、李端:《整数规划》,北京:科学出版社,2010年,ISBN:978-7-03-029380-0)
- Kuhn, H. W. “The Hungarian Method for the Assignment Problem.” Naval Research Logistics Quarterly 2(1-2), 1955, 83-97. DOI: 10.1002/nav.3800020109.
- Munkres, James. “Algorithms for the Assignment and Transportation Problems.” Journal of the Society for Industrial and Applied Mathematics 5(1), 1957, 32-38. DOI: 10.1137/0105003.
- Shmoys, David B., and Éva Tardos. “An Approximation Algorithm for the Generalized Assignment Problem.” Mathematical Programming 62, 1993, 461-474. DOI: 10.1007/BF01585178.
- Fleischer, Lisa, Michel X. Goemans, Vahab S. Mirrokni, and Maxim Sviridenko. “Tight Approximation Algorithms for Maximum General Assignment Problems.” Proceedings of the Seventeenth Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), 2006, 611-620. DOI: 10.1145/1109557.1109624.
- Cohen, Reuven, Liran Katzir, and Danny Raz. “An Efficient Approximation for the Generalized Assignment Problem.” Information Processing Letters 100(4), 2006, 162-166. DOI: 10.1016/j.ipl.2006.06.003.
- “Generalized Assignment Problem.” Wikipedia. https://en.wikipedia.org/wiki/Generalized_assignment_problem.
- “Assignment Problem: Meaning, Methods and Variations | Operations Research.” Engineering Notes. https://www.engineeringenotes.com/project-management-2/operations-research/assignment-problem-meaning-methods-and-variations-operations-research/15652.
- SimyHsu. “Hungarian Algorithm.” CSDN Blog. https://blog.csdn.net/u014754127/article/details/78086014.(SimyHsu:《Hungarian Algorithm匈牙利算法》,CSDN博客)
- Yinshi Mowen Qiancheng. “Bipartite Matching — Hungarian Algorithm (Time Complexity O(nm)).” CSDN Blog. https://blog.csdn.net/weixin_40477002/article/details/122799390.(银时莫问前程:《二分图匹配——匈牙利算法(时间复杂度O(nm))》,CSDN博客)
- Pecco. “Algorithm Study Notes (5): Hungarian Algorithm.” Zhihu Column. https://zhuanlan.zhihu.com/p/96229700.(Pecco:《算法学习笔记(5):匈牙利算法》,知乎专栏)
- Matrix67. “König's Theorem for Maximum Matching in Bipartite Graphs and Its Proof.” Matrix67 Blog. http://www.matrix67.com/blog/archives/116.(Matrix67:《二分图最大匹配的König定理及其证明》,Matrix67博客)
- “Assignment Problem.” Wikipedia. https://en.wikipedia.org/wiki/Assignment_problem.
- Burkard, Rainer E., Mauro Dell'Amico, and Silvano Martello. Assignment Problems. Philadelphia: Society for Industrial and Applied Mathematics (SIAM), 2009. ISBN: 978-0-89871-663-4. DOI: 10.1137/1.9781611972238.
The most relevant next topics are:
-
Network Flow and Minimum-Cost Flow
Bipartite matching and assignment can both be formulated through network-flow models, providing a broader framework for understanding augmenting paths, capacities, and assignment costs. -
Total Unimodularity and Integral Polyhedra
Useful for understanding why the LP relaxation of the classical assignment problem already has integral extreme points. -
Generalized Assignment Algorithms
A deeper study of exact branch-and-bound methods, Lagrangian relaxation, local search, and approximation algorithms for GAP. -
Matching Theory
Extends the ideas in this note to Hall's theorem, weighted matching, non-bipartite matching, blossom algorithms, and deeper structural results.










