zoukankan      html  css  js  c++  java
  • 连号区间数

    小明这些天一直在思考这样一个奇怪而有趣的问题:

    在1~N的某个全排列中有多少个连号区间呢?这里所说的连号区间的定义是:

    如果区间[L, R] 里的所有元素(即此排列的第L个到第R个元素)递增排序后能得到一个长度为R-L+1的“连续”数列,则称这个区间连号区间。

    当N很小的时候,小明可以很快地算出答案,但是当N变大的时候,问题就不是那么简单了,现在小明需要你的帮助。

    输入格式

    第一行是一个正整数N (1 <= N <= 50000), 表示全排列的规模。

    第二行是N个不同的数字Pi(1 <= Pi <= N), 表示这N个数字的某一全排列。

    输出格式

    输出一个整数,表示不同连号区间的数目。

    样例输入1

    4
    3 2 4 1
    

    样例输出1

    7 
    

    样例输入2

    5
    3 4 2 5 1
    

    样例输出2

    9 
    由于给出的是一个全排列,每个数都不一样,如果一个区间的最大值和最小值的差是区间大小,那么就满足条件。
    代码:
    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    using namespace std;
    int n;
    int s[50001];
    int main() {
        scanf("%d",&n);
        for(int i = 0;i < n;i ++) {
            scanf("%d",&s[i]);
        }
        int c = 0;
        for(int i = 0;i < n;i ++) {
            int m1 = s[i],m2 = s[i];
            for(int j = i;j < n;j ++) {
                m1 = min(m1,s[j]);
                m2 = max(m2,s[j]);
                if(m2 - m1 == j - i) c ++;
            }
        }
        printf("%d",c);
    }
    import java.util.Scanner;
    
    public class Main {
        private static Scanner sc = new Scanner(System.in);
        private static int n;
        private static int [] s = new int[50000];
        
        public static void main(String[] args) {
            int c = 0;
            n = sc.nextInt();
            for(int i = 0;i < n;i ++) {
                s[i] = sc.nextInt();
            }
            for(int i = 0;i < n;i ++) {
                int min = s[i],max = s[i];
                for(int j = i;j < n;j ++) {
                    min = Math.min(min, s[j]);
                    max = Math.max(max, s[j]);
                    if(j - i == max - min) c ++;
                }
            }
            System.out.println(c);
        }
    
    }
  • 相关阅读:
    微信小程序登入实现
    CacheLab实验--深入了解计算机系统实验
    power designer的物理数据模型生成数据字典。
    PowerDesigner15在生成SQL时报错Generation aborted due to errors detected during the verification of the mo
    Mac系统下,如何申请并安装教育版Navicat
    Mac下修改Mysql密码
    数组
    AbstractList源码阅读
    List源码阅读笔记
    AbstractCollection源码阅读笔记
  • 原文地址:https://www.cnblogs.com/8023spz/p/10300669.html
Copyright © 2011-2022 走看看