Dynamic programming--triangle splitting

來源:互聯網
上載者:User

標籤:


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.