AcWing 91. 【python】最短Hamilton路径
原题链接
中等
作者:
tt2767
,
2019-12-03 23:19:42
,
所有人可见
,
阅读 1195
import re
import sys
def read(raw):
sbuffer = list()
for s in raw:
if re.match('\s', s) is None:
sbuffer.append(s)
elif len(sbuffer) > 0:
yield ''.join(sbuffer)
sbuffer = list()
yield ''.join(sbuffer)
def hamilton(n, weight):
f = [[float('inf')] * n for _ in range(1 << n)]
f[1][0] = 0
for i in range(1, 1<<n):
for j in range(n):
if (i >> j & 1) == 1:
for k in range(n):
if (((i - (1 << j)) >> k) & 1):
f[i][j] = min(f[i][j], f[i - (1 << j)][k] + weight[k][j])
return f[(1 << n)-1][n-1]
pin = read(sys.stdin.read())
n = int(pin.next())
weight = [[0]*n for _ in range(n) ]
for i in range(n):
for j in range(n):
weight[i][j] = int(pin.next())
print hamilton(n, weight)
python 3 no print, next(pin)
嗯嗯, 我用的python2
厉害了,我发现你java,python都在写