Almost Sorted Array

时间:2023-03-08 16:48:55

http://acm.hdu.edu.cn/contests/contest_showproblem.php?cid=646&pid=1006

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
const int maxn=1e5+;
int ac[maxn],flag,n;
int Increase()
{
int ans,index;
ans=index=;
for(int i=; i<=n; i++)
{
if(ac[i]<ac[i-])
{
ans++;
index=i;
}
}
if(ans==)
flag=;
if(ans==)
{
if(index==n || index== || ac[index-] <= ac[index+] || ac[index-] <= ac[index] )
flag=;///如果这个不满足元素的左边和右边还是非递减的,那么可以去掉该元素,或者该元素前的第二个元素和该元素是非递减的,可以去掉该元素之前的第一个元素
}
if(flag==)
return ;
return ;
}
int Decrease()
{
int ans,index;
ans=index=;
for(int i=; i<=n; i++)
{
if(ac[i]>ac[i-])
{
ans++;
index=i;
}
}
if(ans==)
flag=;
if(ans==)
{
if(index== || index==n || ac[index-]>=ac[index+] || ac[index-]>=ac[index])
flag=;
}
if(flag)
return ;
return ;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
flag=;
scanf("%d",&n);
for(int i=; i<=n; i++)
scanf("%d",&ac[i]);
if(Decrease())//先判断是否是递增序列;找到不满足条件的元素下标,并统计个数,个数<=1时才满足条件
printf("YES\n");
else if(Increase())//如果不是递增在判断其是否是递减序列
printf("YES\n");
else
printf("NO\n");
}
return ;
}
ps : 4 4 1 2 3
4 4 2 7 3
4 4 7 2 3
5 1 2 6 4 5
4 1 1 0 1 1
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.

1≤T≤2000
2≤n≤105
1≤ai≤105
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