Almost Sorted Array(合适数列)

题目:

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 a_1,a_2,…,a_na1​,a2​,…,an​, is it almost sorted?

Input Format

The first line contains an integer TT indicating the total number of test cases.

Each test case starts with an integer nn in one line, then one line with nn integers a_1,a_2,…,a_na1​,a2​,…,an​.

• 1 \le T \le 20001≤T≤2000

• 2\le n\le 10^52≤n≤105

• 1 \le a_i \le 10^51≤ai​≤105

• There are at most 2020 test cases with n > 1000n>1000.

Output Format

For each test case, please output "YES" if it is almost sorted. Otherwise, output "NO" (both without quotes).

样例输入复制

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

样例输出复制

YES
YES
NO

分析:

每次假设是非递增或者非递减,然后碰到第一个不合适的,就判断分别将这两个隔开的的两个位置的是否满足,如果不满足就说明不能,但是自己最爱开始的代码一直没有过,参考了以为思路相同的老哥的代码终于过了;

代码:

#include<stdio.h>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn=100005;
int n,sor[maxn];
bool judge1()//第一次非递减
{
    int sum=0;
    sor[0]=-inf;
    sor[n+1]=inf;
    for(int i=2;i<=n;i++)
    {
        if(sor[i]<sor[i-1])
        {
            if(sum==1)
            return 0;
            sum++;
            if(sor[i+1]>=sor[i-1]||sor[i]>=sor[i-2])
                continue;
            else
                return 0;
        }
    }
    return 1;
}
bool judge2()//第二次非递增
{
    int sum=0;
    sor[0]=inf;
    sor[n+1]=-inf;
    for(int i=2;i<=n;i++)
    {
        if(sor[i]>sor[i-1])
        {
            if(sum==1)
            return 0;
            sum++;
            if(sor[i+1]<=sor[i-1]||sor[i]<=sor[i-2])
                continue;
            else
                return 0;
        }
    }
    return 1;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            scanf("%d",&sor[i]);
        if(judge1()||judge2())
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值