首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【HDU】5532 - Almost Sorted Array(LIS)

【HDU】5532 - Almost Sorted Array(LIS)

作者头像
FishWang
发布2025-08-27 09:12:31
发布2025-08-27 09:12:31
11900
代码可运行
举报
运行总次数:0
代码可运行

点击打开题目

Almost Sorted Array

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

代码语言:javascript
代码运行次数:0
运行
复制
   3
3
2 1 7
3
3 2 1
5
3 1 4 1 5

Sample Output

代码语言:javascript
代码运行次数:0
运行
复制
   YES
YES
NO

Source

2015ACM/ICPC亚洲区长春站-重现赛(感谢东北师大)

不知道序列是升序还是降序,正反做两次 LIS 就行了。

代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-07-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Almost Sorted Array
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档