0w1

CFR 656 E. Out of Controls ( Python )

Problem - E - Codeforces

題意:
給一個 N * N 的鄰接矩陣表示 ( i, j ) 間的邊的距離。問最遠點對的距離為何。
但是,規定不能用類如 for, while, repeat 等關鍵詞 ( 詳見題目本身 )。

資料規模:
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.

解法:
以下兩個做法是用三重引號和 exec() 避免關鍵字裡的字符連在一起。
exec() 可以以字串為參數,動態執行參數的字串代表的 python 代碼。
Submission #17116768 - Codeforces
上面這個利用三重引號內可以再度使用三重引號的特性。
Submission #17098606 - Codeforces
這個利用 replace() 函數,將無用的字元 '@' 暫時夾在中間,最後再一併替換成空字串。
以下這個做法也是臨摹來的,python 真的可以只用 lambda 函數跟 map 等等達到迴圈的效果。
其中比較有趣的是 product 函數,可以支援類似 for 迴圈進行的陣列的乘法合併。

另外要注意第 9 行的部分,如果不用 list() 包住 map(),那麼 map() 只會是個物件,不會被呼叫到。

from itertools import product

def relax( D, f ):
  k, i, j = f
  D[ i ][ j ] = min( D[ i ][ j ], D[ i ][ k ] + D[ k ][ j ] )

N = int( input() )
D = list( map( lambda i: list( map( int, input().split() ) ), range( N ) ) )
list( map( lambda i: relax( D, i ), product( range( N ), range( N ), range( N ) ) ) )
print( max( map( max, D ) ) )