I have this homework assignment that I think I managed to solve, but am not entirely sure as I cannot prove my solution. I would like comments on what I did, its correctness and whether or not there's a better solution.
The problem is as follows: we have N
groups of people, where group i
has g[i]
people in it. We want to put these people on two rows of S
seats each, such that: each group can only be put on a single row, in a contiguous sequence, OR if the group has an even number of members, we can split them in two and put them on two rows, but with the condition that they must form a rectangle (so they must have the same indices on both rows). What is the minimum number of seat开发者_StackOverflow社区s S
needed so that nobody is standing up?
Example: groups are 4 11
. Minimum S
is 11
. We put all 4
in one row, and the 11
on the second row. Another: groups are 6 2
. We split the 6
on two rows, and also the two. Minimum is therefore 4
seats.
This is what I'm thinking:
Calculate T = (sum of all groups + 1) / 2
. Store the group numbers in an array, but split all the even values x
in two values of x / 2
each. So 4 5
becomes 2 2 5
. Now run subset sum on this vector, and find the minimum value higher than or equal to T
that can be formed. That value is the minimum number of seats per row needed.
Example: 4 11 => 2 2 11 => T = (15 + 1) / 2 = 8
. Minimum we can form from 2 2 11
that's >= 8
is 11
, so that's the answer.
This seems to work, at least I can't find any counter example. I don't have a proof though. Intuitively, it seems to always be possible to arrange the people under the required conditions with the number of seats supplied by this algorithm.
Any hints are appreciated.
I think your solution is correct. The minimum number of seats per row in an optimal distribution would be your T (which is mathematically obvious).
Splitting even numbers is also correct, since they have two possible arrangements; by logically putting all the "rectangular" groups of people on one end of the seat rows you can also guarantee that they will always form a proper rectangle, so that this condition is met as well.
So the question boils down to finding a sum equal or as close as possible to T (e.g. partition problem).
Minor nit: I'm not sure if the proposed solution above works in the edge case where each group has 0
members, because your numerator in T = SUM ALL + 1 / 2
is always positive, so there will never be a subset sum that is greater than or equal to T
.
To get around this, maybe a modulus operation might work here. We know that we need at least n
seats in a row if n
is the maximal odd term, so maybe the equation should have a max(n * (n % 2))
term in it. It will come out to max(odd)
or 0. Since the maximal odd term is always added to S
, I think this is safe (stated boldly without proof...).
Then we want to know if we should split the even terms or not. Here's where the subset sum approach might work, but with T
simply equal to SUM ALL / 2
.
精彩评论