CodeForces 547B (单调栈)

题意

一个有n个元素的序列,没连续l个元素的最小值为这个串的strength值,求所有连续l个元素的strength是的最大值。

分析

a[i]如果是其所在串的strength值,那么必然它是最小值,往前和往后找小于它的第一个位置l、r,显然[l + 1, r + 1]区间的strength等于a[i]。
就可以更新长度为len(len = r - l + 1)的strength。还有就是长度为i的strength值一定不大于长度为(i - 1)的strength值。

const int maxn = 2e5 + 10;
int a[maxn];
int ans[maxn];
int pre[maxn];
int nxt[maxn];
int n;
int main(int argc, const char * argv[])
{    
    // freopen("in.txt","r",stdin);
    // freopen("out.txt","w",stdout);
    // ios::sync_with_stdio(false);
    // cout.sync_with_stdio(false);
    // cin.sync_with_stdio(false);

    cin >> n;
    Rep(i, 1, n) scanf("%d", &a[i]);
    vector<int> st;
    Rep(i, 1, n) {
        while(!st.empty() && a[st.back()] >= a[i]) st.pop_back();
        st.empty() ? pre[i] = 0 : pre[i] = st.back();
        st.push_back(i);
    }
    st.clear();
    Rrep(i, n, 1) {
        while(!st.empty() && a[st.back()] >= a[i]) st.pop_back();
        st.empty() ? nxt[i] = n + 1 : nxt[i] = st.back();
        st.push_back(i);
    }
    Rep(i, 1, n) {
        int l = pre[i] + 1;
        int r = nxt[i] - 1;
        int len = r - l + 1;
        ans[len] = max(ans[len], a[i]);
    }
    Rrep(i, n, 1) ans[i - 1] = max(ans[i - 1], ans[i]);
    Rep(i, 1, n) printf("%d%c", ans[i], i == n ? '\n' : ' ');
    return 0;
}

猜你喜欢

转载自blog.csdn.net/KIJamesQi/article/details/52232778