给定一个二维数组,大小为N*N 的arr ,其中arr[i][j]表示第i个工人完成第j个工作的成本。可以指派任何工人执行任何工作。任务是分配工作,使得只有一名工人可以执行一项工作,从而使分配的总成本最小化。
例子
Input: arr[][] = {{3, 5}, {10, 1}}
Output: 4
Explanation: The optimal assignment is to assign job 1 to the 1st worker, job 2 to the 2nd worker.
Hence, the optimal cost is 3 + 1 = 4.
Input: arr[][] = {{2500, 4000, 3500}, {4000, 6000, 3500}, {2000, 4000, 2500}}
Output: 4
Explanation: The optimal assignment is to assign job 2 to the 1st worker, job 3 to the 2nd worker and job 1 to the 3rd worker.
Hence, the optimal cost is 4000 + 3500 + 2000 = 9500.
本文讨论了解决此问题的不同方法。
做法:思路是用匈牙利算法来解决这个问题。算法如下:
- 对于矩阵的每一行,找到最小的元素并从其行中的每个元素中减去它。
- 对所有列重复步骤 1。
- 使用最少数量的水平线和垂直线覆盖矩阵中的所有零。
- 最优性检验:如果覆盖线的最小数量为N ,则最优分配是可能的。否则,如果行小于N ,则未找到最佳分配,必须继续执行步骤 5。
- 确定未被任何行覆盖的最小条目。从每个未覆盖的行中减去此条目,然后将其添加到每个覆盖的列中。返回步骤 3。
考虑一个示例来理解该方法:
Let the 2D array be:
2500 4000 3500
4000 6000 3500
2000 4000 2500
Step 1: Subtract minimum of every row. 2500, 3500 and 2000 are subtracted from rows 1, 2 and 3 respectively.
0 1500 1000
500 2500 0
0 2000 500
Step 2: Subtract minimum of every column. 0, 1500 and 0 are subtracted from columns 1, 2 and 3 respectively.
0 0 1000
500 1000 0
0 500 500
Step 3: Cover all zeroes with minimum number of horizontal and vertical lines.
Step 4: Since we need 3 lines to cover all zeroes, the optimal assignment is found.
2500 4000 3500
4000 6000 3500
2000 4000 2500
So the optimal cost is 4000 + 3500 + 2000 = 9500
为了实现上述算法,想法是使用dlib 库中定义的max_cost_assignment()函数。该函数是在O(N 3 )时间内运行的匈牙利算法(也称为 Kuhn-Munkres 算法)的实现。它解决了最优分配问题。
下面是上述方法的实现:
Python
# Python program for the above approach
import dlib
# Function to find out the best
# assignment of people to jobs so that
# total cost of the assignment is minimized
def minCost(arr):
# Call the max_cost_assignment() function
# and store the assignment
assignment = dlib.max_cost_assignment(arr)
# Print the optimal cost
print(dlib.assignment_cost(arr, assignment))
# Driver Code
# Given 2D array
arr = dlib.matrix([[3, 5], [10, 1]])
# Function Call
minCost(arr)
4
时间复杂度: O(N 3 )
辅助空间: O(N 2 )
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。