python-3.xalgorithmknapsack-problem

knapsack problem - how to cut memory usage


You have 𝑛 items. Each object has a weight, the weight of the object numbered 𝑖 is equal to π‘₯_𝑖. You need to put them in a backpack that holds no more than 𝑆g. At the same time, you want the TOTAL WEIGHT of ALL items in the backpack to be as large as possible and at the same time it (the total weight) to be ODD. If you cannot put an odd weight, you will enter 0.

Input data The first line gives the number of available items 0≀𝑛≀25. The second line lists 𝑛 numbersβ€”the weights of the objects. The weights of the items do not exceed 10^9. The third line contains the number 0≀𝑆≀10^18, a limit on the total weight of the items that will be placed in the backpack.

Output On the first line print the largest odd total weight of objects that can be put in a backpack.

**MY SOLUTION **

import sys

def max_odd_weight(n, weights, S):
    possible_sums = {0}  
  
    for weight in weights:
        current_sums = set(possible_sums)  
        for w in current_sums:
            new_sum = w + weight
            if new_sum <= S:
                possible_sums.add(new_sum)  

    max_odd_weight = 0
    for w in possible_sums:
        if w % 2 != 0 and w > max_odd_weight:
            max_odd_weight = w

    return max_odd_weight

n = int(sys.stdin.readline())
weights = list(map(int, sys.stdin.readline().split()))
S = int(sys.stdin.readline())

result = max_odd_weight(n, weights, S)
sys.stdout.write(str(result))

It's really fast BUT I have a problem passing tests (All correct but memory limit exceeded). Test data is hidden. How can I cut the usage of memory even more?

time limit for test - 3 seconds Memory limit per test - 256 megabytes input - standard input output - standard output

using SYS helped, but not much


Solution

  • The constraints on the problem mean that there could be over 34 million possible sums, which won't fit in memory if you use the standard dynamic programming solution for 0-1 knapsack.

    There are a limited number of items, though, so I suggest recursive backtracking instead, like this:

    import sys
    
    def max_weight(weights, start, limit, odd):
        result = None if odd else 0
        for i in range(start, len(weights)):
            w = weights[i]
            if w <= limit:
                testodd = not odd if (w%2)==1 else odd
                test = max_weight(weights, i+1, limit-w, testodd)
                if test != None:
                    test += w
                    if (result == None or test > result):
                        result = test
        return result
    
    n = int(sys.stdin.readline())
    weights = list(map(int, sys.stdin.readline().split()))
    S = int(sys.stdin.readline())
    
    result = max_weight(weights, 0, S, True)
    sys.stdout.write(str(result))