简单dp hdu 5532 Almost Sorted Array nlogn 的最长非严格单调子序列

来源:互联网 发布:ubuntu dokuwiki 编辑:程序博客网 时间:2024/05/19 11:47

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,,ana1,a2,…,an, is it almost sorted?
Input
The first line contains an integer TT indicating the total number of test cases. Each test case starts with an integer nn in one line, then one line with nn integers a1,a2,,ana1,a2,…,an

1T20001≤T≤2000 
2n1052≤n≤105 
1ai1051≤ai≤105 
There are at most 20 test cases with n>1000n>1000.
Output
For each test case, please output "`YES`" if it is almost sorted. Otherwise, output "`NO`" (both without quotes).
Sample Input
332 1 733 2 153 1 4 1 5
Sample Output
YESYESNO

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
const int inf=1e9+7;
const int maxn=1e5+10;
using namespace std;
int a[maxn],b[maxn],c[maxn];
int n;
int binary_search(int x){ //二分搜索
    int l=1,r=n;
    while(l<r){
        int mid=(l+r)>>1;
        if(b[mid]>x) r=mid;
        else l=mid+1;
    }
    return l;
}
bool LIS(const int *a){ //LIS
    memset(b,inf,sizeof(b));
    b[0]=0;
    int len=0;
    for(int i=1; i<=n; ++i){
        int k=binary_search(a[i]);//i位置的LIS为idx
        len=max(k,len);
        b[k]=a[i];
    }
    if(len>=n-1) return true; //满足条件即可
    return false;
}
int main(){
    int t;scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1; i<=n; ++i){
            scanf("%d",&a[i]);
            c[n-i+1]=a[i];
        }
        if(LIS(a)||LIS(c)) puts("YES");
        else puts("NO");
    }
    return 0;
}

阅读全文
0 0
原创粉丝点击