zoukankan      html  css  js  c++  java
  • 洛谷 P5922 [COCI 2011] Dvoniz(双指针,单调性)

    传送门


    解题思路

    非常好的一道题。

    一开始错误的认为对于一个确定的左端点,合法的区间一定是右面的一个前缀。

    但事实上并不是。

    因为区间[k+1,2k]的起点不确定,所以不满足单调性。

    所以正确的解法是先看区间[1,k],找到最大的k(因为这个区间满足单调性),然后回滚,看看最大k是多少可以使[k+1,2k]也满足条件。

    可以证明,回滚的次数是O(n)的,所以最后的总复杂度也是O(n)的。

    关于证明,推荐此博客

    AC代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    #include<vector>
    #include<queue>
    #include<map>
    #include<bitset>
    #include<stack>
    using namespace std;
    template<class T>inline void read(T &x)
    {
        x=0;register char c=getchar();register bool f=0;
        while(!isdigit(c))f^=c=='-',c=getchar();
        while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
        if(f)x=-x;
    }
    template<class T>inline void print(T x)
    {
        if(x<0)putchar('-'),x=-x;
        if(x>9)print(x/10);
        putchar('0'+x%10);
    }
    const int maxn=1e5+5;
    int n,r,mid;
    long long s,a[maxn],d[maxn];
    int main(){
    	ios::sync_with_stdio(false);
    	cin>>n>>s;
    	for(int i=1;i<=n;i++){
    		cin>>a[i];
    		d[i]=d[i-1]+a[i];
    	}
    	for(int i=1;i<=n;i++){
    		if(mid<i) mid=i;
    		r=mid+mid-i+1;
    		while(r<=n&&d[mid]-d[i-1]<=s) mid++,r+=2;
    		r-=2;
    		mid--;
    		while(mid>=i&&d[r]-d[mid]>s) mid--,r-=2;
    		cout<<r-i+1<<endl;
    	}
    	return 0;
    }
    
  • 相关阅读:
    Rescue_BFS
    Gnome Tetravex_DFS
    Tian Ji -- The Horse Racing_贪心
    A Walk Through the Forest_spfa&&dfs
    迷宫城堡_逆置图&&DFS*2
    Wooden Sticks_贪心
    compute post expression
    infix to postfix 完整版
    Infix to postfix without '(' and ')'
    infix expression 计算完全版
  • 原文地址:https://www.cnblogs.com/yinyuqin/p/15519966.html
Copyright © 2011-2022 走看看