交换使两个序列差最小| Two Equal-sized Subsets Partition Problem | Thousand Sunny


交换使两个序列差最小| Two Equal-sized Subsets Partition Problem | Thousand Sunny
 有两个序列a,b,大小都为n,序列元素的值任意整数,无序;
要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小
http://yyeclipse.blogspot.com/2013/02/two-equal-sized-subsets-partition.html
还有一种思路就是:转化为:2n个数组,把它划分为两个数组并且使之和之差最小,编程之美有详细解答
当数组之和非常大的时候,DP算法的数组就会非常大,就不那么高效了。
对于一些极端例子,比如A=[ 12345,12332,14098], B=[ 32213,12321,23132]. DP还不如暴力破解。C(6,3) = 120。 总共才120种可能。
 /**
  * @param array:
  *        assuming that the input array is the combination of two n-sized array.
  * @return int :
  *        minimal difference of the two n-sized subsets.
  */
 public static int minimalSum (int[] array){
  int total = sum(array);
  int sum = total/2;
  int n=array.length/2;
   
  //dp[i][v] = true means that there's i elements added up to value v.
  boolean[][] dp = new boolean[n+1][sum+1];
  dp[0][0]=true;
   
  for(int k=1;k<=2*n;k++){
   int val = array[k-1];
   for(int i=1;i<=k&&i<=n;i++){
    for(int v=1;v<=sum;v++){
     //try to take k as i th element
     if(v>=val && dp[i-1][v-val])
      dp[i][v]=true;
    }
   }
  }
  //find the answer. we need n-sized subset, so just check dp[n][*].
  for(int i=sum;i>0;i--){
   if(dp[n][i])
    /**
     * we find a subset with size=n and sum=i,another subset will have sum=total-i
     * so the difference will be (total-i)-i=total-2*i
     */
    return total-2*i;
  }
  return -1;
 }
用回溯法(backtracking)解决平衡集合问题
http://blog.csdn.net/ljsspace/article/details/6434621#

X. Don't think this method will work.
http://www.cnblogs.com/tractorman/p/4063866.html
核心代码分析:为什么会使用if((A[i]!=B[j]) && (abs(diff-2*(A[i]-B[j]))<=abs(diff)))...1,而不是if(abs(diff-2*(A[i]-B[j]))<abs(diff))...2 ,因为如果使用代码2,就会有特例出现:
    A = { 5,5,9,10 }; B ={ 4,7,7,13 }; A的和为29,B为31。当把A中的5,5与B中的4,7交换后,A与B的和都为30,差为0.但使用代码2将检测不到这种交换!因此输出结果是原数组。
  而使用代码1就可以输出差为0的两个数组。因为A和B和之差的绝对值为2,如果A的5与B的7交换后差的绝对值也是2,可以交换。则5和7交换之后,再把A的5和B的4交换,差的绝对值就为0了。
  为什么有(A[i]!=B[j]),因为如果A和B中有相同元素的时候,就会进入死循环。
  所以综合起来,就应该使用if((A[i]!=B[j]) && (abs(diff-2*(A[i]-B[j]))<=abs(diff)))
void Swap()
{
    int sumA=0,sumB=0;
    int times = 0;
    int flag = 1;
    for (int i=0;i<N;i++)
    {
        sumA+=A[i];
        sumB+=B[i];
    }

    int diff=sumA-sumB;
    if(diff==0)
        return;
    while (flag)
    {
        flag = 0;
        for(int i=0;i<N;i++)
            for (int j=0;j<N;j++)
            {    
                if((A[i]!=B[j]) && (abs(diff-2*(A[i]-B[j]))<=abs(diff)))
                {
                    diff = diff-2*(A[i]-B[j]);
                    swap(A[i],B[j]);
                    flag = 1;
                }
                times++;
            }
    } 
    cout << "times = " << times << endl;
}
http://www.cnblogs.com/tianshuai11/archive/2012/04/20/2477169.html
http://blog.csdn.net/cwqbuptcwqbupt/article/details/7521733
这种方法却有缺陷,因为一次只允许交换一对元素,这对于一次需要交换两个元素的数组而言将出错,考虑如下情况:
A = { 5,5,9,10 };
B = { 4,7,7,13 };
A的和为29,B为31。当把A中的5,5与B中的4,7交换后,A与B的和都为30,差为0.但上述算法一将检测不到这种交换!因此输出结果是原数组。
当前数组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'| = |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为止。
http://bylijinnan.iteye.com/blog/1356447
  1.      * 求解思路:  
  2.      * 当前数组a和数组b的和之差为 A = sum(a) - sum(b) a的第i个元素和b的第j个元素交换后, 
  3.      * a和b的和之差为 A'  
  4.      * =sum(a) - a[i] + b[j] - (sum(b) - b[j] + a[i])  
  5.      * = sum(a) - sum(b) - 2 (a[i] -b[j])  
  6.      * = A - 2 (a[i] - b[j])  
  7.      * 设x = a[i] - b[j], 则交换后差值变为 A’ = A - 2x 
  8.      *  
  9.      * 假设A > 0, 当x 在 (0,A)之间时,做这样的交换才能使得交换后的a和b的和之差变小,x越接近A/2效果越好, 
  10.      * 如果找不到在(0,A)之间的x,则当前的a和b就是答案。 所以算法大概如下: 
  11.      * 在a和b中寻找使得x在(0,A)之间并且最接近A/2的i和j,交换相应的i和j元素,重新计算A后, 
  12.      * 重复前面的步骤直至找不到(0,A)之间的x为止。 
  13.      */  
  14.     public static void main(String[] args) {  
  15.         MinSumASumB minSumASumB=new MinSumASumB();  
  16.         int[] a={3,5,-10};  
  17.         int[] b={20,25,50};  
  18.         minSumASumB.swapToMinusDiff(a, b);  
  19.         System.out.println(Arrays.toString(a));  
  20.         System.out.println(Arrays.toString(b));  
  21.     }  
  22.   
  23.     public void swapToMinusDiff(int[] a,int[] b){  
  24.           
  25.         int sumA=sum(a);  
  26.         int sumB=sum(b);  
  27.           
  28.         if(sumA==sumB)return;  
  29.           
  30.         if(sumA<sumB){  
  31.             int[] temp=a;  
  32.             a=b;  
  33.             b=temp;  
  34.         }  
  35.         int curDiff=1;  
  36.         int oldDiff=Integer.MAX_VALUE;  
  37.         int pA=-1;  
  38.         int pB=-1;  
  39.         boolean shift=true;  
  40.         int len=a.length;//the length of a and b should be the same  
  41.         while(shift&&curDiff>0){  
  42.             shift=false;  
  43.             curDiff=sum(a)-sum(b);  
  44.             for(int i=0;i<len;i++){  
  45.                 for(int j=0;j<len;j++){  
  46.                     int temp=a[i]-b[j];  
  47.                     int newDiff=Math.abs(curDiff-2*temp);  
  48.                     if(newDiff<curDiff&&newDiff<oldDiff){  
  49.                         shift=true;  
  50.                         oldDiff=newDiff;  
  51.                         pA=i;  
  52.                         pB=j;  
  53.                     }  
  54.                 }  
  55.             }  
  56.             if(shift){  
  57.                 int temp=a[pA];  
  58.                 a[pA]=b[pB];  
  59.                 b[pB]=temp;  
  60.             }  
  61.         }  
  62.         System.out.println("the min diff is "+oldDiff);  
  63.     }  
http://blog.csdn.net/liulanghk/article/details/46628201
通过交换的方式,最终的状态是在保证两个序列中元素个数相同的条件下,任何一个元素都可以位于两个序列中的任何一个。这样问题可以转化为:在一个长度为2*n的整数序列中,如何将元素个数分成两个子集,记每个子集的元素之和分别为S1和S2,使得|S1-S2|最小。

//分别表示 a[]的和 b[]的和 以及2者之差 int sum1,sum2,a; int temp; //和之差是否大于0 bool dayu0; //等待交换的a[i]和b[j]的下标 i j int pos1,pos2; //最接近a/2的a[i]-b[j]值 float minn; //是否能有解 bool have1 ; while (1) { sum1 = 0; sum2 = 0; //求两个数组的和 for (int i = 0 ; i < n;++i) { sum1 += ar1[i]; sum2 += ar2[i]; } a = sum1 - sum2; //和之差 dayu0 = a>0?true:false; //和之差是大于0还是小于0 have1 = false; //是否能找到解 for (int i = 0 ; i < n;++i) //找最接近a/2的 a[i]-b[j] { for (int j = 0;j < n;++j) { temp = ar1[i] - ar2[j]; //如果a[i]-b[j] 在(0,a)之间 (超出的就没有意义了) if ((dayu0 && temp > 0 && temp < a)||(!dayu0 && temp < 0 && temp > a)) { //若比之前的a[i]-b[j]更接近a/2 则更新 if (have1 && abs(temp - a/2.0) < minn) { minn = abs(temp - a/2.0); pos1 = i; pos2 = j; } else { have1 = true; minn = abs(temp - a/2.0); pos1 = i; pos2 = j; } } } } if (!have1) //若找不到符合条件的a[i]-b[j]了 则结束 { break; } swap(ar1[pos1],ar2[pos2]); //交换a b中的元素 }
这个题目的原型是之前做过的ACM动态规划
多米诺骨牌(DOMINO)
问题描述:有一种多米诺骨牌是平面的,其正面被分成上下两部分,每一部分的表面或者为空,或者被标上1至6个点。现有一行排列在桌面上:
顶行骨牌的点数之和为6+1+1+1=9;底行骨牌点数之和为1+5+3+2=11。顶行和底行的差值是2。这个差值是两行点数之和的差的绝对值。每个多米诺骨牌都可以上下倒置转换,即上部变为下部,下部变为上部。
现在的任务是,以最少的翻转次数,使得顶行和底行之间的差值最小。对于上面这个例子,我们只需翻转最后一个骨牌,就可以使得顶行和底行的差值为0,所以例子的答案为1。

Read full article from 交换使两个序列差最小| Two Equal-sized Subsets Partition Problem | Thousand Sunny

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts