The beauty of programming 2.18-array segmentation

Source: Internet
Author: User

Topic:

There is an array of positive integers with no sorting and a number of elements of 2N. It is required to divide it into two arrays with the number of elements N and the closest of two sub-arrays.


Basic idea:

Suppose that the sum of all elements of the array a[1..2n] is sums. Simulate the strategy of dynamic programming to solve the 0-1 knapsack problem, so that s (k, i) represent the set of any I elements in the first k elements.

Obviously:

S (k, 1) = {A[i] | 1<= i <= k}
S (k, k) = {A[1]+a[2]+...+a[k]}
S (k, i) = S (k-1, i) U {a[k] + x | x belongs to S (k-1, I-1)}
According to this recursive formula, finally find out the sum/2 closest to sums in the set S (2N, N) and that is the answer. The time complexity of this algorithm is O (2^n).

Because this process only concerns and is not much more than the sum/2 of that sub-array. So it is meaningless to repeat and to be larger than SUM/2 in the set. These meaningless and eliminated, the remaining meaningful and the number of the most is SUM/2. Therefore, we do not need to record what is in S (2n,n) and, only need to traverse from SUM/2 to 1 once, ask whether this value is not in S (2n,n), the first occurrence of the value is the answer. Our program does not need to calculate each set according to the above recursive formula, only need to set a flag array for each collection, Mark Sum/2 to 1 which values in this interval can be computed.

    #include <iostream> using namespace std; There is an array of positive integers with no sorting and a number of elements of 2N.      It is required to divide it into two arrays with the number of elements N and the closest of two sub-arrays.      int arr[] = {0,1,5,7,8,9,6,3,11,20,17};      const int n=5;            const int SUM = 87;          The strategy of simulating the 0-1 knapsack problem with dynamic programming int solve1 () {int I, j, S;                int dp[2*n+1][n+1][sum/2+2];           /* Use DP (I,J,C) to represent the best (large) scheme in which J is taken from the previous I element and the sum of the J elements does not exceed C, where the i>=j,c<=s equation of state transfer is: limited to the first item         DP (I,J,C) =MAX{DP (I-1,j-1,c-a[i]) +A[I],DP (I-1,J,C)} DP (2N,N,SUM/2+1) is the solution to the problem.                *///Initialize Memset (Dp,0,sizeof (DP));                  for (i = 1, i <= 2*n; ++i) {for (j = 1; J <= min (i,n); ++j) { for (s = sum/2+1; s >= arr[i];--s) {Dp[i][j][s] = max (dp[i-1][j-1][s-arr[i]]+                  Arr[i], dp[i-1][j][s]);       }}}//Because this is the final answer dp[2*n][n][sum/2+1];   I=2*n, J=n, s=sum/2+1;              while (i > 0) {if (dp[i][j][s] = = Dp[i-1][j-1][s-arr[i]]+arr[i])//Determine which state this state is derived from    {cout<<arr[i]<< "";                  Take medium arr[i] j--;              S-= arr[i];          } i--;          } cout<<endl;      return dp[2*n][n][sum/2+1];          } int solve2 () {int I, j, S;     int dp[n+1][sum/2+2];    Take n+1 items, sum not more than sum/2+2, the maximum is how much memset (dp,0,sizeof (DP));              The initial state is 0 for (i = 1; I <= 2*n; ++i) {for (j = 1; J <= min (i,n); ++j)                      {for (s = sum/2+1; s >= arr[i];--s)//01 backpack from large to small, can save space, that is, the outermost space {                   Dp[j][s] = max (Dp[j-1][s-arr[i]]+arr[i], dp[j][s]);      }}}//requires that the optimal solution space cannot be optimized, return dp[n][sum/2+1];   } int Solve3 ()   {int I, j, S; int isok[n+1][sum/2+2];    ISOK[I][V] Indicates whether the number of I can be found so that they are equal to V memset (isok,0,sizeof (IsOK)); are not legal//note initialization isok[0][0] = 1;  Yes, take 0 items, total 0, is valid for (i = 1; I <= 2*n; ++i) {for (j = 1; J <= min (i,n);                      ++J) {for (s = sum/2+1; s >= arr[i];--s)//from large to small, the array is one dimension less {                  if (Isok[j-1][s-arr[i]]) isok[j][s] = 1;                  }}} for (s = sum/2+1; s >= 0;--s) {if (Isok[n][s])          return s;      }//requires that the optimal solution space cannot be optimized for return 0;          } int main (void) {int S1 = solve1 ();          int s2 = solve2 ();          int s3 = Solve3 ();          cout<< "s1=" <<s1<<endl;          cout<< "s2=" <<s2<<endl;     cout<< "s3=" <<s3<<endl;     System ("pause");      return 0;   }

The time complexity of solve1 and Solve2 is O (2^n),

The time complexity of Solve3 is O (n^2*sum).


Extension problem: Swapping two array elements minimizes the difference between two arrays
There are two arrays A, B, the size is n, the value of the array element arbitrarily shaped number, unordered;
Requirement: By exchanging elements in a, b array, the difference between [array A and] and [array b elements and] is minimized.
In fact, this problem is the deformation of the above problem, the A, b two arrays into an array, and then the problem is converted to the 2*n element array into 2 length of an array of n, and the two sub-arrays and the closest.
In addition, It is important to note that if there are negative numbers in the array, the knapsack strategy above cannot be used (since s in the third loop is the subscript of the array and cannot have negative numbers), all the arrays in the array must be given the absolute value of the smallest negative number. The elements in the array are all added to a certain range, all converted to positive numbers, and then use the above knapsack strategy can be solved.

The beauty of programming 2.18-array segmentation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.