Problem Description:
We is all familiar with sorting algorithms:quick sort, merge sort, heap sort, insertion sort, selection sort, bubble sor T, etc. But sometimes it was an overkill to use these algorithms for an almost sorted array.
We say an array was sorted if its elements be in non-decreasing order or non-increasing order. We say an array are almost sorted if we can remove exactly one element from it, and the remaining array is sorted. Now is given an array a1,a2,... ,an, is it almost sorted?Input:the first line contains an integerTindicating the total number of test cases. Each test case starts with an integerNIn one line, then one line withNIntegersa1,a2,... ,an .
1≤T≤
2≤n≤5
< Span id= "mathjax-span-57" class= "Mrow" >1 ≤ Ai≤105
There is at the most test cases With < Span id= "mathjax-span-68" class= "Mrow" >n >1000 . Output:for Each test case, please output "' YES '" if it is almost sorted. Otherwise, Output "' NO '" (both without quotes). Sample input:332 1 733 2 153 1 4 1 5 Sample Output:yesyesno
Test instructions: Gives a sequence that, if one element is removed, asks if the remaining sequence is an ordered sequence.
#include <stdio.h>#include<string.h>#include<queue>#include<math.h>#include<stdlib.h>#include<algorithm>using namespacestd;Const intn=1e5+Ten;Const intinf=0x3f3f3f3f;Const intmod=1e9+7; typedefLong LongLL;intA[n], flag;voidIncrease (intN) { inti, NUM, idex; Num= Flag =0; for(i =2; I <= N; i++) { if(A[i] < a[i-1]) {num++; Idex= i;///Mark subscript that does not satisfy an element } } if(num = =0) flag =1; if(num = =1) { if(Idex = = N | | idex = =2|| a[idex-2] <= A[idex] | | a[idex-1] <= a[idex+1]) Flag=1;///If this does not satisfy the left and right side of the element, then the element can be removed, or the second element before the element and the element is non-decremented, the first element before the element can be removed }}voidDecrease (intN) { intidex, I, num; Num= Flag =0; for(i =2; I <= N; i++) { if(A[i] > a[i-1]) {num++; Idex=i; } } if(num = =0) flag =1; if(num = =1) { if(Idex = =2|| Idex = = N | | a[idex-1] >= a[idex+1] || a[idex-2] >=A[idex]) flag=1; }}intMain () {intT, I, N; scanf ("%d", &T); while(t--) {scanf ("%d", &N); for(i =1; I <= N; i++) scanf ("%d", &A[i]); Increase (n); ///First judge whether the non-descending sequence: Find the element subscript, and count the number<=1 only when the conditions are metif (flag = = 0) decrease (n);///if it is not a non-descending sequence then judge whether it is a non-incrementing sequence if(Flag = =1) printf ("yes\n"); Elseprintf"no\n"); } return 0;}
2015ACM/ICPC Asia Changchun Station-replay 1006 almost Sorted Array