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;
}
發佈了304 篇原創文章 · 獲贊 7 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章