现在的位置: 首页 > 综合 > 正文

交换序列a,b中的元素,使|sum(a)-sum(b)|最小 [No. 49]

2014年09月05日 ⁄ 综合 ⁄ 共 1546字 ⁄ 字号 评论关闭

有两个序列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 static void minDiff(int[] a, int[] b) {
	//get the summations of the arrays		
	int sum1 = sum(a);
	int sum2 = sum(b);
	if (sum1 == sum2) return;
	
	//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;
	int diff = 1; 
	while (shift == true  && diff > 0) {
		shift = false;
		diff = sum(big) - sum(small);
		if (diff < 0) return;
		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;
		}
	}
 }

抱歉!评论已关闭.