سؤال

i came across alternate way of solving sum-suset problem using bitset.

Here is the link for the solution :-

variation of sum-subset problem solution link

Problem description is given in below link :-

Problem statement

Unfortunately i am not able to understand the solution using bitset. Need your help

هل كانت مفيدة؟

المحلول

To pack each boot equally, you need each to get half the total sum of luggage weights.

To check if this is possible, you need to know if some subset adds to sum/2.

We will build a set of numbers reachable with the luggage we have seen so far. To do that you should see that if I had such a set, and a new piece of luggage, then I could now reach any value in the old set, and also any of those values plus the weight of the new item.

This key step is done in the code with this:

    b |= b << luggage ;

This is equivalent to:

    newReachable = b<<luggage
    b |= newReachable

Firstly, b << luggage takes the current set of reachable numbers b and right shifts that by luggage bits. Think we just read a 5 kg bag, this would take each bit originally set, and make the one 5 higher set instead.

Then the b |= newReachable says that we can reach all the newly reachable ones, and we can still reach all the previously reachable ones, thus we want to logically union the sets together, which is what the bitwise-or operator does.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top