ZOJ Sequence in the Pocket

文章目录

题目:

在这里插入图片描述

思路:

以数列4 3 5 2 1 为例来分析。
本题是让我们通过有限次最前端插入,将数组升序化。那么对于数列中可间断,已判断升序的最大子序列长度。比如上述例子的[4 5]就是该条件下的最大子序列长度,数组中的其他数字可依次选取其中的最大数插入前端,加入判断已升序的序列。

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

代码

#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());
    }
}

注释:代码中的ShellSort()是一种O(n Log n)升序排序。程序时间复杂度为O(n Log n)。

猜你喜欢

转载自blog.csdn.net/m0_46198140/article/details/107822540
今日推荐