Almost Sorted Array
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 3734 Accepted Submission(s): 949
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?
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 .
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
解题思路:找出最长递增子序列就行,如果大于等于你n-1就输出yes反之输出no。
Source
2015ACM/ICPC亚洲区长春站-重现赛(感谢东北师大)
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 50;
int a[maxn];
int d1[maxn];
int d2[maxn];
int b[maxn];
int n;
int Find1(int l,int r,int x)
{
while(l <= r)
{
int mid = (l + r)>>1;
if(x >= d1[mid])
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
return l;
}
int Find2(int l,int r,int x)
{
while(l <= r)
{
int mid = (l + r)>>1;
if(x >= d2[mid])
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
return l;
}
int LIS1()
{
d1[1] = a[1];
int len = 1;
for(int i = 2; i <= n; i++)
{
int term;
if(a[i] >= d1[len])
{
len++;
d1[len] = a[i];
}
else
{
term = Find1(1,len,a[i]);
d1[term] = a[i];
}
}
return len;
}
int LIS2()
{
d2[1] = b[1];
int len = 1;
for(int i = 2; i <= n; i++)
{
int term;
if(b[i] >= d2[len])
{
len++;
d2[len] = b[i];
}
else
{
term = Find2(1,len,b[i]);
d2[term] = b[i];
}
}
return len;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
scanf("%d",&a[i]);
b[n + 1 - i] = a[i];
}
int len1 = LIS1();
int len2 = LIS2();
//cout<<"len1="<<len1<<endl;
if(len1 >= n - 1||len2 >= n - 1)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}