Ejemplo n.º 1
0
def formatPrint(prefix, data):
    if isMatrix(data):
        print('%s' % prefix)
        printMatrix(data)
    else:
        splitter = '\n' if isSpecialInstance(data) else '\t'
        print('%s%s%s' % (prefix, splitter, data))
Ejemplo n.º 2
0
def maximumTotalWeight(self, n, weights, tasks, p):
    items = [[tasks[i] * 2, weights[i]] for i in range(len(tasks))]
    knapsackValues = [[0 for _ in range(p + 1)] for _ in range(len(items) + 1)]
    for i in range(1, len(items) + 1):
        duration, value = items[i - 1]
        for d in range(1, p + 1):
            if duration > d:
                knapsackValues[i][d] = knapsackValues[i - 1][d]
            else:
                knapsackValues[i][d] = max(
                    knapsackValues[i - 1][d],
                    knapsackValues[i - 1][d - duration] + value)
    printMatrix(knapsackValues)
    return knapsackValues[-1][-1]
Ejemplo n.º 3
0
def maxWeightRef(self, n, weights, tasks, p):
    """
    0-1背包问题
    https://www.lintcode.com/problem/efficient-job-processing-service/description
    """
    dp = [[0] * (p // 2 + 1) for i in range(n + 1)]
    for i in range(1, n + 1, 1):
        for j in range(1, p // 2 + 1, 1):
            if (j < tasks[i - 1]):
                dp[i][j] = dp[i - 1][j]
            else:
                dp[i][j] = max(dp[i - 1][j],
                               dp[i - 1][j - tasks[i - 1]] + weights[i - 1])
    printMatrix(dp)
    return dp[n][p // 2]