CodeForces-1313C2 Skyscrapers (hard version) monotonic stack

CodeForces - 1313C2 Skyscrapers (hard version)

Original title address:

http://codeforces.com/contest/1313/problem/C2

Topic:

Given the upper limit of the size that can be set for each position, you need to set the actual size for each position to satisfy j <i <k and aj> ai <ak (j and k are not required to be adjacent to i) .
In other words, find a center point that satisfies the non-decreasing on the left and non-increasing on the right to construct the actual size of each point to maximize their sum.

The basic idea:

The monotonic stack is first maintained from the left to maintain the interval [1-i] at each position i. The maximum value obtained by non-decreasing is recorded in l [i]; similarly from the right maintenance interval [N-i] can be obtained by non-decreasing The maximum value of is recorded in r [i].
Then the actual sum that can be obtained when the position i is the center point is r [i] + l [i]-a [i], take the position where the maximum value is located as the center, and construct the answer to both sides according to the conditions.

Reference Code:

#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define INF 0x3f3f3f3f

const int maxn = 5e5+10;
int n,a[maxn],l[maxn],r[maxn],res[maxn];
signed main() {
    IO;
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];
    vector<int> q;
    q.push_back(0);
    for (int i = 1; i <= n; i++) {
        while (!q.empty() && a[q.back()] >= a[i]) q.pop_back();
        int t = q.back();
        l[i] = l[t] + a[i] * (i - t);
        q.push_back(i);
    }
    q.clear();
    q.push_back(n+1);
    for (int i = n; i >= 1; i--) {
        while (!q.empty() && a[q.back()] >= a[i]) q.pop_back();
        int t = q.back();
        r[i] = r[t] + a[i] * (t - i);
        q.push_back(i);
    }
    int ans = 0, pos = 0;
    for (int i = 1; i <= n; i++) {
        int temp = l[i] + r[i] - a[i];
        if (temp > ans) {
            ans = temp, pos = i;
        }
    }
    res[pos] = a[pos];
    for (int i = pos - 1; i >= 1; i--) res[i] = min(a[i], res[i + 1]);
    for (int i = pos + 1; i <= n; i++) res[i] = min(a[i], res[i - 1]);
    for (int i = 1; i <= n; i++) cout << res[i] << " ";
    cout << endl;
    return 0;
}


Published 23 original articles · won 7 · visited 1748

Guess you like

Origin blog.csdn.net/weixin_44164153/article/details/104486676