Problem description:There are two integer sequences A and B, all of which are n. The values of the sequence elements are random integers and unordered. Requirement: by exchanging elements in a and B, sum (a)-sum (B) is minimized. For example: var A = [80, 40, 60, 10, 20, 30]; var B = [10, 20, 50, 40, 30, 20];
Analysis:
Approximate optimal algorithm:
The sum of A and B in the current array is: a = sum (a)-sum (B). After the I element of A is exchanged with the J element of B, the difference between A and B is:
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], A' = A-2x, As long as 0 <x <= A/2, then a' <.
Therefore, the goal is to find I and j, so that X is between 0 and A/2, and the closer it is to A/2, the better. Until such an X is not found.
Code implementation:
1 // 32.cc 2 # include <iostream> 3 using namespace STD; 4 5 // calculate the sum of the array and 6 int sum (const int * a, int N) {7 int COUNT = 0; 8 for (INT I = 0; I <n; I ++) 9 count + = A [I]; 10 return count; 11} 12 13 // exchange array elements to obtain the balanced set 14 void balance_swap (int * a, int * B, int N) {15 // A points to a large set of 16 if (sum (A, n) <sum (B, n) {17 int * t =; 18 A = B; 19 B = T; 20} 21 22 bool loop = true; 23 while (loop) {24 loop = false; 25 for (INT I = 0; I <n; I ++) {26 for (Int J = 0; j <n; j ++) {27 int diff = A [I]-B [J]; 28 int A = sum (A, n)-sum (B, n); 29 If (diff> 0 & diff <a/2) {30 loop = true; 31 int TMP = A [I]; 32 A [I] = B [J]; 33 B [J] = TMP; 34} 35} 36} 37} 38} 39 40 // print array element 41 void print (const int * a, int N) {42 for (INT I = 0; I <n; I ++) 43 cout <A [I] <""; 44 cout <Endl; 45} 46 47 int main () {48 int A [] = {80, 40, 60, 10, 20, 30}; 49 int B [] = {10, 20, 50, 40, 30, 20}; 50 int n = sizeof (a)/sizeof (INT); 51 52 balance_swap (A, B, n); 53 54 print (A, N ); 55 print (B, n); 56 57 Return 0; 58}
Output:
$ ./a.exe50 40 60 10 20 3010 20 80 40 30 20
IT company 100 question-32-finding the sum of the largest subsequences of Arrays