Title Description:
There are two sequences, a, B, the size is n, the values of the sequence elements are arbitrary integers, unordered;
Requirement: To minimize the difference between the and of [sequence A and] and [sequence B elements] by exchanging the elements in A/b.
For example:
var a=[100,99,98,1,2, 3];
var b=[1, 2, 3, 4,5,40];
Analysis:
In many cases, the solution obtained by the greedy algorithm is not the optimal solution, but the problem seems to be the optimal solution.
Thought: Every time we find two elements in AB that make the least difference to each other.
Current and the difference Diff=suma-sumb, from a to find an element A, from B to find an element B, if the exchange then must have (suma-a+b)-(Sumb-b+a) =suma-sumb-2 (a) =diff-2 (a),
Which makes the minimum value of ABS (Diff-2 (a)) Exchange
#include"iostream"#include<fstream>#include<algorithm>#include<functional>using namespacestd;#defineN 6inta[n]={ -, About,98,1,2,3};intb[n]={1,2,3,4,5, +};voidSwap () {intSuma=0, sumb=0; for(intI=0; i<n;i++) {SumA+=A[i]; Sumb+=B[i]; } intdiff=suma-Sumb; while(diff!=0) { intMini=0, minj=0; intbest=0; for(intI=0; i<n;i++) for(intj=0; j<n;j++) { if(ABS (diff-2* (A[i]-b[j])) <abs (diff-2*Best )) { Best=a[i]-B[i]; Mini=i; Minj=J; } } if(best==0)//can no longer find a group to swap return; Swap (A[mini],b[minj]); SumA-=Best ; Sumb+=Best ; Diff=suma-Sumb; } } intMain () {Freopen ("C:\\in.txt","R", stdin); Swap (); for(intI=0; i<n;i++) cout<<a[i]<<" "; cout<<Endl; for(intI=0; i<n;i++) cout<<b[i]<<" "; cout<<Endl; return 0;}
http://shenxingfeng1988.blog.163.com/blog/static/106376005201371171345712/
Http://blog.sina.com.cn/s/blog_60c8379d01014du8.html
Minimizes the difference between the and of [sequence A and] and [sequence B elements] by exchanging the elements in A/b