The user wants a program to solve the assignment problem.
The "assignment problem" is a classic combinatorial optimization problem.
The goal is to assign n tasks to n workers (or agents) such that each worker gets exactly one task, each task is assigned to exactly one worker, and the total cost (or profit) is minimized (or maximized).
This is usually represented as a cost matrix where rows are workers and columns are tasks.
There are several algorithms to solve this:
Brute Force: Try all permutations. Complexity O(n!) - Too slow for anything but tiny n.
Hungarian Algorithm (Munkres Algorithm): The standard efficient solution. Complexity O(n3). This is what people usually look for when asking for "a program to solve the assignment problem".
Linear Programming (LP): It can be formulated as an LP, but the Hungarian algorithm is specialized for it.
I should implement the Hungarian Algorithm because it's the standard and most efficient specific algorithm for this.
Steps of the Hungarian Algorithm:
Subtract the smallest entry in each row from all entries of that row.
Subtract the smallest entry in each column from all entries of that column.
Draw lines through rows and columns to cover all zeros. If the number of lines equals n, an optimal assignment exists among the zeros. Go to step 6.
Find the smallest uncovered element. Subtract it from all uncovered rows. Add it to all covered columns.
Go back to step 3.
Select a matching of zeros such that each row and column has exactly one selected. This is the optimal assignment.
Implementation Details:
Language: Python is a good choice for readability, but C++ is faster. I'll provide Python code because it's accessible and easy to run, but maybe mention that for very large matrices, a compiled language is better. Let's stick to Python for the main solution.
I need a step-by-step implementation of the matrix manipulation.
Refining the Algorithm Steps for Code:
Let C be the cost matrix.
Row reduction: C[i,:]−=min(C[i,:]) for all i.
Col reduction: for all .
Alternative approach for implementation:
Often, coding the "minimum lines to cover zeros" part is tricky.
There's a slightly different way to implement the Hungarian algorithm using potentials (u and v) and finding augmenting paths, which is cleaner in code (similar to min-cost max-flow).
However, the matrix manipulation version is easier to explain and understand conceptually. I will implement the matrix manipulation version.
Let's draft the Matrix Manipulation Code Structure:
Input: cost_matrix (List of Lists).
Copy matrix to avoid modifying input.
Step 1 & 2: Subtract row/col mins.
Loop:
Find maximum matching of zeros. Let size be match_size.
If match_size == n, we are done. Break.
Find minimum lines to cover all zeros (Konig's theorem relation).
Find min uncovered value.
Adjust matrix.
Wait, finding the minimum lines is actually equivalent to finding the minimum vertex cover in the bipartite graph of zeros. Finding the minimum vertex cover is related to the maximum matching (Konig's Theorem).
So the algorithm essentially alternates between:
Find max matching.
If size < n, use the matching to find the minimum vertex cover (lines).
Adjust weights based on lines.
Repeat.
This is the standard O(n3) implementation.
Code Logic Plan:
step1: subtract row mins.
step2: subtract col mins.
step3: Find minimum number of lines to cover all zeros.
This requires a matching algorithm.
This is the hardest part to implement concisely.
Simplification: For a general-purpose request, maybe I shouldn't write the raw algorithm from scratch if there are libraries? The prompt asks to "Create a program". Writing a raw Hungarian algorithm in a single script is educational but error-prone. Using scipy.optimize.linear_sum_assignment is the practical "programmer" way.
Decision: I will provide two solutions.
A Python solution using scipy (best practice for real world).
A raw Python implementation of the Hungarian Algorithm (best for understanding/homework/no-dependencies).
Drafting the Raw Implementation (Simplified Hungarian):
Mask array: To track zeros (starred and primed).
Row/Col cover arrays: Boolean.
Step 1: Subtract row mins.
Step 2: Subtract col mins.
Step 3: Cover columns of starred zeros. (Wait, this is getting specific to a specific variation of the algorithm).
Let's stick to the variation involving finding the maximum matching of zeros.
Actually, looking at common implementations (like the one often adapted from theaconite or similar sources), they follow these states:
Subtract mins.
Find a matching (starred zeros) greedily.
Cover columns containing starred zeros.
While not all columns covered:
Find a non-covered zero.
Prime it.
If no starred zero in its row:
Find augmenting path.
Unstar primed zeros on path, star zeros on path.
Erase primes, uncover rows.
Cover columns with starred zeros.
Else (starred zero in row):
Cover row, uncover col of starred zero.
If no uncovered zero:
Find min uncovered value.
Subtract from uncovered rows, add to covered cols.
This is a bit complex for a quick script, but it's the correct way. I will structure the code to be modular.
Code Structure:
python
import numpy as np
def hungarian_algorithm(cost_matrix):
n, m = cost_matrix.shape
# ... implementation ...
Wait, maybe scipy is too easy? "Create a program that solves..." usually implies "show me the logic".
However, re-implementing a complex O(n3) graph algorithm from scratch in a chat response is often overkill and prone to bugs.
I will provide the scipy solution as the "production" solution, and a Python class/script implementing the algorithm manually as the "educational" solution.
Let's refine the manual implementation details. It's easier to treat the matrix as a list of lists or numpy array.
I'll write a class AssignmentSolver.
Inputs:
Cost matrix (NxN).
Output:
Total cost and the assignment (row -> col).
Let's write the code for the "Manual" version:
I need to be careful with the logic for finding the minimum number of lines.
Actually, a simpler logic often used in competitive programming involves potentials (u, v) and augmenting paths, similar to Min Cost Max Flow. This might be too abstract.
Let's stick to the Matrix method. It is intuitive.
Reduce rows/cols.
Try to assign.
If fail, draw lines, adjust, repeat.
Wait, there's a simpler greedy approach for approximation? No, the user asked to solve it, implying optimal solution.
Let's focus on the scipy solution first, then a raw Python implementation if space permits or just explain the logic.
Actually, the most helpful response provides the standard library usage first, then the algorithm implementation.
Plan:
Explain the problem briefly.
Mention the standard algorithm (Hungarian).
Solution 1 (Recommended): Use scipy.optimize.linear_sum_assignment. This is efficient and robust.
Solution 2 (From Scratch): Implement the Hungarian algorithm in pure Python. This is good for environments without scipy or for learning.
Drafting Solution 2 (Pure Python):
I need a version that isn't 200 lines long.
Key subroutines:
subtract_mins
min_lines_to_cover_zeros (This is the bottleneck).
To find lines, we need a matching.
We can convert the zero-entries to a bipartite graph adjacency list.
Use Hopcroft-Karp or DFS to find max matching.
Use the matching to find minimum vertex cover (lines).
This is getting complex.
Maybe there is a cleaner implementation of the matrix method without explicitly coding a separate graph solver.
The method involving "Starred" and "Primed" zeros is the standard operational procedure for the Hungarian algorithm.
The "Star/Prime" Algorithm Steps:
Reduce matrix.
Star zeros greedily (one per row/col).
Cover columns with starred zeros.
While not all columns covered:
Look for uncovered zero.
Prime it.
Is there a starred zero in this row?
Yes: Uncover that column, cover this row. (Continue loop to find uncovered zero).
No: Augmenting path found.
Follow alternating star/prime back.
Unstar star-zeros on path, Star prime-zeros on path.
Uncover all rows/cols, unprime all zeros.
Go back to covering columns with starred zeros.
If no uncovered zero exists:
Find min value in uncovered cells.
Add to covered rows, subtract from uncovered cols (or vice versa depending on definition of covered).
Actually: Subtract min from all uncovered rows. Add min to all covered columns.
This is doable. I will implement this.
Refining the Code:
I'll use a class to keep state (cost matrix, mask, row_cover, col_cover).
Introduction: The problem is best solved using the Hungarian Algorithm.
Option 1: Using Python's scipy library (Efficient, Production-ready).
Option 2: A custom Python implementation (No dependencies, educational).
Writing Option 2 (The Raw Implementation):
I need to ensure the "min uncovered value" step is correct.
Matrix state M.
Covered rows R, Covered cols C.
Min val m in Mij where .
Subtract from all where row .
Add to all where col .
Zeros on intersections (covered row, covered col) become (not zero).
Zeros in uncovered area become ? No.
Let's trace:
Uncovered cell: . New .
Covered row, uncovered col: . New . (Since covered row is not subtracted? No, usually algorithm says subtract from uncovered rows).
Wait, the step is usually:
Subtract min from all uncovered rows.
Add min to all covered columns.
Let's check a cell (r,c).
Uncovered row, Uncovered col: Subtracts m, adds 0 -> val−m.
Covered row, Uncovered col: Subtracts 0, adds 0 -> val.
Uncovered row, Covered col: Subtracts m, adds -> .
Is this correct?
Standard step:
Find min uncovered h.
Subtract h from all uncovered rows.
Add h to all covered columns.
Effect:
Uncovered/Uncovered: decreases by h.
Covered/Uncovered: unchanged.
Covered/Covered: increases by h.
Uncovered/Covered: unchanged.
This maintains zeros in Uncovered/Uncovered? No, creates new zeros.
Preserves zeros in Covered/Uncovered.
Preserves zeros in Uncovered/Covered.
Zeros in Covered/Covered might become non-zero.
This looks correct.
Final check on language:
Python is the best default. I will present that.
What if the user wants C++?
I'll stick to Python but mention it's the Hungarian algorithm so they can look it up in other languages.
Double check the scipy function name.
It's scipy.optimize.linear_sum_assignment.
If cost matrix is not square, it handles rectangular.
Input cost_matrix, returns row_ind, col_ind.
Code organization:
I'll wrap the raw algorithm in a nice function solve_assignment(cost_matrix).
Let's write the actual code logic for the "Manual" version to ensure it works.
States:
STAR = 1PRIME = 2mask: N x N matrix.
row_cover: N array.
col_cover: N array.
Steps:
step1: Row min reduction.
step2: Col min reduction.
step3: Find zeros. Greedily star them. Cover columns of starred zeros.
step4: Main loop.
If all cols covered -> Done.
Find uncovered zero (r,c).
If found:
Prime it.
If starred zero in row r at col cs:
Cover row , uncover col .
This seems solid. I will implement this logic.
One edge case: N×M where N=M.
The algorithm works for rectangular matrices if we pad with dummy rows/cols of zeros, or if the implementation handles it. For simplicity, I will assume square or handle rectangular by padding in the input processing.
I'll handle non-square by checking dimensions and padding to max(n, m) with zeros.
Let's refine the "Update weights" logic again.
Find min uncovered h.
Iterate all cells:
If row not covered and col not covered: val−=h.
If row covered and col covered: val+=h.
This creates new zero in uncovered area (the min uncovered becomes 0).
Okay, I'm ready to write. I will provide the Scipy version first for practicality, then the algorithmic version for completeness.
Here are two ways to solve the Assignment Problem in Python.
Method 1: Using scipy (Recommended)
If you are writing production code, you should use the scipy library. It is highly optimized (written in C) and uses the Hungarian Algorithm (also known as the Kuhn-Munkres algorithm).
Prerequisite:
bash
pip install scipy numpy
The Code:
python
import numpy as np
from scipy.optimize import linear_sum_assignment
def solve_assignment_scipy(cost_matrix):
# Convert to numpy array
cost = np.array(cost_matrix)
# The function returns the row indices and corresponding column indices.
row_ind, col_ind = linear_sum_assignment(cost)
# Calculate total cost
total_cost = cost[row_ind, col_ind].sum()
# Format the output
assignment = list(zip(row_ind, col_ind))
return total_cost, assignment
# Example Usage
# Rows = Workers, Columns = Jobs
costs = [
[9, 2, 7, 8],
[6, 4, 3, 7],
[5, 8, 1, 8],
[7, 6, 9, 4]
]
total, assign = solve_assignment_scipy(costs)
print(f"Total Cost: {total}")
print("Assignments (Worker, Job):")
for worker, job in assign:
print(f" Worker {worker} -> Job {job} (Cost: {costs[worker][job]})")
Method 2: From Scratch (Educational)
If you need to implement the algorithm yourself without external libraries, here is a clean implementation of the Hungarian Algorithm.
python
C[:,j]−=min(C[:,j])
j
Test for optimality:
Find the maximum number of independent zeros (zeros that don't share a row or column). This can be done using a bipartite matching algorithm (like Hopcroft-Karp or a DFS-based approach) on the graph where edges are zero-cost entries.
Alternatively, the standard way involves covering zeros with a minimum number of lines. If lines < n, adjust matrix.
Let's use the line-covering method as it's the standard "textbook" explanation.
Mark rows/cols.
Find minimum uncovered value.
Subtract from uncovered, add to intersections.
Assign:
Once optimality is reached (min lines = n), find the set of independent zeros.
i∈/R,j∈/C
m
x∈M
i∈/R
m
y∈M
j∈C
m
−m
val
val−m
val
val
m
val
Covered row, Covered col: Subtracts 0, adds m -> val+m.
r
cs
Repeat finding uncovered zero.
Else (no star in row):
Augmenting path.
Path starts at (r,c).
While path not empty:
Move along path (alternating Star, Prime).
Unstar Star nodes, Star Prime nodes.
Clear covers, clear primes.
Go to covering columns of starred zeros.
If not found:
Update weights (step 6).
Repeat finding uncovered zero.
import copy
class HungarianAlgorithm:
def __init__(self, cost_matrix):
# We work on a copy to avoid modifying the original input
self.cost_matrix = copy.deepcopy(cost_matrix)
self.n = len(cost_matrix)
self.m = len(cost_matrix[0])
# Pad matrix to be square if it isn't
max_dim = max(self.n, self.m)
for row in self.cost_matrix:
row.extend([0] * (max_dim - self.m))
self.cost_matrix.extend([[0] * max_dim for _ in range(max_dim - self.n)])
self.n = max_dim
# Stars represent assigned zeros, Primes represent potential alternates
self.starred = [[0] * self.n for _ in range(self.n)]
self.primed = [[0] * self.n for _ in range(self.n)]
self.row_covered = [False] * self.n
self.col_covered = [False] * self.n
def solve(self):
# Step 1: Subtract row minima
for r in range(self.n):
min_val = min(self.cost_matrix[r])
for c in range(self.n):
self.cost_matrix[r][c] -= min_val
# Step 2: Subtract column minima
for c in range(self.n):
min_val = min(self.cost_matrix[r][c] for r in range(self.n))
for r in range(self.n):
self.cost_matrix[r][c] -= min_val
# Step 3: Cover zeros with minimum lines (simplified heuristic approach)
# We find the initial stars
for r in range(self.n):
for c in range(self.n):
if self.cost_matrix[r][c] == 0 and not self.row_covered[r] and not self.col_covered[c]:
self.starred[r][c] = 1
self.row_covered[r] = True
self.col_covered[c] = True
# Reset covers for the algorithm steps
self.row_covered = [False] * self.n
self.col_covered = [False] * self.n
# Main Loop
step = 3
while step != -1:
if step == 3:
step = self.step3()
elif step == 4:
step = self.step4()
elif step == 5:
step = self.step5()
elif step == 6:
step = self.step6()
# Extract results
results = []
for r in range(self.n):
for c in range(self.n):
if self.starred[r][c] == 1:
results.append((r, c))
return results
def step3(self):
# Cover columns with starred zeros
for r in range(self.n):
for c in range(self.n):
if self.starred[r][c] == 1:
self.col_covered[c] = True
# If all columns covered, we are done
if all(self.col_covered):
return -1
return 4
def find_uncovered_zero(self):
for r in range(self.n):
if not self.row_covered[r]:
for c in range(self.n):
if not self.col_covered[c] and self.cost_matrix[r][c] == 0:
return r, c
return None
def step4(self):
while True:
zero = self.find_uncovered_zero()
if not zero:
return 6 # No uncovered zero, go to step 6
r, c = zero
self.primed[r][c] = 1 # Prime the zero
# Find starred zero in this row
star_col = -1
for i in range(self.n):
if self.starred[r][i] == 1:
star_col = i
break
if star_col != -1:
self.row_covered[r] = True
self.col_covered[star_col] = False
else:
# No starred zero in row -> Augmenting path found
self.path = [(r, c)]
return 5
def step5(self):
# Augmenting path algorithm
count = 0
while True:
r, c = self.path[-1]
# Find starred zero in column
found_star = False
for i in range(self.n):
if self.starred[i][c] == 1:
self.path.append((i, c))
found_star = True
break
if found_star:
# Find primed zero in row
for j in range(self.n):
if self.primed[self.path[-1][0]][j] == 1:
self.path.append((self.path[-1][0], j))
break
else:
break
# Unstar starred zeros and star primed zeros in path
for r, c in self.path:
if self.starred[r][c] == 1:
self.starred[r][c] = 0
else:
self.starred[r][c] = 1
# Clear covers and primes
self.row_covered = [False] * self.n
self.col_covered = [False] * self.n
for r in range(self.n):
for c in range(self.n):
self.primed[r][c] = 0
return 3
def step6(self):
# Find minimum uncovered value
min_val = float('inf')
for r in range(self.n):
if not self.row_covered[r]:
for c in range(self.n):
if not self.col_covered[c]:
if self.cost_matrix[r][c] < min_val:
min_val = self.cost_matrix[r][c]
# Adjust matrix
for r in range(self.n):
for c in range(self.n):
if self.row_covered[r]:
self.cost_matrix[r][c] += min_val
if not self.col_covered[c]:
self.cost_matrix[r][c] -= min_val
return 4
# --- Example Usage ---
costs = [
[90, 75, 75, 80],
[35, 85, 55, 65],
[125, 95, 90, 105],
[45, 110, 95, 115]
]
solver = HungarianAlgorithm(costs)
result = solver.solve()
print("Optimal Assignments (Row, Col):")
total_cost = 0
for r, c in result:
# Note: cost[r][c] uses original matrix values, not the modified internal ones
cost_val = costs[r][c]
total_cost += cost_val
print(f"Row {r} assigned to Col {c} (Cost: {cost_val})")
print(f"Total Cost: {total_cost}")