AcWing 2193. 分配问题(二分图完美匹配KM算法python实现)
原题链接
困难
作者:
endinggy
,
2021-05-28 00:26:04
,
所有人可见
,
阅读 527
n = int(input())
a = []
for _ in range(n):
a.append(list(map(int, input().split())))
vis = [0] * 2 * n
val = [max(a[i]) for i in range(n)]
cp = [-1] * 2 * n
val.extend([0] * n)
delta = 0
def dfs(u):
global delta
vis[u] = 1
for v in range(n):
tmp_delta = val[u] + val[v+n] - a[u][v]
v += n
if tmp_delta == 0:
if vis[v] == 1:
continue
vis[v] = 1
if cp[v] == -1 or dfs(cp[v]):
cp[v] = u
cp[u] = v
return True
elif tmp_delta < delta:
delta = tmp_delta
return False
INF = 1E6
def km():
global delta, vis, cp
cp = [-1] * 2 * n
for u in range(n):
while True:
delta = INF
vis = [0] * 2 * n
if dfs(u):
break
for i in range(n):
if vis[i] == 1:
val[i] -= delta
if cp[i] != -1:
val[cp[i]] += delta
res = 0
for i in range(n):
if cp[i] != -1:
res += a[i][cp[i] - n]
return res
res1 = km()
for i in range(n):
for j in range(n):
a[i][j] = - a[i][j]
val = [max(a[i]) for i in range(n)]
val.extend([0] * n)
res2 = -km()
print(res2)
print(res1)