交换序列a,b中的元素,使|sum(a)-sum(b)|最小。

有两个序列a,b,大小都为n,序列元素的值任意整数,无序.

要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小。
例如:
int[] a = {100,99,98,1,2, 3};
int[] b = {1, 2, 3, 4,5,40};

求解思路:
当前数组a和数组b的和之差为
A = sum(a) - sum(b)
a的第i个元素和b的第j个元素交换后,a和b的和之差为
A' = sum(a) - a[i] + b[j] - (sum(b) - b[j] + a[i])
= sum(a) - sum(b) - 2 (a[i] - b[j])
= A - 2 (a[i] - b[j])
设x = a[i] - b[j], 则交换后差值变为 A’ = A - 2x

假设A > 0, 当x 在 (0,A)之间时,做这样的交换才能使得交换后的a和b的和之差变小,x越接近A/2效果越好,
如果找不到在(0,A)之间的x,则当前的a和b就是答案。
所以算法大概如下:

在a和b中寻找使得x在(0,A)之间并且最接近A/2的i和j,交换相应的i和j元素,重新计算A后,重复前面的步骤直至找不到(0,A)之间的x为止。


public void minDiff(int[] a, int[] b) { //get the summations of the arrays int sum1 = sum(a); int sum2 = sum(b); //we use big array to denote the array whose summation is larger. int[] big = b; int[] small = a; if (sum1 > sum2) { big = a; small = b; } // the boolean value shift is used to denote that whether there exists a pair of elements, ai and bj, such that (ai-bj) < diff/2; boolean shift = true; while (shift == true) { shift = false; int diff = sum(big) - sum(small); int maxDiff = Integer.MAX_VALUE; //pa and pb records the switch position int pa = -1; int pb = -1; //the two for loops are used to find the pair of elements ai and bj such that (ai-bj) < diff/2 when sum(a) > sum(b). for (int i = 0; i < big.length; i++) { for (int j = 0; j < small.length; j++) { if (big[i] > small[j]) { int tempDiff = Math.abs(diff - 2*(big[i] - small[j])); //the condition "tempDiff < diff" is very important, if such condition holds, we can switch the elements to make the difference smaller //otherwise, we can't, and we should quit the while loop if ((tempDiff < maxDiff) && tempDiff < diff) { shift = true; maxDiff = tempDiff; pa = i; pb = j; } } } } if (shift == true) { int temp = big[pa]; big[pa] = small[pb]; small[pb] = temp; } } }
参考: http://blog.csdn.net/v_july_v/article/details/6419466

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值