您的位置:首页 > 其它

HDOJ 5532 Almost Sorted Array (正反LIS判断顺序)

2015-11-02 13:30 316 查看

Almost Sorted Array

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

Total Submission(s): 235    Accepted Submission(s): 113


[align=left]Problem Description[/align]
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 arraya1,a2,…,an,
is it almost sorted?
 

[align=left]Input[/align]
The first line contains an integer
T
indicating the total number of test cases. Each test case starts with an integern
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.
 

[align=left]Output[/align]
For each test case, please output "`YES`" if it is almost sorted. Otherwise, output "`NO`" (both without quotes).
 

[align=left]Sample Input[/align]

3
3
2 1 7
3
3 2 1
5
3 1 4 1 5

 

[align=left]Sample Output[/align]

YES
YES
NO

大意:判断一组数是否为排过序的或者去掉一个数为排过序的

思路:正反两次LIS,判断最长递增子序列的长度和数的数量,满足n-1<=len-1即可,要用nlogn的做法,普通的超时
之前写一直不对,然后第二天就重新写了一遍,A了,醉醉的。。。

ac代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#define MAXN 100100
#define MOD 1000000007
#define LL long long
#define INF 0xfffffff
using namespace std;
int dp[MAXN];
int num[MAXN];
int num1[MAXN];
int main()
{
int t,n;
int i,len,k;
scanf("%d",&t);
while(t--)
{
len=1;
k=1;
int bz=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&num[i]);
num1[n+1-i]=num[i];
}
for(i=1;i<=n;i++)
{
if(len==k)
{
dp[len++]=num[i];
continue;
}
if(dp[len-1]<=num[i])
{
dp[len++]=num[i];
continue;
}
int low=1,high=len-1;
while(low<=high)
{
int mid=(low+high)/2;
if(num[i]>=dp[mid])
low=mid+1;
else
high=mid-1;
}
dp[low]=num[i];
}
if((n-1<=len-1))
{
bz=1;
}
len=1;
k=1;
for(i=1;i<=n;i++)
{
if(len==k)
{
dp[len++]=num1[i];
continue;
}
if(dp[len-1]<=num1[i])
{
dp[len++]=num1[i];
continue;
}
int low=1,high=len-1;
while(low<=high)
{
int mid=(low+high)/2;
if(num1[i]>=dp[mid])
low=mid+1;
else
high=mid-1;
}
dp[low]=num1[i];
}
if(n-1<=len-1)
{
bz=1;
}
printf(bz?"YES\n":"NO\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: