-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathwork_dispatch.py
50 lines (44 loc) · 1.46 KB
/
work_dispatch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
''' mbinary
#########################################################################
# File : work_dispatch.py
# Author: mbinary
# Mail: [email protected]
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2019-04-16 09:41
# Description:
#########################################################################
'''
'''
设有n件工作要分配给n个人去完成,将工作i分配给第j个人所需费用为c_ij 。试设计一个算法,为每个人分配1件不同的工作,并使总费用达到最小。
'''
import random
def dispatch(mat):
'''mat: matrix of c_ij'''
def _util(i, arrange, cost):
''' for i-th work'''
nonlocal total, used, rst
if i == n:
total = cost
rst = arrange.copy() # copy is needed
else:
for j in range(n):
if not used[j] and(total is None or cost+mat[i][j] < total):
used[j] = True
arrange[i] = j
_util(i+1, arrange, cost+mat[i][j])
used[j] = False
total = None
rst = None
n = len(mat)
used = [False for i in range(n)]
_util(0, [-1]*n, 0)
return total, rst
if __name__ == '__main__':
n = 10
mat = [[random.randint(1, 100) for i in range(n)] for i in range(n)]
print('work matrix: c_ij: work_i and person_j')
for i in range(n):
print(mat[i])
print('result: ', end='')
print(dispatch(mat))