Smallest Sub Array-hihocoder-tiger

来源:互联网 发布:淘宝上的香皂花有毒吗 编辑:程序博客网 时间:2024/05/10 17:33

Given an array of integers A, find the smallest contiguous sub array B of A such that when you sort B in ascending order the whole array A becomes sorted as well.

For example if A = [1, 2, 3, 7, 4, 6, 5, 8] the smallest B will be [7, 4, 6, 5].  

输入

The first line contains an integer N denoting the length of A. (1 <= N <= 100000)

The second line contains N integers denoting the array A. (0 <= Ai <= 100000000)

输出

The length of the smalltest sub array B.

样例输入
8  1 2 3 7 4 6 5 8
样例输出
           4
#include <bits/stdc++.h>using namespace std;const int MAXN = 100010;int chary[MAXN];int main(){    freopen("in.txt", "r", stdin);    int n, beg, endd;    beg = endd = 0;    int ans = 0;    cin>>n;    for( int i=0 ; i<n ; i++ )        cin>>chary[i];    int i,j;    for( i=0 ; i<n-2 ; i++ )    {            if( chary[i] > chary[i+1] )            {                beg = i;                break;            }    }    for( i=n-2 ; i>=beg ; i-- )    {        if( chary[i] > chary[i+1] )        {            endd = i;            break;        }    }    sort( chary+beg, chary+endd+1 );    int tmpmax = chary[endd];    j = endd;    for( i=n-1 ; i>= j ; i-- )    {        if( chary[i] < tmpmax )        {            endd = i;            break;        }    }    ans =  beg!=endd ? endd - beg + 1 : 0 ;    cout<<ans<<endl;    return 0;}

0 0
原创粉丝点击