HDU 5532 Almost Sorted Array (2015ACM/ICPC长春&&LIS)

【题目链接】:click here~~

【题目描述】:

Almost Sorted Array

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 272    Accepted Submission(s): 132


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 .

1T2000
2n105
1ai105
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-1就可以了,单调递减的就翻转数列在操作一遍即可,复杂度(O(nlogN))

代码:

/*
* Problem:HDU 5532
* Running time: 1100MS
* Complier: G++
* Author: javaherongwei
* Create Time: 21:20 2015/11/02 星期一
*/
#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;
inline int max(int a,int b){
    return a>b?a:b;
}
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 maxx=0;
    for(int i=1; i<=n; ++i){
        int idx=binary_search(a[i]);//i位置的LIS为idx
        maxx=max(idx,maxx);
        b[idx]=a[i];
    }
    if(maxx>=n-1) return true; //满足条件即可
    return false;
}
int main(){
    //freopen("1.txt","r",stdin);
    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;
}

你可能感兴趣的:(HDU,二分,LIS)