点击打开题目
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others) Total Submission(s): 2375 Accepted Submission(s): 590
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 , is it almost sorted?
Input
The first line contains an integer indicating the total number of test cases. Each test case starts with an integer in one line, then one line with integers . There are at most 20 test cases with .
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
Source
2015ACM/ICPC亚洲区长春站-重现赛(感谢东北师大)
不知道序列是升序还是降序,正反做两次 LIS 就行了。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAX 100000
#define INF 0x3f3f3f3f
int main()
{
int u;
int n;
int a[MAX+11];
int g[MAX+11];
int ans; //LIS
scanf ("%d",&u);
while (u--)
{
scanf ("%d",&n);
for (int i = 1 ; i <= n ; i++)
scanf ("%d",&a[i]);
if (n == 2 || n == 3)
{
printf ("YES\n");
continue;
}
//由于不知道升序还是降序,那就正反做两次LIS
int pos;
ans = 0;
fill(g+1 , g+n+1 , INF);
for (int i = 1 ; i <= n ; i++)
{
pos = upper_bound(g+1 , g+1+n , a[i]) - g;
ans = max (pos , ans);
g[pos] = min (g[pos] , a[i]);
}
if (ans >= n - 1)
{
printf ("YES\n");
continue;
}
fill(g+1 , g+n+1 , INF); //正序不行,反向LIS
ans = 0;
for (int i = n ; i >= 1 ; i--)
{
pos = upper_bound (g+1 , g+1+n , a[i]) - g;
ans = max (pos , ans);
g[pos] = min (g[pos] , a[i]);
}
if (ans >= n - 1)
printf ("YES\n");
else
printf ("NO\n");
}
return 0;
}