hdu 5532 Almost Sorted Array

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5532

Almost Sorted Array

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


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的数列,让你从中删除一个数,使这个数列变成非递减或者非递增(数列中可能有重复的数)
题解:对数列正反各求一次LIS(最长上升子序列(这里要将相等的数也考虑进去))再拿n减去最长上升子序列的长度,小于等于1输出YES
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
#include<math.h>
#define MAX 100100
#define INF 0x3f3f3f
#define DD double
using namespace std;
int stack[MAX];
int top;
int f(int x)//二分 查找栈中第一个大于x的数 
{
	int l=0,r=top;
	int mid;
	while(r>=l)
	{
		mid=(l+r)/2;
		if(x>=stack[mid])
		    l=mid+1;
		else
		    r=mid-1;
	}
	return l;
} 
int main()
{
	int t,n,m,j,i,k;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		int s[MAX];
		for(i=1;i<=n;i++)
		    scanf("%d",&s[i]);
		
		top=0;
		stack[0]=-1;
		for(i=1;i<=n;i++)
		{
			if(s[i]>=stack[top])
			    stack[++top]=s[i];
			else
				stack[f(s[i])]=s[i];
		}
		int ans=top;
		
		memset(stack,0,sizeof(0)); 
		top=0;
		stack[0]=-1;
		for(i=n;i>=1;i--)
		{
			if(s[i]>=stack[top])
			    stack[++top]=s[i];
			else
				stack[f(s[i])]=s[i];
		}
		int ant=top;
		if(n-ant<=1||n-ans<=1)
		printf("YES\n");
		else
		printf("NO\n");
	} 
	return 0;
} 

  

posted @ 2015-12-10 16:23  非我非非我  阅读(210)  评论(0编辑  收藏  举报