题目:

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;
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐