(LIS) rises up sequence (DP + binary optimization)

Seeking a number of columns increase the longest sequence

  Dynamic programming : O (n ^ 2)

       

. 1  // the DP
 2  int the LIS (A int [], int n-)
 . 3 {
 . 4      int the DP [n-];
 . 5      int Cnt = -1;
 . 6      Memset (the DP, 0, the sizeof (the DP));
 . 7      for (int I = 0; I <n-; I ++)
 . 8      {
 . 9          for (int J = 0; J <I; J ++)
 10          {
 . 11              IF (A [I]> A [J])
 12 is              {
 13 is                  the DP [I] = max ( the DP [I], the DP [J] + 1'd);
 14                  Cnt = max (the DP [I], Cnt); // record the number of elements contained in the longest sequence
 15              }
 16          }
 17      }
 18     return Cnt + 1; // initializes to 0 because, it returns the result +1
 19  }

 

 

 

 

Greedy + dichotomy : O (nlogn) 

Analysis : let rise in a sequence with the longest sequence, in fact, is to ensure that each element in the sequence as small as possible, lower the threshold, so that element back as much as possible to enter the sub-sequence

Implement : a longest sequence defined array Array, as well as the current length Len, from start to finish a maintenance array

. A a [i]> Array [i] (the end of the current element is greater than the sequence elements), the a [i] into the sequence: Array [++ len] = a [i]

b. a [i] <= Array [i], Array case of maintenance, the replacement ratio of Array in a [i] into the first large element a [i] (into the back of the element can be reduced so that the sub-sequence threshold.

c. To reduce the complexity of the algorithm is as Array ascending sequence, so use lower_bound lookup Array not less than the first a [i] element

 

 1 //贪心+二分
 2 int LIS(int a[])
 3 {
 4     int Cnt=0;
 5     int Array[n+1];
 6     Array[0] = a[0];
 7     for(int i=1; i<n; i++ )
 8     {
 9         if( a[i]>Array[Cnt] )
10             Array[++Cnt]=a[i];
11             else
12             {
13                 int Index=lower_bound(Array, Array+Cnt+1, a[i])-Array;
14                 Array[Index]=a[i];
15             }
16     }
17     return Cnt+1;
18 }

 

 

Decline in demand longest sequence:

    --- not need to write directly to the requirements of the LDS array reverse, reverse array rise longest sequence length = original array longest sequence length decreased.

 

Guess you like

Origin www.cnblogs.com/wsy107316/p/11502538.html