铜牌汇总2

来源:互联网 发布:装修招标网源码 编辑:程序博客网 时间:2024/04/27 18:17
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,,ana1,a2,…,an, is it almost sorted?
Input
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 a1,a2,,ana1,a2,…,an

1T20001≤T≤2000 
2n1052≤n≤105 
1ai1051≤ai≤105 
There are at most 20 test cases with n>1000n>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
#include<stdio.h>#include<string.h>int stack[100000];int top;int f(int x){    int l=0,r=top;    int mid;    while(r>=l)    {        mid=(l+r)/2;        if(x>=stack[mid])            l=mid+1;        else            r=mid-1;    }    return l;}int main(){    int t,n,m,j,i,k;    scanf("%d",&t);    while(t--)    {        scanf("%d",&n);        int s[100000];        for(i=1;i<=n;i++)            scanf("%d",&s[i]);                 top=0;        stack[0]=-1;        for(i=1;i<=n;i++)        {            if(s[i]>=stack[top])                stack[++top]=s[i];            else                stack[f(s[i])]=s[i];        }        int ans=top;                 memset(stack,0,sizeof(0));        top=0;        stack[0]=-1;        for(i=n;i>=1;i--)        {            if(s[i]>=stack[top])                stack[++top]=s[i];            else                stack[f(s[i])]=s[i];        }        int ant=top;        if(n-ant<=1||n-ans<=1)        printf("YES\n");        else        printf("NO\n");    }    return 0;}

原创粉丝点击