ZOJ Sequence in the Pocket

Article Directory

topic:

Insert picture description here

Ideas:

Take the number sequence 4 3 5 2 1 as an example to analyze.
This question is to let us insert the array in ascending order through a limited number of front-end insertions. Then for the discontinuity in the sequence, the maximum subsequence length in ascending order has been determined. For example, [4 5] in the above example is the maximum subsequence length under this condition. The other numbers in the array can be selected in turn and inserted into the front end, adding the sequence that has been judged ascending.

3 4 5 2 1
2 3 4 5 1
1 2 3 4 5

Code

#include<stdio.h>
#define MaxSize 100000
int st[MaxSize];
int ch[MaxSize];
int n;

void gets_in()
{
    
    
    scanf("%d", &n);
    for(int i=0; i<n; i++){
    
    
        scanf("%d", st+i);
        ch[i] = st[i];
    }
}

void ShellSort()
{
    
    
    int i, j, d;
    int tmp;
    d = n/2;
    while(d>0) {
    
    
        for(i=d; i<n; i++) {
    
    
            tmp = ch[i];
            j = i-d;
            while(j>=0 && tmp<ch[j]) {
    
    
                ch[j+d] = ch[j];
                j -= d;
            }
            ch[j+d] = tmp;
        }
        d /= 2;
    }
}

//找出数组中可间断,已判断升序的最大子序列长度
int SearchLength()
{
    
    
    int len=0;
    int i=n-1, j=n-1;
    int tmp=ch[j];
    while(i>=0) {
    
    
        if(tmp==st[i]) {
    
    
            j--; len++;
            if(j<0) break;
            tmp = ch[j];
        }
        i--;
    }
    return len;
}

int main(void)
{
    
    
    int tests;
    scanf("%d", &tests);
    while(tests--) {
    
    
        gets_in();
        ShellSort();
        printf("%d\n", n-SearchLength());
    }
}

Note: ShellSort() in the code is a sort of O(n Log n) in ascending order. The time complexity of the program is O(n Log n).

Guess you like

Origin blog.csdn.net/m0_46198140/article/details/107822540
ZOJ
ZOJ