codeforces-547B Mike and Feet(单调栈)

题意:
给一段序列,要求分别输出长度为1-n的子串中最大的最小值

题解:
用单调栈求出每一个数往左和往右第一个比他小的数,这样当该数字作为答案时,他就是最小值。 需要注意的是,长度短的答案由长度长的答案确定,比如长度为4的答案为10,那么当用单调栈求得长度为3的答案比10小时那么应该取10作为长度为3的答案,因为可以从长度为4的字串中取一个长度为3的包含10的字串。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<map>
using namespace std;

long long L[200010], R[200010];
long long n, a[200010];

stack<long long> s;
map<long long, long long> ma;

int main(){
    cin>>n;
    for(int i = 1; i<=n; i++){
        cin>>a[i];
    }

    for(int 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);
    }
    while(s.size()) s.pop();

    for(int i = n; i>=1; 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(int i = 1; i<=n; i++){
        cout<<i<<": "<<a[i]<<" "<<L[i]<<" "<<R[i]<<endl;
    }*/

    for(int i = 1; i<=n; i++){
        long long len = R[i]-L[i]-1;
        ma[len] = max(ma[len], a[i]);
    }
    //long long temp = ma[n];
    for(int i = n-1; i>=1; i--){
        ma[i] = max(ma[i+1], ma[i]);
    }
    for(int i = 1; i<=n; i++){
        cout<<ma[i];
        if(i == n) cout<<endl;
        else cout<<" ";
    }



    return 0;
}

猜你喜欢

转载自blog.csdn.net/GrimCake/article/details/80377375