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

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 
				 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值