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
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
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 5Sample Output
YES YES NO
思路:
这个LIS要用upper_lound来写,因为是非递增和递减,故用这个找到第一个大于它的数,发现了upper_lound()第二个参数必须有数才能用,估计它也是二分实现的把,以后要注意
code:
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
typedef long long LL;
int t,n,arr[100100],arr2[100100],dp[100100],len;
void input()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&arr2[i]);
}
int solve()
{
fill(dp,dp+n+10,1000000);
for(int i=1;i<=n;i++)
{
(*upper_bound(dp,dp+n,arr2[i]))=arr2[i];
}
return upper_bound(dp,dp+n+10,99999)-dp;
}
int solve2()
{
fill(dp,dp+n+10,1000000);
for(int i=n;i>=1;i--)
{
*upper_bound(dp,dp+n,arr2[i])=arr2[i];
}
return upper_bound(dp,dp+n+10,99999)-dp;
}
int main()
{
int t;
cin>>t;
while(t--)
{
input();
int ans1=solve();
int ans2=solve2();
if(ans1>=n-1||ans2>=n-1)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}