def_heapify_down(self, index): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2
if left_index < len(self.heap) andself.heap[left_index] > self.heap[largest]: largest = left_index if right_index < len(self.heap) andself.heap[right_index] > self.heap[largest]: largest = right_index
if largest != index: self.heap[index], self.heap[largest] = self.heap[largest], self.heap[index] self._heapify_down(largest)
defquick_sort(arr): iflen(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(right)
def knapsack(values, weights, capacity):
n = len(values)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, capacity + 1):
if weights[i-1] <= w:
dp[i][w] = max(dp[i-1][w], dp[i-1][w - weights[i-1]] + values[i-1])
else:
dp[i][w] = dp[i-1][w]
return dp[n][capacity]
# 使用案例
values = [60, 100, 120