简体   繁体   English

Python中的动态编程实现

[英]Dynamic Programming Implementation in Python

I am trying to solve this problem我正在努力解决这个问题

在此处输入图片说明

This is the Python code and I am having trouble figuring out dp[i][j].这是 Python 代码,我在计算 dp[i][j] 时遇到了麻烦。 This is supposed to be the minimum cost for the first j city centers with i shops.这应该是前 j 个拥有 i 个商店的城市中心的最低成本。

# A an integer array for city centers
# k an integer number of shops
# return  an integer
def groceryShops(A, k):
    # Write your code here
    if not A:
        return 0

    n = len(A) # n is the number of city centers.

    if k >= n: # we should not have more shops than city centers.
        return 0

    A.sort()
    cost = [[0 for _ in range(n + 1)] for _ in range(n + 1)]

    """
    cost[i][j] is the minimum cost to build a shop between city centers i and j
    This shop should be in the median of the city centers.
    """
    for i in range(n):
        for j in range(i, n):
            mid = int(i + (j - i) / 2)
            print("i= ", i, " j= ", j, "Median is: ", mid, " Center:",  A[mid], "\n")

            for r in range(i, mid + 1):
                cost[i + 1][j + 1] += A[mid] - A[r]
                print("dist of ", A[mid] ," --to-> " ,  A[r], " Right ", cost[i + 1][j + 1])
            for r in range(mid + 1, j + 1):
                cost[i + 1][j + 1] += A[r] - A[mid]
                print("dist of ",  A[mid] ," <--to-- " ,  A[r], " Left ", cost[i + 1][j + 1])
            print("COST: ", "(", A[i ], "," ,A[j], " )", cost[i + 1][j + 1], "\n\n")


    # print("cost")
    # for row in cost:
    #   for c in row:
    #     print(c, end = " ")
    #   print()
    """
    dp[i][j] is the minimum cost for the first j city centers with i shops.
    """
    dp = [[float('inf') for _ in range(n + 1)] for _ in range(k + 1)]
    dp[0][0] = 0

    for i in range(1, k + 1):
        for j in range(1, n + 1):
            for r in range(j):
                dp[i][j] = ???  # only fill this gap :), min or max of some values using i, j and r?

    # print("\n\nDP Table")
    # for row in dp:
    #   for c in row:
    #     print(c, end = "       ")
    #   print("\n")

    return dp[-1][-1]

The following input k = 5, a = [1, 2, 3, 6, 7, 9, 11, 21, 40, 50] should produce an output of 9.以下输入k = 5, a = [1, 2, 3, 6, 7, 9, 11, 21, 40, 50]应产生输出 9。

As @Kenny Ostrom said, you have to get into the code by actually going through the debugger and checking your data structures while you do that and compare it with the actual task you wanted it to do.正如@Kenny Ostrom 所说,您必须通过实际通过调试器并在执行此操作时检查您的数据结构并将其与您希望它执行的实际任务进行比较来进入代码。

Although, I did read the code and the time complexity is O(nk) :)虽然,我确实阅读了代码,时间复杂度是 O(nk) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM