B. Mike and Feet(单调栈)

 

有 n 个数,每次选择区间长度 i (i ∈[1,n]),当区间长度为 i 时,找出所有区间长度为 i 的区间内的最小值,将这 几个数中的最大值作为答案 

利用栈顶最大的单调栈求解,对于每一个数 a[i] 都可以向左向右找出第一个小于它的元素位置,那么 a[i] 作为此区间内的最小值进行最后的比较 

const int N=2e5+5;
 
    int n,m,t;
    int i,j,k;
    int a[N];
    stack<int> s;
    int l[N],r[N],ans[N];

int main()
{
    //IOS;
    while(sd(n)==1){
        for(i=1;i<=n;i++) sd(a[i]);
        for(i=1;i<=n;i++){
            while( s.size() && a[s.top()]>=a[i]) s.pop();
            if(s.empty()) l[i]=0;
            else l[i]=s.top();
            s.push(i); 
        }
        stack<int> hollow;
        swap(hollow,s);
        for(i=n;i;i--){
            while( s.size() && a[s.top()]>=a[i] ) s.pop();
            if(s.empty()) r[i]=n+1;
            else r[i]=s.top();
            s.push(i);
        }
        for(i=1;i<=n;i++){
            int len=r[i]-l[i]-1;
            ans[len]=max(ans[len],a[i]);
        }
        for(i=n-1;i;i--) ans[i]=max(ans[i],ans[i+1]);
        for(i=1;i<=n;i++) printf("%d%c",ans[i],i==n?'\n':' ');
    }
    //PAUSE;
}

 

猜你喜欢

转载自blog.csdn.net/C_Dreamy/article/details/107728115