Problem 1:Balanced Partition
You have a set, A = {a1,···, an}, of n integers. Partition these integers into two subsets such that you minimize |S1 − S2|, where S1 and S2 denote the sums of the elements in each of the two subsets.
伪代码如下:
Array_Partition(s): sum = 0; for: i = 1 to n do sum += s[i] a[] = 0, b[] = 0 g[][] = g(n, sum / 2) g[0, 0] = 1 for i = 1 to n do for j = i down to 1 do for k = s[i] to sum / 2 do if g[j - 1, k - s[i]] == 1 then g[j, k] = 1 flag = false for i = sum / 2 down to 0 do if flag == true then break for j = n down to 0 do if g[j, i] == 1 then flag = true aval = i size = j break ans = sum - 2 * aval while aval > 0 do for int i = 1 to n do if aval >= s[i] & g[size - 1, aval - s[i]] == 1 then a[] += s[i] aval -= s[i] size-- break return a, b, ans
Problem 2Balanced Partition
You have a set, A = {a1,···, a2n}, of 2n integers. Partition these integers into two subsets,with each owns n elements, such that you minimize |S1 − S2|, where S1 and S2 denote the sums of the elements in each of the two subsets. 伪代码如下:
Array_Partition(s): a{} = 0, b{} = 0 sum = 0 for i = 1 to 2 * n do sum += s[i] g[][] = g(n, sum / 2) g[0, 0] = 1 for i = 1 to 2 * n do for j = min(i, n) down to 1 do for k = s[i] to sum / 2 do if g[j - 1, k - s[i]] == 1 then g[i, j] = 1 for i = sum / 2 down to 0 do if g[n, i] == 1 then ans = sum - 2 * i break t = n for i= sum / 2 down to 0 do if g[t, i] then for j = 1 to 2 * n do if i >= s[j] & g[t - 1][i - s[j]] a{} += s[j] t--, i -= s[j] break b = s - a return ans, a and b