HDU 5532 Almost Sorted Array (最长非递减子序列)

题目链接

Problem Description
We are all familiar with sorting algorithms: quick sort, merge sort, heap sort, insertion sort, selection sort, bubble sort, etc. But sometimes it is an overkill to use these algorithms for an almost sorted array.

We say an array is sorted if its elements are in non-decreasing order or non-increasing order. We say an array is almost sorted if we can remove exactly one element from it, and the remaining array is sorted. Now you are given an array a1,a2,…,an, is it almost sorted?

Input
The first line contains an integer T indicating the total number of test cases. Each test case starts with an integer n in one line, then one line with n integers a1,a2,…,an.

1≤T≤2000
2≤n≤105
1≤ai≤105
There are at most 20 test cases with n>1000.

Output
For each test case, please output "YES" if it is almost sorted. Otherwise, output "NO" (both without quotes).

Sample Input
3
3
2 1 7
3
3 2 1
5
3 1 4 1 5

Sample Output
YES
YES
NO

分析:
给出n个数,问如果去掉其中一个数,能否构成不上升或者不下降的序列。

比赛的时候直接暴力写的,代码写了不到一百行,最组要需要考虑的情况有点复杂,这里使用非递减子序列的思想。

可以将数组正序进行一次最长非递减子序列,再将数组逆序进行一次最长非递减子序列,最终只要其中又有个满足子序列的长度等于n(本身就是满足情况的),或则等于n-1(去掉其中的一个之后满足情况)即可。

数组逆序求非递减,也就相当于对于原数组求非递增。

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100005],ans[100005];
//a数组是原始的输进去的序列,ans数组是保存的a数组中的非递减子序列,ans数组中的元素一定是有序的
int main()
{
    int T,n,len;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(int i=1; i<=n; i++)
            scanf("%d",&a[i]);
        ans[1]=a[1];//首先只有一个元素的话肯定就是有序的了。
        len=1;
        for(int i=2; i<=n; i++)
        {
            if(a[i]>=ans[len])//如果大于等于当前的ans数组中的最后一个元素(最大的),那么这个数可以直接加到ans数组中
                ans[++len]=a[i];
            else
            {
                /*
                当前的这个数没有办法直接加入到ans数组的最后面,但是我们可以将ans数组中的比他大并且距离他最近的那个数给替换掉
                这样子序列的长度肯定会减少1,并且保证子序列里面的元素尽可能的小
                */
                int pos=upper_bound(ans+1,ans+len+1,a[i])-ans;
                ans[pos]=a[i];
            }
        }
        if(len==n-1||len==n)//子序列的长度为n或则n-1的话,计算满足条件的
        {
            printf("YES
");
            continue;
        }
        ///再反过来进行一遍,寻找反过来的非递减,也就相当于原序列的非递增
        ans[1]=a[n];
        len=1;
        for(int i=n-1; i>=1; i--)
        {
            if(a[i]>=ans[len])
                ans[++len]=a[i];

            else
            {
                int pos=upper_bound(ans+1,ans+len+1,a[i])-ans;
                ans[pos]=a[i];
            }
        }
        if(len==n-1||len==n)
            printf("YES
");
        else printf("NO
");

    }
    return 0;
}
原文地址:https://www.cnblogs.com/cmmdc/p/7822131.html