divide S by the number of columns, let's call this M.
find a set of values of which the sum is M or as close as possible to M, using a knapsack algorithm (e.g. http://search.cpan.org/~andale/Algorithm-Knapsack-0.02/lib/Algorithm/Knapsack.pm (just a quick Google on knapsack))
take the sum of the set of values and subtract it from S, let's call it T.