码迷,mamicode.com
首页 > 其他好文 > 详细

Dynamic programming--triangle splitting

时间:2016-05-04 21:09:27      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:


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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!