from collections import namedtuple Result = namedtuple("Result", ['objective', 'is_optimal', 'xs']) Item = namedtuple("Item", ['index', 'value', 'weight']) Knapsack = namedtuple("Knapsack", ['count', 'capacity', 'items']) Node = namedtuple("Node", ['index', 'value', 'room', 'estimate', 'path']) def solve_knapsack_greedy(knapsack): remaining_capacity = knapsack.capacity current_value = 0 xs = [0] * knapsack.count for item in knapsack.items: if remaining_capacity >= item.weight: remaining_capacity -= item.weight current_value += item.value xs[item.index] = 1 return Result(current_value, 0, xs) def solve_knapsack_dynamic(knapsack): value_column = [0 for _ in range(knapsack.capacity + 1)] # Keep track for each item for what capacities we take # the respective item. This allows us to backtrack the items # for the optimal solution later. item_taken = {i: set() for i in range(len(knapsack.items))} for item in knapsack.items: new_column = list(value_column) for capacity in range(knapsack.capacity + 1): if item.weight <= capacity: # Calculate the new value for the capacity if we take the item. new_value = item.value + value_column[capacity - item.weight] if new_value > value_column[capacity]: new_column[capacity] = new_value item_taken[item.index].add(capacity) # There is no else case because new_colum contains the right values # from the previous item so we only have to update when the new # value is better. value_column = new_column objective = value_column[-1] # Dynamic programing computes the best posible solution. is_optimal = 1 # Reconstruct which items are used for the optimal solution. xs = [] current_index = knapsack.items[-1].index current_capacity = knapsack.capacity while current_index >= 0: if current_capacity in item_taken[current_index]: current_capacity -= knapsack.items[current_index].weight xs.append(1) else: xs.append(0) current_index -= 1 xs.reverse() return Result(objective, is_optimal, xs) def solve_knapsack_depth_first_search(knapsack): knapsack.items.sort(key=lambda item: item.value / float(item.weight), reverse=True) def get_estimate(current_value, current_index, remaining_capacity): estimated_value = current_value for item in knapsack.items[current_index:]: if item.weight <= remaining_capacity: estimated_value += item.value remaining_capacity -= item.weight else: v = int((remaining_capacity / float(item.weight)) * item.value) estimated_value += v return estimated_value return estimated_value estimate = get_estimate(0, 0, knapsack.capacity) nodes = [Node(0, 0, knapsack.capacity, estimate, [])] num_items = len(knapsack.items) best_value = 0 best_path = [] while nodes: current_node = nodes.pop() current_index = current_node.index if current_node.room < 0: continue if current_node.estimate < best_value: continue if current_node.value > best_value: best_value = current_node.value best_path = list(current_node.path) if current_index == num_items: continue current_item = knapsack.items[current_index] # Right child - do not take current_item new_index = current_index + 1 new_value = current_node.value new_room = current_node.room new_estimate = get_estimate(new_value, new_index, new_room) if new_estimate > best_value: new_path = current_node.path + [0] r = Node(new_index, new_value, new_room, new_estimate, new_path) nodes.append(r) # Left child - take current_item new_index = current_index + 1 new_room = current_node.room - current_item.weight if new_room >= 0: new_value = current_node.value + current_item.value new_estimate = get_estimate(new_value, new_index, new_room) new_path = current_node.path + [1] n = Node(new_index, new_value, new_room, new_estimate, new_path) nodes.append(n) # If we sort the items by estimate here it becomes # best first search. # nodes.sort(key=lambda node: node.estimate) def correct_path(path): path = path + [0] * (num_items - len(path)) values = zip(path, knapsack.items) path = [v[0] for v in sorted(values, key=lambda value: value[1].index)] return path return Result(best_value, 0, correct_path(best_path)) def input_data_to_knapsack(input_data): lines = input_data.split('\n') item_count, capacity = map(int, lines[0].split()) items = [] for i in range(1, item_count + 1): line = lines[i] value, weight = map(int, line.split()) items.append(Item(i - 1, value, weight)) k = Knapsack(item_count, capacity, items) return k def result_to_output_data(result): # prepare the solution in the specified output format output_data = str(result.objective) + ' ' + str(result.is_optimal) + '\n' output_data += ' '.join(map(str, result.xs)) return output_data if __name__ == '__main__': file_location = "./data/ks_60_0" with open(file_location, 'r') as input_data_file: input_data = input_data_file.read() k = input_data_to_knapsack(input_data) print(result_to_output_data(solve_knapsack_dynamic(k))) print(result_to_output_data(solve_knapsack_depth_first_search(k)))