-1

I´ve read at wiki http://en.wikipedia.org/wiki/Subset_sum_problem#Pseudo-polynomial_time_dynamic_programming_solution about the sumsubsetproblem and wonder if i can adapt it to the following problem:

I need all possible subsets ss1, ss2 restricted by n1, n2 being the number of elements out of 2 sets s1,s2

I will use the elements of S1 as positive elements and the elements of s2 as negative elements to answer the question if the subsets of size n1 and n2 have sum equal 0

My special problem here is that the sets can contain 0 itselfs and i thought i solve this by setting these elements to 1 or -1 repectivly ( 1 is not a member of my input, which will be (0,10,50,100,200,500) ) and the next problem is that this algorithm gives me yes or no only, but i know this answer already ( its a precondition ) what i need is the results.

Is this still fast enough ? i ´ve read here about an perl implementation where the OP posted a list with runtimes an 30 elements had a computation time of 30-40 seconds wich is far too slow for my needs and i need to implement in java, wich is, as far as i know even slower then perl

regards

dirk

user2792876
  • 31
  • 1
  • 5

1 Answers1

0

Consider each of S1 and S2 in turn. As in the subset sum problem, you can create an array which tells you which numbers you can compute by adding together any possible subset of the elements of S1 (and similarly for S2). You can keep an extra flag which tells you if you can get the result zero by adding together one or more elements of S1 (and similarly for S2).

Now all you need to do is to go through the results of the two arrays trying to find two numbers that add up to zero, and find out if both zero flags are set.

I don't know how long this will take, but I would expect a JVM on a desktop to be faster than Perl, because JVMs on desktops have Just-In-Time compilers. I would expect the time of generating each array of possible sums to go up with the size of the set times the number of possible sums, which will be roughly the same as the size of the maximum possible sum, unless the numbers in the set are very different.

mcdowella
  • 19,301
  • 2
  • 19
  • 25