HDU5532 Almost Sorted Array(LIS)

版权声明:欢迎转载~转载请注明出处! https://blog.csdn.net/riba2534/article/details/82988052

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

思路

题意:

我们对排序算法很熟悉了:快速排序、归并排序、堆排序、插入排序、选择排序、冒泡排序等等,但有时用这些算法对一个几乎有序的数组进行排序就没必要了。
我们说一个数组有序,如果它的元素“按非递减顺序排列”或者“按非递增顺序排列”。我们说一个数组几乎有序,如果从它之中移除一个元素,剩下的数组是有序的。现在给你一个数组 a1, a2,…,an,它是否几乎有序?

思路:

只需要求出最长非递减和非递增子序列的长度,然后判断是否大于等于n-1即可。求非递增的时候就是把序列翻转求非递减.

代码

#include <bits/stdc++.h>
using namespace std;
#define mem(a, b) memset(a, b, sizeof(a))
#define y1 hpc1
#define y2 hpc2
const int N = 1e5 + 10;
int y1[N], y2[N], b[N], n;
int get_len(int a[])
{
    mem(b, 0);
    int len = 0;
    for (int i = 0; i < n; i++)
    {
        int p = upper_bound(b, b + len, a[i]) - b;
        b[p] = a[i];
        if (p == len)
            len++;
    }
    return len;
}
int main()
{
    //freopen("in.txt", "r", stdin);
    int t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d", &n);
        for (int i = 0; i < n; i++)
            scanf("%d", &y1[i]);
        for (int i = 0, j = n - 1; i < n; i++, j--)
            y2[i] = y1[j];
        if (get_len(y1) >= n - 1 || get_len(y2) >= n - 1)
            puts("YES");
        else
            puts("NO");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/riba2534/article/details/82988052