C++ serial interval number (enumeration)

Xiao Ming has been thinking about such a strange and interesting question these days:
how many consecutive intervals are there in a certain permutation from 1 to N?
The definition of the serial interval mentioned here is:
if all the elements in the interval [L,R] (that is, the Lth to Rth elements of this arrangement) are sorted ascendingly, a length of R−L+1 can be obtained The "continuous" sequence is called this interval consecutive number interval.
When N is very small, Xiao Ming can quickly calculate the answer, but when N becomes large, the problem is not so simple. Now Xiao Ming needs your help.
Input format The
first line is a positive integer N, indicating the scale of the arrangement.
The second line is N different numbers Pi, representing a certain arrangement of these N numbers.
Output format
Output an integer, which represents the number of different consecutive intervals.
Data range
1≤N≤10000,1≤Pi≤N
Input example 1: *
4
3 2 4 1
Output example 1:
7
Input example 2:
5

If you pay attention to the arrangement of these two words, the idea of ​​this question will be solved. The arrangement shows that each number only appears once. When the length of the interval is known, only the difference of the highest value in the interval can be judged whether it is a consecutive interval.
AC code:

#include<stdio.h>
#include<algorithm>

using namespace std;

int n;
int a[10010];
int maxv,minv;//所枚举区间内最值
int ans=0;

int main()
{
    
    
    scanf("%d",&n);
    for(int i=1;i<=n;++i) scanf("%d",&a[i]);
    for(int i=1;i<=n;++i)//枚举左端点
    {
    
    
        maxv=-0x7f7f7f7f;minv=0x7f7f7f7f;
        for(int j=i;j<=n;++j)//枚举右端点
        {
    
    
            maxv=max(maxv,a[j]);minv=min(minv,a[j]);
            if(maxv-minv==j-i) ++ans;
        }
    }
    printf("%d",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108853166