zoukankan      html  css  js  c++  java
  • FZU 2016 summer train I. Approximating a Constant Range 单调队列

    题目链接:

    题目

    I. Approximating a Constant Range
    time limit per test:2 seconds
    memory limit per test:256 megabytes

    问题描述

    When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?

    You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.

    A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.

    Find the length of the longest almost constant range.

    输入

    The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points.

    The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

    输出

    Print a single number — the maximum length of an almost constant range of the given sequence.

    样例

    input
    5
    1 2 3 3 2

    output
    4

    input
    11
    5 4 5 5 6 7 8 8 8 7 6

    output
    5

    题意

    求最大值最小值相差小于2的最大区间长度

    题解

    这一题由于相邻的数据最多差一,可以直接做,但是这里贴一个单调队列的模板吧,毕竟更通用,
    开两个单调队列来维护窗口最大最小值。(这里的实现是有先队列+时间戳)下标其实就相当于时间戳了,对于窗口l,r,小于l的都是过期的。

    代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<queue> 
    #define X first
    #define Y second
    #define mp make_pair
    using namespace std;
    
    typedef __int64 LL;
    const int maxn=1e5+10;
    int arr[maxn];
    priority_queue<pair<int,int> > mi,ma;
    
    int main(){
    	int n;
    	scanf("%d",&n);
    	for(int i=0;i<n;i++) scanf("%d",&arr[i]);
    	int l=0,r=0;
    	int ans=-1;
    	while(r<n){
    		mi.push(mp(-arr[r],r));
    		ma.push(mp(arr[r],r));
    		while(-mi.top().X<ma.top().X-1){
    			l++;
    			while(mi.top().Y<l) mi.pop();
    			while(ma.top().Y<l) ma.pop();
    		}
    		ans=max(ans,r-l+1);
    		r++;
    	}
    	printf("%d
    ",ans);
    	return 0;
    }
  • 相关阅读:
    Django + Uwsgi + Nginx 的概念
    ubantu+nginx+uwsgi+django部署
    FileZilla以root用户登录Linux
    全文检索django-haystack+jieba+whoosh
    七牛云上传视频
    JWT登录与多方式登录
    vue绑定用户页面
    绑定微博用户接口
    vue微博回调空页面
    微博回调接口
  • 原文地址:https://www.cnblogs.com/fenice/p/5675154.html
Copyright © 2011-2022 走看看