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

来源:互联网 发布:奥运会男篮vs美国数据 编辑:程序博客网 时间:2024/04/30 06:35
有两个序列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为止。

[java] view plaincopy
  1. public static void minDiff(int[] a, int[] b) {  
  2.     //get the summations of the arrays        
  3.     int sum1 = sum(a);  
  4.     int sum2 = sum(b);  
  5.     if (sum1 == sum2) return;  
  6.       
  7.     //we use big array to denote the array whose summation is larger.  
  8.     int[] big = b;  
  9.     int[] small = a;  
  10.     if (sum1 > sum2) {         
  11.         big = a;  
  12.         small = b;  
  13.     }   
  14.     // the boolean value "shift" is used to denote that whether there exists   
  15.     // a pair of elements, ai and bj, such that (ai-bj) < diff/2;  
  16.     boolean shift = true;  
  17.     int diff = 1;   
  18.     while (shift == true  && diff > 0) {  
  19.         shift = false;  
  20.         diff = sum(big) - sum(small);  
  21.         if (diff < 0return;  
  22.         int maxDiff = Integer.MAX_VALUE;  
  23.         //pa and pb records the switch position  
  24.         int pa = -1;  
  25.         int pb = -1;  
  26.         //the two for loops are used to find the pair of elements ai and bj   
  27.         //such that (ai-bj) < diff/2 when sum(a) > sum(b).  
  28.         for (int i = 0; i < big.length; i++) {  
  29.             for (int j = 0; j < small.length; j++) {  
  30.                 if (big[i] > small[j]) {  
  31.                     int tempDiff = Math.abs(diff - 2*(big[i] - small[j]));  
  32.                     //the condition "tempDiff < diff" is very important, if such condition holds,                          
  33.                     //we can switch the elements to make the difference smaller  
  34.                     //otherwise, we can't, and we should quit the while loop  
  35.                     if (tempDiff < maxDiff && tempDiff < diff) {  
  36.                         shift = true;  
  37.                         maxDiff = tempDiff;  
  38.                         pa = i;pb = j;  
  39.                     }  
  40.                 }  
  41.             }  
  42.         }  
  43.         if (shift == true) {  
  44.             int temp = big[pa];  
  45.             big[pa] = small[pb];  
  46.             small[pb] = temp;  
  47.         }  
  48.     }  
  49.  } 

原创粉丝点击