CodeForces 547B (monotonic stack)

Title

For a sequence of n elements, the minimum value of not consecutive l elements is the strength value of this string, find the maximum value of the strength of all consecutive l elements.

analysis

If a[i] is the strength value of the string it is in, then it must be the minimum value. Go forward and backward to find the first position l and r less than it. Obviously the strength of the interval [l + 1, r + 1] Equal to a[i].
You can update the strength of len (len = r-l + 1). In addition, the strength value of length i must not be greater than the strength value of length (i-1).

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;
}

Guess you like

Origin blog.csdn.net/KIJamesQi/article/details/52232778