There are two arrays, B, size is n, the value of the array element arbitrarily shaped number, unordered;
Requirement: To minimize the difference between the and of elements of array A and the array B elements by swapping the elements in a A.
Order A=sum (a)-sum (b)
The difference between A and b after the first element of a and the J element of B is exchanged.
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])
Set x = A[i]-B[J]
Only when | a-2x|<| A|, A[i] and b[j] only make sense, at this time the condition is:
0<x<a,a>0 or a<x<0,a<0, if you find an X that does not meet the criteria, end the swap.
And when X gets closer to A/2, the better (A ' approaches 0).
So the algorithm is probably as follows:
Look for two numbers in A and b a[i],b[j] make 0<x<a,a>0 or a<x<0,a<0, and closest to A/2 I and J, exchange the corresponding I and J elements, after recalculating A, repeat the previous steps until you cannot find a match 0< X<a,a>0 or a<x<0,a<0 a[i],b[j] so far.
The code is as follows:
#include <iostream>using namespacestd;voidMinsumdiff (intA[],intB[],intN) { BOOLUnfinish=true; while(unfinish) {unfinish=false; intsumdiffab=0;//storage sum (a)-sum (b) =a for(intI=0; i<n;i++) Sumdiffab+=a[i]-C[i]; floathalfsum=sumdiffab/2.0;//namely A/2 intPosa=0, posb=0; floatmindis=ABS (SUMDIFFAB); for(intI=0; i<n;i++) { for(intj=0; j<n;j++) { intx=a[i]-B[j]; if((sumdiffab>0&&x>0&&x<sumdiffab) | | (sumdiffab<0&&x<0&&x>sumdiffab))//if (x*sumdiffab>0&&abs (x) <abs (sumdiffab))//Only Meet | a-2x|<| a|, Exchange only makes sense: that is a>0 when,0<x<a; when A<0, a<x<0{unfinish=true; floatT=abs (x-halfsum);//calculate the distance between x and A/2 if(T<mindis)//stores the distance value of the nearest X from A/2 and the corresponding swap. {Mindis=T; Posa=i; POSB=J; } } } } if(unfinish) {inttmp; TMP=A[posa]; A[posa]=B[POSB]; B[POSB]=tmp; } }}intMain () {inta[]={4,3,9}; intb[]={2,1,6}; Minsumdiff (A, B,3); for(intI=0;i<3; i++) {cout<<a[i]<<","<<b[i]<<Endl; } System ("Pause"); return 0;}
There are two arrays, a, B, the size is n, the values of the array elements are arbitrarily shaped, unordered, by exchanging the elements in a A, a, so that |sum (a)-sum (b) | minimum