您的位置:首页 > 其它

hdu 5532 Almost Sorted Array 最长上升子序列

2015-11-01 16:23 197 查看


Almost Sorted Array

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)

Total Submission(s): 0    Accepted Submission(s): 0


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

 

nlogn 的算法

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<climits>
#include<queue>
#include<vector>
#include<map>
#include<sstream>
#include<set>
#include<stack>
#include<cctype>
#include<utility>
#pragma comment(linker, "/STACK:102400000,102400000")
#define PI 3.1415926535897932384626
#define eps 1e-10
#define sqr(x) ((x)*(x))
#define FOR0(i,n)  for(int i=0 ;i<(n) ;i++)
#define FOR1(i,n)  for(int i=1 ;i<=(n) ;i++)
#define FORD(i,n)  for(int i=(n) ;i>=0 ;i--)
#define  lson   num<<1,le,mid
#define rson    num<<1|1,mid+1,ri
#define MID   int mid=(le+ri)>>1
#define zero(x)((x>0? x:-x)<1e-15)
#define mk    make_pair
#define _f     first
#define _s     second
using namespace std;
//const int INF=    ;
typedef long long ll;
//const ll inf =1000000000000000;//1e15;
//ifstream fin("input.txt");
//ofstream fout("output.txt");
//fin.close();
//fout.close();
//freopen("a.in","r",stdin);
//freopen("a.out","w",stdout);
const int INF =0x3f3f3f3f;
const int maxn=1e5+10    ;
//const int maxm=    ;
int a[maxn];
int q[maxn];

int n;

int work(int le,int ri,int x)
{
while(le<=ri)
{
int mid=(le+ri)>>1;
if(q[mid]<=x)  le=mid+1;
else   ri=mid-1;
}
return le;
}

bool up()
{
int r=1,f=1;
for(int i=1;i<=n;i++)
{
if(r==f) q[r++]=a[i];
else
{
if(q[r-1]<=a[i])  {q[r++]=a[i];continue;}
int p=work(1,r-1,a[i] );//第一个比他大
q[p]=a[i];
}
}
if(r-1 >=n-1)  return true;
return false;

}
bool check()
{
if( up())  return true;

for(int i=1,j=n;i<j;i++,j--)
swap(a[i],a[j]);

if(up())  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]);
puts(check()?"YES":"NO");
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: