和差值最小的数组划分问题

来源:互联网 发布:淘大象软件下载 编辑:程序博客网 时间:2024/06/07 02:35

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 dosum += s[i]a[] = 0, b[] = 0g[][] = g(n, sum / 2)g[0, 0] = 1for i = 1 to n dofor j = i down to 1 dofor k = s[i] to sum / 2 doif g[j - 1, k - s[i]] == 1 theng[j, k] = 1flag = falsefor i = sum / 2 down to 0 doif flag == true then break for j = n down to 0 do if g[j, i] == 1 then flag = trueaval = isize = jbreakans = sum - 2 * avalwhile aval > 0 dofor int i = 1 to n doif aval >= s[i] & g[size - 1, aval - s[i]] == 1 then a[] += s[i] aval -= s[i] size-- breakreturn a, b, ans

Problem 2:Balanced 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 = 0for i = 1 to 2 * n dosum += s[i]g[][] = g(n, sum / 2)g[0, 0] = 1for i = 1 to 2 * n dofor j = min(i, n) down to 1 dofor k = s[i] to sum / 2 doif g[j - 1, k - s[i]] == 1 theng[i, j] = 1for i = sum / 2 down to 0 doif g[n, i] == 1 thenans = sum - 2 * ibreakt = nfor i= sum / 2 down to 0 doif g[t, i] thenfor j = 1 to 2 * n doif i >= s[j] & g[t - 1][i - s[j]]a{} += s[j]t--, i -= s[j]breakb = s - areturn ans, a and b  


0 0
原创粉丝点击