用回溯法(backtracking)解决平衡集合问题(一道微软公司面试题)

来源:互联网 发布:tcp默认端口号 编辑:程序博客网 时间:2024/05/17 23:34

(原题出自微软公司面试题)问题如下:

有两个序列a,b,大小都为n,序列元素的值任意整数,无序;
要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小。
例如:   
var a=[100,99,98,1,2, 3];
var b=[1, 2, 3, 4,5,40];

 

分析:

通过交换的方式,最终的状态是在保证两个序列中元素个数相同的条件下,任何一个元素都可以位于两个序列中的任何一个。这样问题可以转化为:在一个长度为2*n的整数序列中,如何将元素个数分成两个子集,记每个子集的元素之和分别为S1和S2,使得|S1-S2|最小。显然这是一个最优化问题,如果用brute-force方法,组合数是C(2n,n)=(2n)!/(2*(n!)), 如果n很大这个方法不奏效。

 

这里采用回溯法(backtracking),即前序(preorder)遍历状态空间树(state-space tree)。难点在于剪枝条件的确定,下面说明如何确定剪枝条件:

注意到如果将原序列按从小到大的顺序排好序,每次从较大的元素开始取,可以得到一个这样的规律:设长度为2*n序列的元素总和为Sigma,当前集合元素的和为S,剩下的元素之和为Sigma-S,如果二者满足S>=Sigma-S,即Sigma<=2*S,那么在当前集合中剩下需要添加进来的元素必须从余下的元素中取最小的那些元素,这样才能保证|S1-S2|最小。这是因为如果在下一次任意从余下的元素中取的元素分别为e和f,那么取e后的两个子集差为(S+e) - (Sigma-S-e) = 2S-Sigma +2e,取f后的两个子集差为2S-Sigma +2f,显然如果e>f>0, 则有前者的子集差大于后者的子集差(注意这里假设元素都为非负整数,原序列中有负数的情况参考下面的讨论)。

 

如果输入序列中有负整数,可以通过平移操作转化为非负,因为每个数都平移了,它们的差值保值不变。如果不平移,结果不一定正确,比如:输入的2*n序列为:-10,5,3,20,25,50,平衡的对半子集应该为[-10,5,50]和[3,20,25],差值的绝对值为3。在下面的实现中,如果不考虑平移,得到的错误结果却是[-10,3,50]和[5,20,25],差值的绝对值为7。

 

另外在状态空间树只需要考虑根节点的左枝子树,因为原问题考虑的是对半子集。

 

[java] view plaincopy
  1. import java.util.Arrays;  
  2. import java.util.Stack;  
  3. /** 
  4.  *  
  5.  * @author ljs  
  6.  * 2011-05-20 
  7.  * 平衡集合问题 
  8.  * 
  9.  */  
  10. public class BalancedSet {  
  11.     //the offset to eliminate negative integers  
  12.     int OFFSET;  
  13.     int[] A;  
  14.     //the total value of the two sets  
  15.     int sigma;  
  16.     //the number of elements in each set  
  17.     int N;  
  18.     //positive value  
  19.     int minDiff=Integer.MAX_VALUE;  
  20.     Stack<Integer> tracer = new Stack<Integer>();  
  21.     Stack<Integer> bestDiffStack = new Stack<Integer>();  
  22.       
  23.       
  24.     public BalancedSet(int[] A) throws Exception{  
  25.         this.A = A;  
  26.         this.init();          
  27.     }  
  28.     private void init() throws Exception{  
  29.         if(A.length % 2 != 0)  
  30.             throw new Exception();  
  31.         N = A.length / 2;     
  32.                   
  33.         //sort A in ascending order  
  34.         Arrays.sort(A);  
  35.           
  36.         //offset if possible  
  37.         if(A[0]<0){  
  38.             OFFSET = -A[0];  
  39.             for(int i=0;i<A.length;i++){  
  40.                 A[i] += OFFSET;  
  41.             }  
  42.         }  
  43.         //sigma is the total value after offset is done  
  44.         for(int i=0;i<A.length;i++){  
  45.             sigma += A[i];  
  46.         }             
  47.     }  
  48.       
  49.     private void print(){  
  50.           
  51.         System.out.format("best partition difference is: %d%n",minDiff);  
  52.           
  53.         //caculate the difference of two sets  
  54.         int[] P = new int[N];  
  55.         int p=0;  
  56.         int i=0,j=bestDiffStack.size()-1;  
  57.           
  58.         //note: bestDiffStack is in descending order, we need an ascending order to compare with A        
  59.         for(;i<A.length && j>=0;){  
  60.             if(A[i]==bestDiffStack.get(j)){  
  61.                 i++;  
  62.                 j--;  
  63.             }else if(A[i] < bestDiffStack.get(j)){  
  64.                 P[p++] = A[i++];  
  65.             }//else: impossible case                  
  66.         }  
  67.         if(i<A.length){  
  68.             P[p++] = A[i++];  
  69.         }  
  70.           
  71.         System.out.println("One set is: ");  
  72.         while(!bestDiffStack.isEmpty())  
  73.             System.out.format(" %2d",bestDiffStack.pop()-OFFSET);         
  74.         System.out.println();  
  75.         System.out.println("Another set is: ");  
  76.         for(p=0;p<N;p++){  
  77.             System.out.format(" %2d",P[p]-OFFSET);        
  78.         }  
  79.     }  
  80.       
  81.       
  82.       
  83.     public void solve(int[] A){  
  84.         //the first node is not needed to analyse the include=false case  
  85.         check(A.length-100true);  
  86.         print();  
  87.     }  
  88.     //A is sorted in ascending order  
  89.     //count: the searched number of elements (<=N)  
  90.     //include: is the element i included in the set  
  91.     private void check(int i,int sum,int count,boolean include){          
  92.         if(include){  
  93.             //record the node  
  94.             tracer.push(A[i]);  
  95.               
  96.             sum += A[i];  
  97.             count++;  
  98.         }  
  99.         if(count==N){  
  100.             int diff = Math.abs(2*sum- sigma);  
  101.             if(diff < minDiff){  
  102.                 minDiff = diff;               
  103.                 //record the best nodes until now  
  104.                 bestDiffStack.clear();  
  105.                 for(Integer k:tracer){  
  106.                     bestDiffStack.add(k);  
  107.                 }  
  108.             }//else: just throw away this combination                 
  109.         }else{  
  110.             if(sigma<=2*sum){  
  111.                 //prune the tree: choose the remaining least numbers  
  112.                 int remainCount = N-count;  
  113.                 for(int j=0;j<remainCount;j++){  
  114.                     sum += A[j];  
  115.                 }  
  116.                 int diff = Math.abs(2*sum- sigma);  
  117.                 if(diff < minDiff){  
  118.                     minDiff = diff;  
  119.                     //record the nodes "1...remainCount"  
  120.                     bestDiffStack.clear();  
  121.                     for(Integer k:tracer){  
  122.                         bestDiffStack.add(k);  
  123.                     }  
  124.                     for(int j=remainCount-1;j>=0;j--){  
  125.                         bestDiffStack.push(A[j]);  
  126.                     }                     
  127.                 }//else: just throw away this combination                     
  128.             }else{  
  129.                 if(i>=1){  
  130.                     //traverse the next subtrees in the state-space tree  
  131.                     check(i-1,sum,count,true);  
  132.                     check(i-1,sum,count,false);  
  133.                 }//else: the check is invalid                     
  134.             }  
  135.         }  
  136.         if(include)  
  137.             //backtracking  
  138.             tracer.pop();  
  139.     }  
  140.       
  141.     public static void main(String[] args) throws Exception {  
  142.         int A[] = {3,5,-10,20,25,50};         
  143.         //int A[] = {3,5,10,20,25,50};        
  144.         //int A[] = {100,99,98,1,2,3,1,2,3,4,5,40};  
  145.         BalancedSet bs = new BalancedSet(A);  
  146.         bs.solve(A);  
  147.     }  
  148. }  

 

0 0
原创粉丝点击