zoukankan      html  css  js  c++  java
  • POI2015 WIL-Wilcze doły

    题目传送门

    很不错的一道单调队列神题


    可以发现,当我们向右移动右端点时,左端点也会向右移动或不动。所以我们可以从左向右移动右端点,以上一个区间的左端点作为这个区间的左端点,然后将左端点右移,直到这个区间为一个合法区间。

    为了判断区间是否合法,我们可以维护每个元素的前缀和,从而得到每段长为(d)的区间的和。之后移动左端点时,就可以用这段区间的区间和减去区间内长度为(d)的最大区间和。

    快速求出长度为(d)的最大区间,我们可以用单调队列来维护。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #define LL long long
    using namespace std;
    LL read(){
    	LL k=0,f=1; char c=getchar();
    	for(;c<'0'||c>'9';c=getchar())
    	  if(c=='-') f=-1;
    	for(;c>='0'&&c<='9';c=getchar())
    	  k=k*10+c-48;
    	return k*f;
    }
    LL a[2000010],sum[2000010];
    LL q[2000010],h=1,t;
    int main(){
    	LL n=read(),p=read(),d=read();
    	for(int i=1;i<=n;i++) a[i]=read()+a[i-1];  //前缀和
    	for(int i=d;i<=n;i++) sum[i]=a[i]-a[i-d];  //长度为d,右端点为i的区间和
    	int ans=d,last=1; q[++t]=d;  //初始化
    	for(int i=d+1;i<=n;i++){
    		while(sum[q[t]]<sum[i]&&h<=t) --t;  //维护单调队列
    		q[++t]=i;
    		while(q[h]-d+1<last&&h<=t) ++h;  //当最大值的左端点不在这个区间里,需要将它出队
    		while(h<=t&&a[i]-a[last-1]-sum[q[h]]>p){ //向右移动左端点,直到区间合法
    			last++;
    			while(q[h]-d+1<last&&h<=t) ++h;  //随着左端点右移,要时刻注意最大值的合法性
    		}
    		ans=max(ans,i-last+1);
    	}
    	cout<<ans;
    	return 0;
    }
    
  • 相关阅读:
    DataGridView如何获取某个数据
    扩展方法
    base和this关键字
    装箱和拆箱
    var,object和dynamic
    const和readonly
    react native回调函数刷新页面
    react native打包android,android9.0以上版本http请求不了怎么办?
    react native中android app怎样打包发布
    React Native 实现页面返回监听
  • 原文地址:https://www.cnblogs.com/morslin/p/11854907.html
Copyright © 2011-2022 走看看