标签:
weight_polygon = [
[0, 2, 2, 3, 1, 4],
[2, 0, 1, 5, 2, 3],
[2, 1, 0, 2, 1, 4],
[3, 5, 2, 0, 6, 2],
[1, 2, 1, 6, 0, 1],
[4, 3, 4, 2, 1, 0]]
polygon_split = [[0 for col in range(6)] for row in range(6)]
print polygon_split
split = [[0 for col in range(6)] for row in range(6)]
def weight(a, b, c):
return weight_polygon[a][b] + weight_polygon[a][c] + weight_polygon[b][c]
def minimum(polygon, n):
for i in range(1, n):
polygon_split[i][i] = 0
for r in range(2, n+1):
for i in range(1, n-r+1+1):
j = i + r - 1
k = i + 1
if (k < n and j < n):
polygon_split[i][j] = polygon_split[i+1][j] + \
weight(i-1, i, j)
split[i][j] = i
while(k < j and j < n and k < n):
cur_val = polygon_split[i][k] + \
polygon_split[k+1][j] + weight(i-1, k, j)
if cur_val < polygon_split[i][j]:
polygon_split[i][j] = cur_val
split[i][j] = k
k = k + 1
return polygon_split[1][n-1]
def trace(i, j, s):
if i == j:
return
trace(i, s[i][j], s)
trace(s[i][j]+1, j, s)
print i-1, j, s[i][j], weight(i-1, j, s[i][j])
print minimum(weight_polygon, 6)
print trace(1, 5, split)
print polygon_split
Dynamic programming--triangle splitting
标签:
原文地址:http://www.cnblogs.com/zhaodonglin/p/5459693.html