(Dynamic programming) longest increasing sub-column

First look at the problem,

The longest increasing sub-column.

That is, take out n numbers in order in the array, (in the original order) the sub-number sequence is an increasing sequence.

For example: the final result of the 1 2 3 -1 sequence is 3. The most corresponding sequence is obviously 1 2 3

(Note, only the length is output.)

Of course, if you still need to modify the algorithm slightly according to the coordinates,

Here is mainly to understand the ideas

   Without further ado, let's start to explain the general idea (dynamic programming)

   For the first n numbers of the array, that is the first, the second nth, respectively, find the longest continuously increasing subsequence ending in the first, second, and nth. Then, when we enter the nth For +1 numbers, we only need to compare forward, find the number smaller than the n + 1th bit, and record it as the Xth bit. Since we have obtained the length of the longest continuously increasing subsequence ending with the Xth bit (record Do Y) So our longest continuously increasing subsequence ending in n + 1 bits is Y + 1

We sequentially compare forwards, the record is smaller than n + 1 and the maximum value of the corresponding length can be increased by one

So we know the end of the traversal from the first bit, and we can get the length of the longest continuously increasing subsequence ending with each bit. So we can get the result

Of course, you can also get the corresponding sequence. The steps to get the sequence are not specific here.

Below we look at the specific code

 

 

#include <stdio.h>

int Max(int a[][2],int n,int cont)//寻找
{
    int i;
    int max=0;
    for (i=n-1; i>=0; i--) {
        if (a[i][0]<cont) {
            if (a[i][1]>max) {
                max=a[i][1];
            }
        }
    }
    
    return max;
    
}
int main(int argc, const char * argv[]) {
    // insert code here...
    int n;
    scanf("%d",&n);
    int n1[n][2];
    int i;
    int max=1;
    for (i=0; i<n; i++) {
        scanf("%d",&n1[i][0]);
        n1[i][1]=Max(n1,i,n1[i][0])+1;//Enter and find the assignment 
        if (n1 [i] [ 1 ]> max) { 
            max = n1 [i] [ 1 ]; 
        } 
        
    } 
    int n2 [max]; // Store sub-column 
        printf ( " % d \ n " , max ); // Output length 
    int m = max; // Record max 
    for (i = n- 1 ; i> = 0 ; i-- ) {
         if (n1 [i] [ 1 ] == max) { 
            n2 [max - . 1 ] = N1 [I] [ 0 ]; 
               max -;
        }
    }
    for(i=0;i<m;i++)//输出
    {
        printf("%d ",n2[i]);
    }
    printf("\n");
    return 0;
}

 

 

 

 

This is the test output graph

 

Here is also written the code to output the specific sequence, you can study it yourself

  If there is something wrong or something you do n’t understand well, leave a comment in the comment area   

Thanks! !

Guess you like

Origin www.cnblogs.com/cndccm/p/12207796.html