Optimal subsequence problem (reduction and rule - binary search - grouping)

 

. 1 #include <stdio.h>
 2 #include <stdlib.h>
 . 3  int isSright ( int * ARR, int N, int M, int S); // determines whether or S and may be packet number column 
. 4  int Dichotomy ( int ARR *, int N, int m); // for the lower limit of the S dichotomy 
. 5  int main ( void )
 . 6  {
 . 7      int * ARR, N, m, I; // n-digits, parts of m 
. 8  
. 9      Scanf ( " % D% D " , & N, & M);
10     arr=(int*)malloc(sizeof(int)*N);//动态分配内存
11     for(i=0;i<N;i++)
12         scanf("%d",arr+i);
13     printf("%d\n",dichotomy(arr,N,M));
14     free(arr);
15     arr=NULL;
16 
17     return 0;
18 }
19 int isSright(int *arr,int N, int M, int S)
 20 is  {
 21 is      int J = 0 ;
 22 is      int Currents = 0 ; // try segmentation process, and the current partition portion 
23 is      int SUM = . 1 ; // record the segmentation process attempts have been distributed parts 
24      for (J = 0 ; J <N; J ++ )
 25      {
 26 is          IF (* (ARR + J)> S) return  0 ; // if the individual elements than S directly back to 0s appear 
27          Currents + = ARR [J ];
 28          IF (Currents>S)
29         {
30             currentS=0;
31             sum++;
32             j--;
33         }
34     }
35     if(sum>M) return 0;
36     else return 1;
37 }
38 int dichotomy(int *arr,int N,int M)//二分法
39 {
40     int i=0;
41     int left=0,right=0,middle=0;
42     for(i=0;i<N;i++)
43         right+=*(arr+i);
44     while(left<=right)
45     {
46         middle=(left+right)/2;
47         if(isSright(arr,N,M,middle)==1)    right=middle-1;
48         else    left=middle+1;
49     }
50     return left;
51 }

Clear two points: First, the column number of columns is a positive integer, the maximum value of S should be whole numbers and, the upper limit of S is easily

        determine. As long as I determine the feasibility of the current S, will be able to determine the scope of the next S, and that brings me

        It can be used to complete dichotomy.

     Second, for each S feasibility check, the original sequence has been accumulated in the array, until no more than just

        S, open up a new starting point, and continue to add, and then open up the total number of copies is compared with M.

PS: I feel more comfortable with computational thinking, know nothing about from the beginning, willing to spend time behind the repeated studies, self

  Own progress is obvious. Although I still have a big gap and dalao, but I see hope.

   Come on, Ziyang!

  

Guess you like

Origin www.cnblogs.com/ziyang1060/p/12026405.html